Criar post em um wordpress e trazer em outro wordpress automaticamente

Question: Opções:

Criar um novo POST em um wordpress-1, a partir de outro wordpress-2.

ou

Tudo que for criado no wordpress-2 ser "copiado" para o wordpress-1

ou

Criar/Cadastrar um produto em uma loja(site)-1, a partir de outra loja(site)-2. [RESOLVIDO]

Eu já usei o multsite integrado com o ThreeWP-Broadcast, mas apresenta bugs estranhos, tais como deslogar-se automaticamente do admin quando alterno o dashboard.

[UPDATE]
  Utilizar o mesmo banco, alterando lá no wp-config, não dar certo! Pois
  o wordpress trabalha com links permanentes e vai trazer uma URL fixa e
  no caso, não devo acessar o site 1 através do site 2, mas somente
  devem ter os mesmos post!
Comment: Você está falando de Multisite ou de dois WP independentes?
Comment: conseguiu resolver esse problema? fiquei curioso
Comment: Não, @CaioFelipePereira, mas vou analisar sua resposta. Vi agora.
Comment: WP independentes.
Answer: Fazer isso automaticamente me parece meio complicado, mas acho que é possível. A solução que eu vou sugerir não foi testada mas, em teoria, acho que deve funcionar. Vou chamar de w1 o WordPress no qual você quer criar o post, e de w2o WordPress que irá receber os posts, assim que eles forem criados no primeiro.

Mantenha a integridade entre os dois sites
Esse eu acredito que deveria ser o passo zero, mas enfim. Se você tem algum tipo de customização nos posts de w1, como meta data, custom fields e coisas do tipo, e não tem pelo menos a mesma estrutura no w2, o post que você está querendo duplicar não será duplicado 100% corretamente. Portanto, garanta que w2 tenha, no mínimo, todas as propriedades definidas por você em w1.
Crie um action hook para a publicação de posts em w1
O WP tem uma série de actions pré-definidas, e atrelar alguma funcionalidade a mais a elas é tido como a criação de um hook. A action que vamos usar é a publish_post. Do codex:

publish_post is an action triggered whenever a post is published, or if it is edited and the status is changed to publish.

Ou seja, toda vez que você publicar um post, alguma coisa (que você definir) vai acontecer. Em termos de código, esse é o esqueleto que você coloca no functions.php:
add_action('publish_post', 'replicar_post_em_w2');
function replicar_post_em_w2(){
    # code...
}

Basicamente, replicar_posts_em_w2() vai ser chamada no momento da publicação. Volto pra este método em breve.
Criar uma interface de inserção de posts em w2
Existe mais de um jeito de você fazer isso, mas um que eu particularmente gosto, é usando o plugin JSON API (A partir desse ponto, toda minha resposta baseia-se neste plugin). Ele proporciona métodos de consulta - que devolvem um JSON baseando-se em uma URL e em seus parâmetros - e também métodos de criação de posts (o que nos interessa), que funciona basicamente da mesma maneira. Você chama uma URL do tipo http://w2.com/api/create_post/?nonce=123abc&content=blablabla, e ele cria o post pra você. Falando especificamente deste plugin, existe um método chamado get_nonce() que deve ser usado pra gerar o nonce, que é um parâmetro necessário para o método create_post(). Leia sobre os pormenores do plugin aqui.
Chame, dentro do action hook, o seu método de inserção em w2
Agora que você já tem (ou deve ter) pronta, e testada, a estrutura de inserção de posts em w2, está na hora de construir o método de replicação propriamente dito. Como você vai trabalhar com um post, você deve fornecê-lo como parâmetro para este método. Dentro dele, você vai extrair o que você precisa do post que acabou de criar em w1, montar uma query string usando este método, e chamar a URL de inserção de w2 para que o processo se complete. De uma maneira bem simples, seu código seria:
function replicar_post_em_w2($post){
    $url_de_insercao = 'http://w2.com/api/create_post/?';

    $titulo = $post->title;
    $couteudo = $post->content;
    $nonce = '123abc';
    #... E por aí vai

    $query_params = array(
        'nonce' => $nonce,
        'title' => $title,
        'content' => $conteudo
    );

    $url_de_insercao .= http_build_query($query_params);

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url_de_insercao);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_exec($ch);

    curl_close($ch);

}

Note que usei cURL pra chamar o método de inserção em w2. Note também que o valor do nonce foi arbitrário. Você pode usar o cURL para fazer a requisição em w2 para pegar o valor correto. A lista de parâmetros de todos os métodos do plugin encontra-se na documentação.
Por fim, como agora o seu método recebe um parâmetro, você tem que alterar o add_action para:
add_action('publish_post', 'replicar_post_em_w2', 10, 1);

Onde 10 é a prioridade, e 1 é o número de argumentos de replicar_post_em_w2.

Acredito que, se você seguir esses passos, vai alcançar o seu objetivo. Claro que você vai ter um bom trabalho de debug pela frente, e a inserção dos posts pode ser meio chata, principalmente por conta do nonce. A construção da query pode ser meio complexa também, e se você estiver trabalhando com custom posts, talvez a inserção se complique um pouco. De qualquer maneira, a teoria é essa. Espero ter ajudado.
Comment: @PauloBoaventura felizmente minha carreira me levou para longe do wordpress e eu imagino (na verdade, espero) que as coisas tenham mudado bastante dentro dele e que essa resposta tenha deixado de ser coerente. Ademais, meu conhecimento no WP já é obsoleto. Sugiro que faça uma pesquisa nas APIs que são disponibilizadas e veja o que (ainda) faz sentido
Comment: Poderia atualizar? (Tinha que ser um Brasileiro para simplificar algo tão problemático....)
Answer: Conforme o (grande) Frank Bueltge, existem tres métodos para fazer isso:

WP API (JSON)
Feed (XML)
XMLRPC API

E, ainda segundo Bueltge, deveriamos priorizar o WP JSON API pois é a maneira mais moderna e está a ponto de ser incorporada no código base do WordPress. Porém, minha resposta é via XMLRPC, um método clássico do WP (para fazer trackbacks e pingbacks, publicar desde web ou desktop apps), e que normalmente recomenda-se desabilitar porque abre a porta a diversas tentativas de ataque [vide "segurança" ao final].
Observações:

este código é só uma prova de conceito; o post de origem é reproduzido no site destino, mas essa informação não é armazenada no site de origem;
um código completo teria que armazenar o ID do post "espelho" no site de origem. E, ao ser chamada outra vez, em vez de criar um novo post de novo, teria que atualizar o post "espelho" que foi criado primeiro e cujo ID armazenamos como add_post_meta ao fazer a reprodução;
o site destino devolve o ID do post espelho que foi criado, então a funcionalidade acima não é muito difícil, são necessários um pouco de jQuery e AJAX.

Plugin Destino
Instalado no site que vai receber o post duplicado.
<?php
/**
 * Plugin Name: (SOpt) Plugin de Destino
 * Description: Publicações DE outro site
 * Plugin URI: http://pt.stackoverflow.com/questions/66280
 * Version: 1.0
 * Author: brasofilo
 */

add_filter( 'xmlrpc_methods', 'xmlrpc_sopt_66280' );

function xmlrpc_sopt_66280( $methods ) {
    /* BLOQUEIO DE TODOS OS MÉTODOS, remova a seguinte linha para habilitar todos os métodos padão do WP */
    $methods = array();
    $methods['postFromOutside'] = 'outside_sopt_66280';
    return $methods;
}

function outside_sopt_66280( $args ) {
    // A ordem dos argumentos é importante!
    $username   = $args[0];
    $password   = $args[1];
    $data = $args[2];
    global $wp_xmlrpc_server;

    // Usuário correto?
    if ( !$user = $wp_xmlrpc_server->login( $username, $password ) ) {
        return $wp_xmlrpc_server->error;
    }

    // Titulo e custom fields do post
    $title = $data["title"];
    $custom_fields = $data["custom_fields"];

    // Formatar o novo post
    $new_post = array(
        'post_status' => 'draft',
        'post_title' => $title,
        'post_type' => 'post',
    );

    // Faz o insert do novo post
    $new_post_id = wp_insert_post( $new_post );
    foreach( $custom_fields as $meta_key => $values )
        foreach ( $values as $meta_value )
            add_post_meta( $new_post_id, $meta_key, $meta_value );
    // Devolve ID do novo post
    return $new_post_id;
}

Plugin de Origem
Instalado no site que vai criar post duplicado.
/wp-content/plugins/xml-post/xml-post.php
<?php
/**
 * Plugin Name: (SOpt) Plugin de Origem
 * Description: Publicações PARA outro site. CONFIGURAR 'user' e 'password' do Site Destino.
 * Plugin URI: https://wordpress.stackexchange.com/a/54875/12615
 * Version: 1.0
 * Author: brasofilo
 */

add_action( 'add_meta_boxes', 'wpse_54822_add_custom_box' );
add_action( 'admin_head', 'wpse_54822_script_enqueuer' );
add_action( 'wp_ajax_wpse_54822_custom_query', 'wpse_54822_custom_query' );
add_action( 'wp_ajax_nopriv_wpse_54822_custom_query', 'wpse_54822_custom_query' );

function wpse_54822_add_custom_box() {
    add_meta_box(
        'wpse_54822_sectionid',
        __( 'Page Attachments' ),
        'wpse_54822_inner_custom_box',
        'page'
    );
}

function wpse_54822_inner_custom_box() {
    global $post;
    ?>
        Post Me
    <?php
}

function wpse_54822_script_enqueuer() {
    global $current_screen;
    if( 'page' != $current_screen->id )
        return;
    wp_register_script( 'my-js', plugin_dir_url(__FILE__) . '/ajax-xmlrpc.js' );
    wp_enqueue_script( 'my-js' );
    wp_localize_script( 'my-js', 'wp_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

function wpse_54822_custom_query() {
    // Dados a enviar na chamada XML-RPC
    $data = array(
        "title" => 'titulo',
        "custom_fields" => 'custom_fields'
    );
    // Considerando que user e password são "admin" e "admin"
    // E que o método postFromOutside é o que está definido no Plugin Destino
    $params = array( 'admin', 'admin', $data );
    $params = xmlrpc_encode_request( 'postFromOutside', $params );
    // Iniciar a requisição HTTP
    $request = new WP_Http;
    $result = $request->request(
        'http://plugins.dev/xmlrpc.php',
        array('method' => 'POST', 'body' => $params )
    );
    // O retorno XML é EXTREMAMENTE ESPECÍFICO e depende do Plugin de Origem
    $xml = simplexml_load_string( $result['body'] );
    wp_send_json_success( $xml->params->param->value->int );
}

/wp-content/plugins/xml-post/ajax-xmlrpc.js
/**
 * Arquivo JS que acompanha o plugin XML-POST.PHP
 * O objeto wp_ajax é enviado pelo wp_localize_script
 * A propriedade the_id é somente ilustrativa
 */
jQuery(document).ready(function($) {
    $('#post-me').click(function(){
        $.post(
            wp_ajax.ajaxurl,
            {
                action: 'wpse_54822_custom_query',
                the_id: 'toast'
            },
            function(data){
                console.log('Novo Post:',data.data[0]);
            }
        );
    });
});

[Segurança]

Crie um usuário no Site Destino somente para a conexão XMLRPC; pode usar  nome  e senha tipo 128bits; ou seja, bem complicados.
Talvez queira armazenar user e password em um arquivo de configuração fora da pasta public_html e fazer um require/include para puxar isso .
Pelo que vi, tem alguns métodos específicos que são alvos preferidos de ataques DDoS e a prevenção é fazer o unset() desse métodos. Com a linha $methods = array(); no Plugin de Destino estamos apagando todos os métodos padrão e adicionando só o nosso logo em seguida.
Sugiro duas ferramentas de segurança: o plugin WordFence e as regras de .htaccess 5G Blacklist 2013.

Referências:

Custom XML-RPC Methods in WordPress – Konstantin Kovshenin
How to get WordPress posts from a single category using XML-RPC
How to validate a user from ouside wordpress/php?
Comment: Perfeito. Resolvido.
Comment: @PauloBoaventura, não, esse código não lida com exportar/importar as imagens anexas ao post. Hoje em dia é melhor trabalhar com a WP Rest API, já está tudo bem documentado e existem bons exemplos no [so] e no [wordpress.se]
Comment: @brasofilo Poderia atualizar? Neste caso é " importado" as imagens?
Comment: @brasofilo me referia ao trazer o outro post automaticamente... As imagem anexas a estes posts vão para o outro post? São excluídas? ou fazem alguma referencia...  Teria a possibilidade de incorporar um código para que isso possa ser feito juntamente?
Comment: @PauloBoaventura Que eu saiba, isso só acontece ao fazer o export/import nativo do WordPress (é um arquivo XML). Certamente haverá plugins/serviços que oferecem isso. Quando você exporta um post, ele tem no HTML do conteúdo `` mas o XML do WP também exporta os "attachments". O export/import default do WP vai cuidar de fazer download da imagem e trocar a URL e cuidar de tudo mais. Qualquer outro export/import tem que ser explicito "Vou cuidar das imagens/anexos!", senão não vai fazer.
Comment: Aqui é uma gambiarra que arrumei pra importar arquivos/imagens da sua máquina para o servidor usando o XML do WP: https://wordpress.stackexchange.com/a/87407/12615
Answer: Você pode editar o arquivo wp-config.php nas duas instalações Wordpress para que eles apontem para o mesmo banco de dados.
Dessa forma, tudo que for criado através de um irá aparecer automaticamente no outro.
Comment: Sem maiores detalhes, esta resposta é uma receita perfeita para um problema bem grande.
Comment: Mas como vão apontar pro mesmo banco, se possuem URL diferentes? Digo...Quando for em uma interna, por exemplo, irei para a url que está no banco. `Site 1: www.site.com.br/wordpress` - `Site 2 :www.site.com.br/wordpress/mobile` - PODE ATUALIZAR A RESPOSTA?
Comment: @Lollipop ao invés do endereço do banco apontar para localhost ele pode apontar para a outra URL.
Comment: Mano, entenda...São dois wordpress. Quando eu obter o post do banco, NO SITE 2, ele vai me trazer `www.site.com.br/contato` que pertence ao site1 e vai me redirecionar para ele. Mas o problema é que o site 1 nunca deve ser aberto pelo site 2. Mas tudo que houver no site 1 deve haver no site 2. Ta claro?
Comment: Veja o update da minha pergunta.


Kill a SPID on SQL Server 2008

Question: We have a rogue SPID on a MS SQL Server 2008.
Is there a way to kill it without restarting the server?
Answer: KILL
Comment: This is one of the rare cases where violence *is* the answer.
Comment: @splattne: I should flag your comment for moderator review because it is glorifying violence, shouldn't I? ;)
Comment: @abaumg ☮ man...

Kill a SPID on SQL Server 2008


Finding the angle of two congruent isosceles triangles inscribed in a semi circle.

Question: Question
This question comes from Question 10 of the 2020 AIMO

A circle with centre $O$ has diameter $AD$. With $X$ on $AO$ and points $B$ and $C$ on the circle, triangles $ABX$ and $XCO$ are similar isosceles with base angle $\alpha$ as shown. Find, with proof, the value of $\alpha$.

My Attempt
I knew we probably have to use the fact that the isosceles triangles have a base on the diameter and vertex on the circle. Then $\angle ACD=\angle ABD=90^{\circ}$. Since $\angle ABX=180-2\alpha=\angle XBC$, then $AB||XC$.
Now, when constructing $CD$ and $BD$, I notice that $CD$ looked very much like the angle bisector of $\angle XCD$ and $BD$ looked very much like the angle bisector of $\angle CDA$. Let $CD$ and $BD$ intersect at $I$. I would need to prove that $I$ is in fact the incenter of $XCD$ to give a rigorous proof. Note that $\angle XCO=180-2\alpha$ and since $CO=OD$ (both a radius), then $\angle ODC=\angle COD=\frac{\alpha}{2}$. If $I$ were to be the incenter of $XCD$, then $\angle XCO=\angle OCD\implies 180-2\alpha=\frac{\alpha}{2}\implies \alpha=72^{\circ}$. This looked to be the right answer (could confirm with geogebra).
However, this is also the step that I am struggling to prove. I tried constructing the altitude of $\triangle XID$, $\triangle CIX$ and $\triangle DIC$ to be $IF,IG$ and $IH$ repsetively. Note that since $AB||XC$, $\angle ABD=\angle XGD=90^{\circ}$ and thus the points $B,G,I,D$ are colinear. Refer to the following figure:

It would suffice to prove that $\triangle CGI\cong\triangle CHI$ and $\triangle XGI\cong\triangle XFI$.
Any hints or solutions would be appreciated. It would be nice if you would be able to show how to prove the last step in my attempt. Otherwise, giving me a hint to a better approach would also be much appreciated. Thank you in advance!
Comment: *Trigonometry* is a good hint.
Comment: @cosmo5 could you elaborate a bit. I did consider using trigonometry, but I think the angle $\alpha=72^{\circ}$ and would create a bit of complications.  If I were to use trigonometry, then I might end up with something such as $\sin(\alpha)=x$, but I doubt $x$ would have a nice value. Do you mean I should use trigonometry to prove that lengths are equal?
Comment: Hint : Use $\triangle AOB \cong \triangle XCO$.
Answer: Let $B'$ the point symmetric to $B$ with respect to $AO$. Then $B', X, C$ are collinear because both $\angle OXC$ and $\angle AXB'$ are equal to $\alpha$. Since the central angle $COA$ subtends the same arc as the inscribed angle $CB'A$, we have $\angle COA = 2\angle CB'A$. This leads to $\alpha = 2(\pi - 2\alpha)$ from which we calculate $\alpha=\dfrac 25 \pi$.
Answer: Is this is enough information for you to figure out the proof?
Comment: Yes! We can use the inscribed angle theorem to find the arc $BC$ and we can determine arc $AB$ since $\triangle AOB=\triangle XCO$. Thank you! This was a very smart method.
Answer:
B' is mirror of B about AD.
$\angle AB'C=\frac{arc AC}2=\frac{\alpha}2$.
C', B'' are mirrors of C and B about vertical diameter and $\angle COC'=\angle OCB=\angle AB'C$, therefore $arc CC=arc CB=arc AB=arc C'B''=arc B''D$
Finally:
$\alpha =\frac {2}5 (arc AD)=\frac{2}5\times 180=72^0$


Animating in jquery: running a function after a group of animation finishes

Question: I'm animating a group of divs that need to move together. Each div will follow a different path, and will move at same time, for the same period.
After this piece of the animation is over, I'd like to run some code to redraw some other stuff.
I'm using jquery for this. Here is a sample code of what I'm doing:
    // units is an array containing the divs encapsulated on $()
for (var i = 0; i < units.length; i++)
{
    var unit = units[i];
    var idUnit = unit.attr('id');

            // New coordinates
    var xNew = layout.x[idUnit];
    var yNew = layout.y[idUnit];

            // Actual coordinates
    var xAct = x(unit);
    var yAct = y(unit);

            // Animate!
    unit.animate(
            {left: xNew, top: yNew}, {
                duration: 1000,
                easing: 'easeOutBack'
            }
    );
}

I could put the code I want to execute on the complete callback of one of the animate calls, but I'm looking for something like this:
queue.delay(1000).run(function(opts) {

   // Code goes here!

});

Is there a way to do this? Or should I rewrite my code to work with only one call to animate, and pass to it a custom stepper function?...
Answer: If you have a jQuery variable named $units that holds all the elements to be animated, you can do this:
$units.each(function() {
    var $unit = $(this),
        id = $unit.attr('id');

    var xNew = layout.x[id],
        yNew = layout.y[id];

    $unit.animate({ left: xNew, top: yNew },
        { duration: 1000,  easing: 'easeOutBack' });
}).promise().done(function() {
    // This will execute after all the animations have finished.
});

Comment: Works nicely! I took me some time to understand promise. I really need to take some time to study jquery more deeply!
Answer: Use setTimeout(function () { /* do callback */ }, 1000) where 1000 is your duration of pause. Add this line just after the for loop.
Comment: I thought doing that, but I have some concerns with synchronization. If I use the jquery animation API, jquery will put everything that should start at the same time in the same call, right? If I have some other animation scheduled to start at the same time of this call to setTimeout, my code would have a race condition, and I wouldn't known which call would be executed first, right?


How to compute $ \int e^{-st} \sin(2t) dt $

Question: Wolfram Alpha shows me the result of $ \int  e^{-st} \sin(2t) dt $ .
However it doesn't let me see the step to step solution. Then I tried to do this by hand as the solution didn't look "too difficult", however couldn't do it.
So can someone show me how to do it?
Comment: Try writing $\sin(2t)$ in exponential form using Euler's formula.
Comment: possible duplicate of [Name of this identity? $\int e^{\alpha x}\cos(\beta x)  \space dx = \frac{e^{\alpha x} (\alpha \cos(\beta x)+\beta \sin(\beta x))}{\alpha^2+\beta^2}$](http://math.stackexchange.com/questions/19796/name-of-this-identity-int-e-alpha-x-cos-beta-x-space-dx-frace-al)
Answer: You can integrate by parts twice or use this method
$$\int e^{-st}\sin (2t)dt=\operatorname{Im}\int e^{(-s+2i)t}dt$$
Can you take it from here?
Answer: using integration by parts we obtain
$\int e^{-st}\sin(2t)dt=-e^{-st}\frac{cos(2t)}{2}-\int\frac{s}{2}e^{-st}\cos(2t)dt$
and now the same once more
Answer: You start by using integration by parts two times, and then solve algebraically for the integral you want:
$\begin{align}
\int  e^{-st} \sin(2t) dt  &= -\frac12 e^{-st}\cos(2t) -\frac{s}{2}\int e^{-st}\cos(2t) dt \\
&=-\frac12 e^{-st}\cos(2t) -\frac{s}{2}\left(\frac12 e^{-st}\sin(2t) + \frac{s}{2}\int e^{-st}\sin(2t) dt \right) \\
&=-\frac12 e^{-st}\cos(2t)  -\frac{s}{4}e^{-st}\sin(2t) - \frac{s^2}{4}\int e^{-st}\sin(2t) dt
\end{align}$
So, that's two applications of integration by parts. Now you can add that last term back over to the left-hand side:
$\int  e^{-st} \sin(2t) dt + \frac{s^2}{4}\int e^{-st}\sin(2t) dt = -\frac12 e^{-st}\cos(2t)  -\frac{s}{4}e^{-st}\sin(2t)$
Multiplying everything by $4$ and factoring appropriately, we obtain:
$(4+s^2)\int e^{-st}\sin(2t) dt = -e^{-st}\left(2\cos(2t) + s\sin(2t)\right)$
or,
$\int e^{-st}\sin(2t) dt = \frac{-e^{-st}\left(2\cos(2t) + s\sin(2t)\right)}{4+s^2}$.


Get result based on Row_number criteria

Question: I have tables three tables: #T, #T1, #Maintable, for which I'll attach the corresponding DDL.
Create table  #T ( id int , reason varchar (50));

insert into #T Values (1,'Texas for live music');
insert into #T Values (1,'Texas for BBQ');
insert into #T Values (2,'Wisconsin for dairy products');
insert into #T Values (2,'Wisconsin for Rock');
insert into #T Values (2,'Wisconsin for Bird');
insert into #T Values (3,'North Carolina for Pepsi');
insert into #T Values (4,'Missouri for Forest');
insert into #T Values (5,'Oklohoma for cowboy');
insert into #T Values (5,'Oklohoma for Native Americans');
insert into #T Values (5,'Oklohoma for oil and gas');

Create table  #T1 ( id int , reason varchar (50));

insert into #T1 Values (1,'Texas for live music,BBQ');
insert into #T1 Values (2,'Wisconsin for dairy products, rock,bird');
insert into #T1 Values (3,'North Carolina for Pepsi');
insert into #T1 Values (4,'Missouri for Forest');
insert into #T1 Values (5,'Oklohoma for Native Americans,oil and gas');

Create table #MainTable (id int, State varchar(20),Capital varchar(30),Governer varchar(30));

Insert into #Maintable values (1,'Texas','Austin','A');
Insert into #Maintable values (2,'Wisconsin','Madison','B');
Insert into #Maintable values (3,'North Carolina','Releigh','C');
Insert into #Maintable values (4,'Missouri','Jefferson City','D');
Insert into #Maintable values (5,'Oklohoma','Oklohoma city','E');

Expected Output

ID
Reason
State
Capital
Governer

1
Texas for live music,BBQ
Texas
Austin
A

2
Wisconsin for dairy products, rock,bird
Wisconsin
Madison
B

3
North Carolina for Pepsi
North Carolina
Releigh
C

4
Missouri for Forest
Missouri
Jefferson City
D

5
Oklohoma for Native Americans,oil and gas
Oklohoma
Oklohoma city
E

I have a couple of tables, based on the criteria I will be filtering records from table #T and joining with other tables to get more columns but with the help of cte, I am not able to filter. if first table #T has more than one Id then we will be using reason from another table #T1. If it has only one Id then we will be using Reason from Table #T and finally, we will join with #main table to get other records. I have added an image describing more. Help is much appreciated. All those temp tables we can test
And the scenario is:

If reason appears more than once in #T table use #T1 table
If reason appears only once in the #T table use #T only, this is the first table

Here's my coding attempt:
with cte as (
    select *, ROW_NUMBER() over (partition by id order by id) rn
    from #T
)
select mt.id, state, capital, Governer,
       case when c.rn > 1
            then #t1.reason
            else c.reason
       end as reason
from cte c
join #t1           on c.id = #t1.id
join #maintable mt on c.id = mt.id

I am getting more results, I was expecting only 5 records. I guess there is some issue in my row_number. Help is appreciated.
Comment: [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551) *"It is not not letting me to add code"* It did but the problem is you basically formatted your *entire* question as code, which meant that by the time you tried to add the (markdown?) tables, you effectively had no content to your question. I've fixed the formatting issues (though there are plenty of other problems with your post), so you can now [edit] your question to add the data in a consumable format
Answer: You should first extract the ranking value from the table "#T" for each ID. Then you can use the COALESCE function in combination with LEFT JOIN operations to solve your problem:
WITH #T_ranked AS (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY id ORDER BY reason) AS rn
    FROM #T
)
SELECT m.id,
       COALESCE(#T1.reason, #T_ranked.reason) AS Reason,
       m.State,
       m.Capital,
       m.Governer
FROM      #Maintable m
LEFT JOIN #T1 ON m.id = #T1.id
LEFT JOIN #T_ranked ON m.id = #T_ranked.id AND #T_ranked.rn = 1

The LEFT JOIN operations will make your ids in the "MainTable" be kept, while the COALESCE function will make the first non-null argument to be the value for the "Reason" new field, in the specific case it will check whether "#T1.Reason" is null, if it is then it will assign "#T2.Reason". Values from "#T.Reason" which have an existing correspondent in "#T1.Reason" will never be selected in this way.
Check the demo here.
Comment: Hi I gues this will not work I am expecting as                      Expected Result
ID Reason State Capital Governer
1 Texas for live music,BBQ Texas Austin A
2 Wisconsin for dairy products, rock,bird Wisconsin Madison B
3 North Carolina for Pepsi North Carolina Releigh C
4 Missouri for Forest Missouri Jefferson City D
5 Oklohoma for Native Americans,oil and gas Oklohoma Oklohoma city E
Comment: I guess you're getting more rows than expected due to the "1-to-n" relationship cardinality between "*MainTable*" and "*#T*" tables, try now with the updated query.
Comment: Update your post accordingly with your environment completely cleaned out for what concerns images, tables and final query, then I may help you. Currently I'm not understanding your problem as is.
Comment: Check the updated answer: play with the provided demo if you want. Does it work for you?

Get result based on Row_number criteria


Weighted median of a portfolio

Question: I need to calculate weighted median return for a portfolio (using MATLAB).  There is information available online: MATLAB Central/rates&weights and Excel/note 4+4+4+7+7/5 logic
How would you calculate weighted median for following portfolios with given weights and returns?
Much of online help is about returns with frequencies.
I think the Matlab code in the solution above does not account for ties correctly.
Eg.
A portfolio has 6 investments with the following returns:
            A       B     C     D     E     F
weights:    0.1     0.1   0.1   0.2   0.1   0.4
returns:    10%     20%   30%   1%    2%    1%

weighted mean = *easy!*
weighted median = 1%??

            A      B     C      D      E      F     G     H
weights:    0.15   0.1   0.15   0.09   0.01   0.01  0.14  0.35
returns:    0.05%  1%    1%     1%     1%     2%    2%    5%

weighted mean = *easy!*
weighted median = 1.5%?? <or should it be (1+1+1+1+2+2)/6??>

Comment: Could you elaborate on what sense you think it treats ties incorrectly?  The weighted median in the example quite clearly is 1%, because the weights assigned to it are 0.6 out of 1.0, showing that 1% constitutes the bottom 60% of this weighted empirical distribution.
Comment: Please see the updated example.  I have added the (1+1+1+1+2+2)/6 in the query now to highlight my doubt.  Medians are not affected by this but per the second URL, I want to be sure I'm not missing anything.  I haven't used weighted medians before.
Answer: As detailed in this answer on the math SE, weights in a weighted median are expressed duplicates of the datum. In your top example, replace the weights with their multiples of ten, like so:
            A       B     C     D     E     F
weights:    1       1     1     2     1     4
returns:    10%     20%   30%   1%    2%    1%

Sort these by return and you have 1 1 1 1 1 1 2 10 20 30; the median of this pseudo-dataset is the weighted median, in this case the average of the middle two values, i.e. 1%. If you repeat this exercise for the second set, you'll see that the value is 1.5%.
Also note that the weighted-median is the same for any vector of weights proportional to this one. (This is straightforward to prove, but I leave that to you.)
Comment: Can you please check - I get median in second case as 1.5% when done manually using your approach
Comment: You are correct, I must have switched a number or two :)

Weighted median of a portfolio


Number of ways of selecting 4 numbers from 20 numbers under certain condition

Question: Out of 20 consecutive natural numbers, in how many ways 4 numbers can be selected such that any two selected number differ by at least 3.
I am not able to proceed further than writing domain of each number( x, y, z, w be the numbers in increasing order).
$ x \le  11$
$ x +3 \le y \le  14$
$ y +3 \le z \le  17$
$ z +3 \le w \le  20$
How can I proceed? Thanks
Answer: Instead of selecting four numbers out of $\{1,\ldots,20\}$, select four numbers $x_1<x_2<x_3<x_4$ out of $\{1,\ldots,14\}$ and let $y_1=x_1$, $y_2=x_2+2$, $y_3=x_3+4$, $y_4=x_4+6$. Then $(y_1,y_2,y_3,y_4)$ has the properties required and any allowed quadruple can be obtained this way.
Therefore the answer is $14\choose 4 $ (or in general $n-(k-1)(d-1)\choose k$ for choosing $k$ numbers out of $n$ with distance at least $d$).
Answer: Think of the four chosen numbers as dividers, breaking the string of integers from $1$ through $20$ into five sections. For instance, if you choose $5,10, 17$, and $20$, the picture looks like this:
<code>                    oooo|oooo|oooooo|oo|
                        5   10     17 20
</code>
The first section, before the $5$, contains four numbers; the second, between $5$ and $10$, also contains four numbers; the third, between $10$ and $17$, contains six numbers; the fourth, between $17$ and $20$, contains two numbers; and the fifth, after $20$, contains none.
Let $u_1,u_2,u_3,u_4$, and $u_5$ be the number of numbers in the respective sections. There are $16$ other numbers, and there must be at least two of them between adjacent dividers, so $u_1,u_2,u_3,u_4$, and $u_5$ must satisfy the following conditions:

$u_1+u_2+u_3+u_4+u_5=16$, and
$u_1,u_5\ge 0$, $u_2,u_3,u_4\ge 2$.

Moreover, each set of integers satisfying those solutions describes one of the solutions to your problem, so you just need to count the solutions to (1) satisfying (2). In fact, we can simplify this even further if we let $v_2=u_2-2,v_3=u_3-2$, and $v_4=u_4-2$. Then we need only count the non-negative solutions to $u_1+v_2+v_3+v_4+u_5=10$, which is a standard stars-and-bars problem.


Authorization with two Keycloaks and shared tokens

Question: I have the following situation. Some of the users are authorized to the my backend service with Direct Access Grants, but those who are administrators are on a second Keycloak with another client and realm, and I need to be able to get valid tokens for the first Keycloak for them as well. I registered the second Keycloak with the administrators in the Identity Provider of the first one and if I use the normal web work flow from the first one I can log in with an admin user but I stay in the page of the first Keycloak and I can't get the tokens of that user in my backend. If I try to change the redirect_uri, I get an error that it is not allowed, even though I put * in the client of the second one. These are my settings for both Keycloaks.
How can I get a token for a user from the second Keycloak that is also valid in the first Keycloak?
First Keycloak Identity Provider settings:
<code>  "identityProviders": [
{
  "alias": "keycloak-oidc",
  "internalId": "c3a3b1db-65ee-49df-b517-bfba6c355696",
  "providerId": "keycloak-oidc",
  "enabled": true,
  "updateProfileFirstLoginMode": "on",
  "trustEmail": false,
  "storeToken": true,
  "addReadTokenRoleOnCreate": true,
  "authenticateByDefault": false,
  "linkOnly": false,
  "firstBrokerLoginFlowAlias": "first broker login",
  "config": {
    "userInfoUrl": "http://host.docker.internal:909/auth/realms/vrp-realm-adm/protocol/openid-connect/userinfo",
    "hideOnLoginPage": "false",
    "clientId": "vrp-client-adm",
    "tokenUrl": "http://host.docker.internal:909/auth/realms/vrp-realm-adm/protocol/openid-connect/token",
    "acceptsPromptNoneForwardFromClient": "false",
    "backchannelSupported": "false",
    "useJwksUrl": "true",
    "loginHint": "false",
    "authorizationUrl": "http://host.docker.internal:909/auth/realms/vrp-realm-adm/protocol/openid-connect/auth",
    "clientAuthMethod": "client_secret_post",
    "logoutUrl": "http://host.docker.internal:909/auth/realms/vrp-realm-adm/protocol/openid-connect/logout",
    "syncMode": "IMPORT",
    "clientSecret": "**********"
  }
}
</code>
Second Keycloak client settings:
<code>{
  "id": "f873a96c-6468-4737-b576-bdf610fb9597",
  "clientId": "vrp-client-adm",
  "rootUrl": "http://localhost:808",
  "adminUrl": "http://localhost:808",
  "surrogateAuthRequired": false,
  "enabled": true,
  "alwaysDisplayInConsole": false,
  "clientAuthenticatorType": "client-secret",
  "secret": "**********",
  "redirectUris": [
    "*"
  ],
  "webOrigins": [
    "*"
  ],
  "notBefore": 0,
  "bearerOnly": false,
  "consentRequired": false,
  "standardFlowEnabled": false,
  "implicitFlowEnabled": true,
  "directAccessGrantsEnabled": true,
  "serviceAccountsEnabled": true,
  "publicClient": false,
  "frontchannelLogout": false,
  "protocol": "openid-connect",
  "attributes": {
    "saml.multivalued.roles": "false",
    "saml.force.post.binding": "false",
    "frontchannel.logout.session.required": "false",
    "oauth2.device.authorization.grant.enabled": "false",
    "backchannel.logout.revoke.offline.tokens": "false",
    "saml.server.signature.keyinfo.ext": "false",
    "use.refresh.tokens": "true",
    "oidc.ciba.grant.enabled": "true",
    "backchannel.logout.session.required": "true",
    "client_credentials.use_refresh_token": "false",
    "saml.client.signature": "false",
    "require.pushed.authorization.requests": "false",
    "saml.allow.ecp.flow": "false",
    "saml.assertion.signature": "false",
    "id.token.as.detached.signature": "false",
    "client.secret.creation.time": "1668867137",
    "saml.encrypt": "false",
    "saml.server.signature": "false",
    "exclude.session.state.from.auth.response": "false",
    "saml.artifact.binding": "false",
    "saml_force_name_id_format": "false",
    "tls.client.certificate.bound.access.tokens": "false",
    "acr.loa.map": "{}",
    "saml.authnstatement": "false",
    "display.on.consent.screen": "false",
    "token.response.type.bearer.lower-case": "false",
    "saml.onetimeuse.condition": "false"
  },
  "authenticationFlowBindingOverrides": {},
  "fullScopeAllowed": true,
  "nodeReRegistrationTimeout": -1,
  "protocolMappers": [
    {
      "id": "6e02e265-af71-4af2-9253-ac26051053a4",
      "name": "Client IP Address",
      "protocol": "openid-connect",
      "protocolMapper": "oidc-usersessionmodel-note-mapper",
      "consentRequired": false,
      "config": {
        "user.session.note": "clientAddress",
        "id.token.claim": "true",
        "access.token.claim": "true",
        "claim.name": "clientAddress",
        "jsonType.label": "String"
      }
    },
    {
      "id": "2173ad2e-953d-401a-816b-19d920f7fa16",
      "name": "Client ID",
      "protocol": "openid-connect",
      "protocolMapper": "oidc-usersessionmodel-note-mapper",
      "consentRequired": false,
      "config": {
        "user.session.note": "clientId",
        "id.token.claim": "true",
        "access.token.claim": "true",
        "claim.name": "clientId",
        "jsonType.label": "String"
      }
    },
    {
      "id": "2aad6645-174c-4dcd-b711-4eb388dbac3e",
      "name": "Client Host",
      "protocol": "openid-connect",
      "protocolMapper": "oidc-usersessionmodel-note-mapper",
      "consentRequired": false,
      "config": {
        "user.session.note": "clientHost",
        "id.token.claim": "true",
        "access.token.claim": "true",
        "claim.name": "clientHost",
        "jsonType.label": "String"
      }
    }
  ],
  "defaultClientScopes": [
    "web-origins",
    "acr",
    "profile",
    "roles",
    "email"
  ],
  "optionalClientScopes": [
    "address",
    "phone",
    "offline_access",
    "microprofile-jwt"
  ]
}
</code>
Comment: I think what you might need is the "identity provider federation" feature or Keycloak, where you can connect several identity providers. (Don't necessarily have to be all Keycloak instances.) Found the docs (https://www.keycloak.org/docs/latest/server_admin/#_identity_broker) but didn't try it for myself.
Answer: The post by trotman23 in this thread may help
https://keycloak.discourse.group/t/unable-to-retrieve-upstream-identity-providers-original-token/2267/2
Answer: I detailed how to achieve multi-tenancy on a Spring resource-server with JWT decoder in this answer.
All the authorization-servers being Keycloak is not important. The solution I proposed there is having resource-server(s) accept identities emitted by more than just one issuer (use a list of trusted issuers instead). So clients or users can choose their preferred authorization-server in that list.
Comment: Thanks, but the customer's requirement is that admins are authenticated by the 2nd Keycloak. Multitenancy doesn't work for me
Comment: I might need your definition of multi-tenancy to understand. What I refer to is perfectly compatible with admins being authenticated by an authorization-server (tenant `A`) and other users by a different one (tenant `B`)
Comment: Identity federation is required only when when one authorization-server emits opaque tokens or does not include your resource-server in its audience.
Answer: I found next article who helped me to do auth process throw 2 keycloak instances
https://www.jessym.com/articles/stateless-oauth2-social-logins-with-spring-boot


PhpStorm, Windows 10 PowerShell and Git commands

Question: I'm using PhpStorm on windows and I'm trying to learn working with CLI.
So in the Program settings I use Windows PowerShell as native Terminal.
I installed git, node and npm.
I'm very new on using the command line on Windows.....
When using the PowerShell as standalone the command git --version gives me the correct git Version. When using the same command in PhpStorm Terminal which is linked to the PowerShell I get an error (sorry for German):

"git : Die Benennung "git" wurde nicht als Name eines Cmdlet, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt. Überprüfen Sie die Schreibweise des Namens, oder ob der Pfad korrekt ist (sofern enthalten), und wiederholen Sie den Vorgang."

What am I doing wrong?? Or do I miss something??
Answer: Please use PhpStorm run as administrator.
Answer: You don't have git in the terminal's PATH environment variable. If you look for "terminal" in the Settings dialogue you can use the Environment Variables section to tweak that. Mine is empty and I have Include system environment variables checked, which I believe it's the default.


Erro no visual studio runtimelibrary error

Question: Esta apresentando o seguinte erro de runtimelibrary error:

Error LNK2038 mismatch detected for 'RuntimeLibrary': value
  'MD_DynamicRelease' doesn't match value 'MDd_DynamicDebug' in
  Aimbot.obj    INDIGO  C:\smef-s-Indigo-Remasterd-master\INDIGO\libprotobuf.lib(message_lite.obj)  1

Eu estou com 40 errors desse mesmo tipo .
Answer: Sua pergunta não foi muito clara, onde e quando que esse erro aparece ? Mas geralmente esse tipo de defeito é resolvido com uma Reinstalação.
Tente desinstalar o programa, apagar todas as pastas sobrarem (Que restarem da desinstalação) e instalar o Aplicativo novamente, se o erro persistir, entre em contado com o suporte da Microsoft.


Drupal's built-in xss filters vs. HTML purifier module

Question: Does the  htmlpurifier module for Drupal provide better security against xss (and possibly other vulnerabilities) than Drupal's built in functionality such as filter_xss?
Looking for some guidance on why I should use htmlpurifier module for Drupal if I'm purely concerned with security (NOT concerned with preserving inline styles).
Answer: I trust the filter_xss function a bit more than htmlpurifier simply due to the complexity of the htmlpurifier code. Neither function is easy to understand, but at least filter_xss is shorter and more stable.
It is true that htmlpurifier is a general library used by other systems and therefore it could have "more eyes" on it. If you look at the HTMLPurifier Summary they claim that kses (which is what filter_xss was originally based on) is "Probably" XSS safe but misses out on other features of HTMLPurifier. The Drupal input format system handles many of the other features that HTMLPurifier mentions in that table so it's not an apples-to-apples comparison.
By the way, you may want to post questions like this to https://drupal.stackexchange.com/ in the future.


How can I write a condition in a rule of the ACL file, if I'm working with arrays?

Question: I have this rule:
rule Viewer {
  description: "Allow the viewer read access to his assigned assets"
  participant(v): "org.biz.app.Viewer"
  operation: READ
  resource(d): "org.biz.app.Activo"
  condition: (v.getIdentifier() === d.viewers.getIdentifier())
  action: ALLOW
}

and in the model file:
asset Activo identified by acitvoId {
  o String activoId
  o String activoName
  o Integer version
  o DateTime startDate
  o DateTime endDate
  --> Author owner
  --> Viewer[] viewers optional
}

What I want the rule to be is that the viewer only gets read access to the assets that he is assigned to.
The:
v.getIdentifier();

returns the viewer id, and I want to compare it with the array of viewers in the asset:
--> Viewer[] viewers optional

if the viewerid is in the array, the viewer has read access. How can I write that rule?
Answer: The pii-network includes ACL rules that reference arrays. E.g. the call to indexOf here:
https://github.com/hyperledger/composer-sample-networks/blob/master/packages/pii-network/permissions.acl#L38


Using matter-js when adding a Body using fromVertices - the resulting vertices are not positioned correctly with relation to each other

Question: Here's the shape I'm expecting to see.  You can see the points along the edge depicting the vertices.

Here's the json file (generated from the above) that I'm loading in (via a simple import) and using to create the Body.
{
    "cannon_transparent_sm": {
        "label": "cannon",
        "density": 0.1,
        "restitution": 0,
        "friction": 0.1,
        "frictionAir": 0.01,
        "frictionStatic": 0.5,
        "fixtures": [
            {
                "label": "cannon_fixture",
                "vertices": [
                    [ { "x":150, "y":45 }, { "x":134, "y":0 }, { "x":18, "y":30 }, { "x":1, "y":56 }, { "x":21, "y":94 }, { "x":86, "y":76 } ],
                    [ { "x":43, "y":17 }, { "x":44, "y":23 }, { "x":59, "y":19 }, { "x":58, "y":14 } ],
                    [ { "x":6, "y":41 }, { "x":1, "y":56 }, { "x":18, "y":30 } ],
                    [ { "x":6, "y":83 }, { "x":21, "y":94 }, { "x":1, "y":56 }, { "x":2, "y":72 } ],
                    [ { "x":86, "y":76 }, { "x":21, "y":94 }, { "x":25, "y":108 }, { "x":48, "y":124 }, { "x":61, "y":124 }, { "x":73, "y":119 }, { "x":83, "y":109 }, { "x":88, "y":95 } ],
                    [ { "x":34, "y":118 }, { "x":48, "y":124 }, { "x":25, "y":108 } ]
                ]
            }
        ]
    }
}

The above was generated from this physicseditor tool.
There's a problem when I try to add this to my 2d world.  I'm using the javascript library matter-js and fromVertices() to generate the sprite.
This is what I see however.

It looks to me like each set of vertices has been positioned incorrectly with relation to each other.
Here's the javascript I'm using to add the "cannon".
var cannonBodyDef = {
  position: Vector.create(300, 50),
  density: this._cannon.density,
  restitution: this._cannon.restitution,
  friction: this._cannon.friction,
  frictionStatic: this._cannon.frictionStatic,
  frictionAir: 0.9, //this._cannon.frictionAir
};

var cannon = Bodies.fromVertices(300, 200, this._cannon.fixtures[0].vertices, cannonBodyDef);

World.add(engine.world, cannon);

It's also dropping to the floor (expected) then wobbling a little and falling straight through!  Even though the floor is static: true.  Not sure if that is related.
Answer: It appears that Matter slices off the protruding parts of your shape, making it convex. I would suggest using poly-decomp library to decompose your concave shape into the set of convexes. And when creating a body from vertices, you'll have to sort the flatted array, which you export from physics editor.
Common.setDecomp(require('poly-decomp'))
const cannon = Bodies.fromVertices(x, y, [Vertices.clockwiseSort(vertices.flat())])

Got something like this, might look better with some overlapping texture:


synchronized method not working as Lock ?? why not make a lock on count

Question: As given below code I have a use for the intensive lock (monitor) for my count variable and only a single Thread can be accessed at a time by making  synchIncrement() method to be a synchronized method. Then the O/P should be 20000 but still some time difference value is coming.
Why?
public class SynchBlockThread {
    private int count = 0;

    private synchronized void synchIncrement() {
        count++;
    }

    public static void main(String[] args) {
        SynchBlockThread sBT = new SynchBlockThread();
        sBT.doWork();

    }

    private  void doWork() {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i<10000; i++) {
                    synchIncrement();
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i<10000; i++) {
                    synchIncrement();
                }
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(count);
    }
}

Comment: It's not necessary to provide a screenshot of the whole screen to prove that you are getting a value different from `20000`. By default, we believe you :)
Answer: Quite a hard one to spot.
At the end of the doWork() method you join Thread t1 twice, so Thread t2 is still doing its work when the result is printed.
To express it in code:
try {
    t1.join();
    t1.join();
} catch (InterruptedException e) {
    e.printStackTrace();
}

should instead be
try {
    t1.join();
    t2.join();
} catch (InterruptedException e) {
    e.printStackTrace();
}

Answer: The synchronised method does its job right. The problem is that you aren't waiting for the second Thread. count can be printed before the second thread terminates, so you should add t2.join(); as well:
try {
    t1.join();
    t2.join();
} catch (InterruptedException e) { ... }

Let's consider a more interesting version of your method:
private void doWork() throws InterruptedException {
    final int n = 2;

    final CountDownLatch latch = new CountDownLatch(n);
    final ExecutorService service = Executors.newFixedThreadPool(n);
    final Runnable task = () -> {
        for (int i = 0; i < 10000; i++) {
            synchIncrement();
        }
        latch.countDown();
    };

    for (int i = 0; i < n; ++i) {
        service.execute(task);
    }

    latch.await();
    service.shutdown();
    System.out.println(count);
}

I introduced a fixed-size ExecutorService to not create threads on my own. I wrote a CountDownLatch to know when all the tasks finish execution, so I can shut down the service and print the result.


Background Process subprocess.Popen with Pipe

Question: I'm trying to record and convert a stream with python using arecord.
In the shell this is a command more or less like:
arecord -B 5000 -f dat | lame -m j -q 5 -V 2 - test.mp3 &

In Python I tried this with subprocess.Popen:
reccmd = ["arecord", "-B", "5000", "-f", "dat"]
mp3cmd = ["lame", "-m", "j", "-q", "5", "-V", "2", "-", "test.mp3"]
p = subprocess.Popen(reccmd, stdout=subprocess.PIPE)
p2 = subprocess.Popen(mp3cmd, stdin=p.stdout)
p2.communicate()

But I don't know how to include the "&" or something similar in the code to be able to stop the recording with a
killall arecord command
Answer: If you don't want the main Python process to block while executing the subprocesses, simply don't call p2.communicate().  The calls to subprocess.Popen() don't block.
Comment: Thank you very much. Wasted hours trying to find a way out and sometimes the answer is just this easy


Calculating Cohen's Kappa in SPSS for a systematic review

Question: I'm sure there's a simple answer to this but I haven't been able to find it yet. All the explanations I've found to calculate Cohen's Kappa in SPSS use data that is formatted with cases that are listed as rows (see image below for example). Then analysing the data as a cross tabulation.

My problem is that for a systematic review, this way of formatting data is very inconvenient (I would have to list more than 1500 articles as cases). Is there a way of calculating Cohen's Kappa when the data is presented as a square matrix (see image below)? I know how to calculate the statistic manually but my problem is that SPSS generates the p-value which I do not know how to manually calculate.
Answer: You can use the counts from your confusion matrix to simulate data in the long format that SPSS expects.
As a very simple example, imagine your four cells of the confusion matrix were 1, 2, 3, 4 (instead of 100, 20, 40, 100).
Create 1 example of include-include, 2 examples of include-exclude, 3 examples of exclude-include, and 4 examples of exclude-exclude:

RaterA
RaterB

Include
Include

Include
Exclude

Include
Exclude

Exclude
Include

Exclude
Include

Exclude
Include

Exclude
Exclude

Exclude
Exclude

Exclude
Exclude

Exclude
Exclude

Update:
Here is the formula for the two-rater unweighted Cohen's kappa when there is no missing ratings and the ratings are organized in a contingency table.
$$\hat{\kappa} = \frac{p_a - p_e}{1 - p_e}$$
$$p_a = \sum_{k=1}^q p_{kk}$$
$$p_e = \sum_{k=1}^q p_{k+} p_{+k}$$
Here is the formula for the variance of the two-rater unweighted Cohen's kappa assuming the same.
$$v(\hat{\kappa}) = \frac{1-f}{n(1-p_e)^2}\left(p_a(1-p_a)-4(1-\hat{\kappa}\left(\sum_{k=1}^qp_{kk}\hat{\pi}_k - p_a p_e\right) + 4(1-\hat{\kappa})^2\left(\sum_{k=1}^q\sum_{l=1}^qp_{kl}((p_{Al}+p_{Bk})/2)^2 - p_e^2\right)\right)$$
From this variance estimate, you can compute the standard error and calculate a $p$-value and confidence interval.
See Gwet (2014) page 142 for more information.
Comment: Thanks for your advice, Jeffrey! Out of curiosity, could you please share the formula for calculating p?
Comment: I added the formula for your curiosity.
Comment: I could share the formula for calculating $p$ for you, but I suspect this isn't what you're looking for if you use SPSS. As an alternative that would still be easy, check out www.agreestat360.com for Gwet's web-based calculator.
Answer: You can use 'weight cases' in SPSS to tell SPSS to treat that row in the data as repeating N times.
So you make four rows (inc/inc, inc/exc, exc/inc and exc/exc) and add the number in each of these categories, then you can analyze in the usual ways.
Comment: Thanks for your solution, Jeremy! That's exactly what I was looking for.


How to skip waiting for response from db part when saving data in Django?

Question: The challenge is that I need to recompute all the data I have in db, after saving a new instance. The computation takes not more than 2 mins, which is fine for my problem. I have custom save method and all I need to do is to go through all items and item.save(), but as I said It takes more than 30 sec, so I have issues with 'request timeout'(using Heroku btw). Any ideas on how to deal with this?
Answer: @Uladzislau Malinouski, you can use the asynchronous tools like celery.
The way it works is that the task that is taking a significant amount of time can be wrapped as an asynchronous task and the computing can be done in the background. You can setup celery on Heroku by following this guide - https://devcenter.heroku.com/articles/celery-heroku.
If you are using free account and have not provided your card details on Heroku, it'd not be possible for you to add the addon for the broker which are used along with celery-like Redis, Rabbitmq etc.
In such cases, you may follow this guide to schedule an asynchronous task on Heroku - https://devcenter.heroku.com/articles/clock-processes-python


Telegram Bot - Cannot remove custom keyboard using PHP

Question: please help me. I added a custom keyboard via reply_markup like this:
<code>        $reply_markup = array(
            'keyboard' => array(
                array(
                    array(
                        'text' => 'Click here to upload contact & validate it',
                        'request_contact' => true
                    )
                )
            ),
            'one_time_keyboard' => true,
            'resize_keyboard' => true
        );

        $reply_markup = json_encode($reply_markup);

        API_URL."sendmessage?chat_id=".$chatID."&text=".urlencode($reply)."&reply_markup=".urlencode($reply_markup);
</code>
it is working fine. but now I need to remove the custom keyboard. I tried like this:
<code>        $reply_markup = array(
            'remove_keyboard' => true
        );

        API_URL."sendmessage?chat_id=".$chatID."&text=".urlencode($reply)."&reply_markup=".urlencode($reply_markup);
</code>
it is not working. the custom keyboard only hidden, not removed. By the way, I am using PHP 7.
Please help. Thank you in advance
Comment: I tried to reproduce your problem. But I don't see anything wrong. Used your code and everything works as expected. Custom keyboard is removed and not hidden. Tried with telegram's desktop application on (win10) also on android.
Comment: thank you @newsha for checking. I edited the code, and realised a line is missing in the code block which having error. your checking pointed me to a right direction
Answer: so today I found out, my actual code missing one line of code. it can be seen below, the bold part.
<code>        $reply_markup = array(
            'remove_keyboard' => true
        );
</code>
$reply_markup = json_encode($reply_markup);
<code>        API_URL."sendmessage?chat_id=".$chatID."&text=".urlencode($reply)."&reply_markup=".urlencode($reply_markup);
</code>


Pentatonic and Chinese tradition - what I am getting wrong?

Question: I am not a musician, just a dilettante. I am interested in the traditional Chinese music system, which is supposed to be a pentatonic scale.
According to Wiki, one way to get a pentatonic scale is to take five consecutive pitches from the circle of fifths and put them into one octave. For example, we take C, G, D, A, E and put them in one octave as C, D, E, G, A. That sounds good, as according to my references, the traditional Chinese system consists of the following pitches separated by perfect five (7 semitones).
Now comes what I need help understanding. As I read about the pentatonic scale, I should take C, D, E, G, and A and then go to the next octave, retaking C. I.e., the same notes but the next octave. However, if I keep taking seven semitones, it should be C, G, D, A, E, and then B, F#, and so on! These notes are not in the octave-based pentatonic scale but appear when I keep taking seven semitones; it makes me think I am missing something.
UPD: To clarify the question. I have a book claiming that the traditional Chinese acoustic system was based on twelve notes separated by perfect fifths, seven semitones. So, as far as I see, it does not correspond to the standard pentatonic (C-D-E-G-A) as soon as we go outside an octave?
Comment: You might be running into the fact that to say "chinese" and "traditional" is to reference several millennia of history, and many shifting and overlapping subcultures. You might start with a deeper dive using some truly historical and reputable source; I suspect it's something more nuanced then "over all those thousands of years and diverse genres, cultures, and practices, 'Chinese music was pentatonic.'"
Comment: @Arastas the 12-note scale is also not closed unless you temper the fifths or let one of them be rather smaller than a 3:2 ratio, or some other compromise.
Comment: Wikipedia turns up [Shi'er lü](https://en.wikipedia.org/wiki/Shi%27er_l%C3%BC), but the timeline for it seems to overlap with the sentence "[Around or before the 7th century BC, a system of pitch generation and pentatonic scale was derived from a cycle-of-fifths theory](https://en.wikipedia.org/wiki/Music_of_China#Early_history)."
Comment: You don't keep taking seven semitones. You just get the five notes and then play them in any octave.
Comment: @ToddWilcox Thanks! I have updated the question to make it more clear.
Comment: What book is it? It's hard for us to clarify without more understanding of the book.
Comment: @AndyBonner That is exactly where I fail! I see how the cycle-of-fifths yields the twelve-notes Shi'er lü, but to get a pentatonic, we need to take only the first five steps, which is not, as to me, a "cycle" anymore as it is not closed.
Answer: Sixteenth-century Chinese music theorists were apparently the first to calculate 12-tone equal temperament with high precision, so they must have known that equal temperament was a fairly close approximation to twelve tones derived from the just fifth (3:2 frequency ratio).  Some Chinese music also uses, fairly prominently but not exclusively, a five-pitch pentatonic scale of the type described in the question.  The derivation of the pentatonic scale from four perfect fifths was known from the 7th century or earlier.
We can infer that Chinese theorists also recognized octave equivalence, and that they, or at least some of them, knew these facts, which are not mutually exclusive or contradictory:

one can derive the pentatonic scale described in the question from five pitch classes separated by a fifth.
if you keep going until you have twelve pitch classes, the next one you generate will  be fairly close to the one you started with.
if you temper the fifths, you can spread the out-of-tune-ness around so nothing sounds that bad.
you can use the 12 pitch classes you end up with to create other scales with more than five pitch classes per octave; each scale with fewer than twelve pitch classes is a subset of the full twelve-member set of pitch classes.  (The Indian seven-tone scale was used for a time from the sixth century but later abandoned.)

So at some point at least, somebody recognized that the pentatonic scale was five adjacent pitches in the circle of fifths.  Or maybe they didn't think of extending the circle to the twelfth tone until much later.  In any event, when you have a melody in the pentatonic scale, you don't generally play the notes in circle-of-fifths order, and the jump from E to G is the same as the jump from A to the upper C as you wrap around the octave.
It's very unlikely that Chinese music started by noticing you could generate scales by using notes a fifth apart and then just decided to stop after five notes.  Rather, the theorists noticed (as Greek theorists also did) that the notes of the scale they'd already been using could be related to one another through recursive application of the 3:2 ratio.
Comment: @Aaron I've added some sources and corrected the timeline.
Comment: "Ancient Chinese music theorists apparently theorized about the 12-tone scale and knew that equal temperament was a fairly close approximation to twelve tones derived from the just fifth." Apparent how? Source?
Answer: A pentatonic scale has five notes. Once you have establisehed five notes by whichever method you choose then you stop and repeat those notes in the other octaves.
If you keep adding notes by your perfect fifth method then you end up with the notes of a seven-note major scale, and if you add even more then you end up with a twelve-note chromatic scale. Both of these are useful, but neither of them is a pentatonic scale.
Comment: Sure, but by this argument you get a minor scale as well. The reasonable assumption is that the starting tone is the root, by which it would be lydian. Of course, if you assume that the second note obtained that way was the root, then it would be a major scale. But I'd claim it makes more sense to use the first note upon which everything else builds on as the root.
Comment: @Lazy It depends where you start, lydian is just a mode of the major scale.
Comment: @Lazy it really doesn't matter here: call it whatever you like. It contains the notes of a major scale, so that's what I'm calling it.
Comment: Thanks! So, we either take the first five steps of the perfect-fifths-sequence to get a (major?) pentatonic, or keep adding notes getting something else.
Comment: No seven note major scale, but a lydian scale!
Comment: Or call it the diatonic gamut, understand its deep history, and realize the major/minor system came much later.


BroadcastReceiver is not called in Android >= Api 26

Question: BroadcastReceiver ist not working for any action in Api 26 or higher, according to documentation implicit actions are blocked, but not boot_completed. I tested with Android 19, 24, 26 and 28.
Here is my receiver declaration:
<receiver
        android:name="de.com.limto.limto1.broadcastReceiver"
        android:label="StartMyServiceAtBootReceiver"
        android:directBootAware="true"
        android:enabled="true">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
            <action android:name="android.intent.action.REBOOT" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
            <action android:name="android.intent.action.ACTION_SHUTDOWN" />
            <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

and here my permissions
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

and here my receiver:
@Override
public void onReceive(Context context, Intent intent) {
    try {
        Log.d(BROADCAST_RECEIVER,intent.getAction());
        lib.appendLog(intent.getAction(),context);
        lib.ShowToast(context, BROADCAST);
        if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
            if (service != null) {
                try {
                    service.stop();
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                    Log.e(BROADCAST_RECEIVER,throwable.getMessage(), throwable);
                }
            }
        } else {
            /*if (service != null) return;
            Intent serviceIntent;
            serviceIntent = new Intent(context, LimindoService.class);
            serviceIntent.putExtra(BOOT, true);
            */
            LimindoService.ccontext = context;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //context.startService(serviceIntent);
                lib.scheduleJob(context);
            } else {
                //context.startService(serviceIntent);
                startServiceByAlarm(context);
            }

        }
    }
    catch (Throwable ex)
    {
        ex.printStackTrace();
        lib.appendLog(ex.getMessage(), context);
        Log.e(BROADCAST_RECEIVER,null,ex);
        lib.ShowToast(context, ex.getMessage());
    }
}

Answer: AFAIK BOOT_COMPLETED broadcast doesn't have category android.intent.category.DEFAULT, removing the category should fix the problem.
Comment: This makes no difference. If I call am broadcast -a android.intent.action.ACTION_BOOT_COMPLETED onReceive is not being called....
Comment: @Hans-MartinGoebel You should send `android.intent.action.BOOT_COMPLETED` not `android.intent.action.ACTION_BOOT_COMPLETED`. Although this is a [protected-broadcast](https://android.googlesource.com/platform/frameworks/base/+/master/core/res/AndroidManifest.xml#37), meaning that only the system can send it, I'm not sure it's possible to send it via shell uid or not.
Comment: @Hans-MartinGoebel Also note that Android won't send implicit broadcast intents to newly installed apps or force closed ones until user explicitly opens one of its Activities, or an explicit intent has been previously sent to this app.
Comment: only root can send android.intent.action.BOOT_COMPLETED and I don't have a rooted device. I also registered android.intent.action.ACTION_BOOT_COMPLETED and it is being called in devices < api 26. I also restarted the device and nothing is being written to the log file. And I did open the app before.
Comment: @Hans-MartinGoebel Where's the log file? Before user unlocks the device, storage may be encrypted and not accessible to your app. Does your app really need `LOCKED_BOOT_COMPLETED`? I tested the BOOT_COMPLETED broadcast on a device having O+, it woks fine. My `` has only one `` (``) and without ``.
Comment: My IntentFilter is now:

and still onReceive is not called on startup.
Comment: I also made a test app and onReceive gets called with API 25 but does not get called with API 26......
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/205839/discussion-between-hans-martin-goebel-and-frogatto).
Answer: This behaviour is happening only on some devices with api >= 26 ... This was caused by the phone settings: Starting the service on boot was disabled in the settings.
Comment: What is the solution please?
Comment: enable start background service in settings
Comment: Which settings screen?
Comment: android >= 26 Settings for each app you can allow or prohibit background services.


Angular/Restangular, how to pass data to url like $routeParams with angular-resource

Question: I asked this question earlier for angular-resources and I got it working, but now I have moved on to using restangular.
I have a view /models that gets data from storage/models.json, and I set that up to work fine with restangular.
Now I want to have a view such as /models/:modelId that would get data from storage/individual/:modelId.json with :modelId being the respective Id of the model, obviously, and I am having troubles setting this up with restangular. I got it working with angular-resources but restangular has many features that I will benefit from in the future so I decided to make the switch.
Can someone point me in the right direction? The GitHub page doesn't really talk about routeParams and I can't find examples doing what I'm trying to achieve, though I may have overlooked it.
ModelsCtrl.js:
'use strict';

angular
    .module('swoleincApp')
    .controller('ModelsCtrl', ['ModelsService', '$scope', ModelsCtrl]);

function ModelsCtrl(ModelsService, $scope) {
    ModelsService
        .then(function(allModels) {
            $scope.models = allModels;
        });
}

ModelsService.js:
'use strict';

angular
    .module('swoleincApp')
    .factory('ModelsService', ['Restangular', ModelsService]);

function ModelsService(Restangular) {
    return Restangular
        .service('app/storage/models.json')
        .getList();
}

The above two examples work well together and give me the desired results.
I'm trying to do something such as this for the second route but I get a 404 because ":modelId" is being used in the url as opposed to the actual model Id.
IndividualCtrl.js:
'use strict';

angular
    .module('swoleincApp')
    .controller('IndividualCtrl', ['Individual', '$scope', IndividualCtrl]);

function IndividualCtrl(Individual, $scope) {
    Individual
        .then(function(individual) {
            $scope.model = individual;
        });
}

IndividualService.js:
'use strict';

angular
    .module('swoleincApp')
    .factory('Individual', ['Restangular', IndividualService]);

function IndividualService(Restangular) {
    return Restangular
        .one('storage/individual/:modelId.json')
        .get();
}

Answer: In your service change
Restangular
        .one('storage/individual/:modelId' + '.json')
        .get();

to
Restangular
        .one('storage/individual/', actualModelId)
        .get();

Then wherever you are configuring your module you need to add the suffix:
RestangularProvider.setRequestSuffix(".json");

(from Restangular docs)
If all of your requests require to send some suffix to work, you can set it here. For example, if you need to send the format like /users/123.json you can add that .json to the suffix using the setRequestSuffix method
Comment: I tried this and just get errors. Either I'm implementing incorrectly or you're misunderstanding. For example, /models view loads all models. Each model has link to /models/:modelId with :modelId being the string that leads to their .json file. I want it such that when that link is clicked, the /models/:modelId view is loaded with the storage/individual/:modelId.json file being used for data. I had this set up easily with angular-resource using routeParams but can't find examples for restangular.
Answer: Solved my problem
Changed this:
Restangular
        .one('storage/individual/:modelId' + '.json')
        .get();

To this:
Restangular
        .one('storage/individual/', $route.current.params.modelId + '.json')
        .get();

And added $route to the controller.


Determine size of functions/stub/namespace in memory

Question: I have a couple of functions in a namespace called stub.
I have to determine the exact start address of the namespace and the end address, of at least the size of the namespace in memory (to copy these functions into another process).
While this worked perfectly in Visual C++ 2008 by adding a
void stub_end() { }
at the end of the namespace and using
size_t size = reinterpret_cast<ULONG_PTR>(stub_end) - reinterpret_cast<ULONG_PTR>(stub_start);
to determine the size of the stub.
This worked because Visual C++ preserved the function order as it is in the .cpp file, however that does not seem to be the case in Visual C++ 2010 anymore.
How can I find out the size of the functions or the whole namespace/stub by using pragma directives, compiler/linker facilities or similar?
Comment: Namespaces don't imply the storage for the contained types and functions, they are a syntactical tool.
Comment: The compiler doesn't have to order the code in order of declaration and definitely won't as soon as optimizations are enabled.
Comment: I know, but basically the question is about any kind of bundle of functions (given a first and a last function, where the last function may also be empty, like in the example)
Comment: I would be interested why you want to do this?
Comment: Remote Code Injection -> Getting the kernel32.dll address after starting a process with CreateProcess with THREAD_SUSPENDED. The Toolhelp32 API can not read the LDR table at that point yet.
Answer: With the new push in security these days (heap randomization, layout randomization, etc..) I think this is going to be much more difficult. You may end up having to just copy each function individually.
Answer: You can try and place each function in a different section, using the VC++ equivalent  GCC's attribute ((section ("name")))  http://www.delorie.com/gnu/docs/gcc/gcc_62.html and then use your technique, or you could place each function in a different source file.
Answer: The C++ language provides no guarantees for finding addresses or sizes of namespaces. That said, venture into assembly language and linker instructions.
Many assembly languages have an opcode or mnemonic for placing code at specific addresses.  This allows a label to be set up to indicate the start of a memory area.  Some linkers have variables for obtaining segment starting addresses and sizes.  These would be user defined logical addresses.
In summary, use your assembly and linker tools to define public symbols for the namespace start and length or optionally the end of the segment.  In your C++ program, access these labels as extern.
Comment: Can you give examples for the directives in Visual C++?


When using env.yml with conda whats the difference between dependencies and pip dependencies?

Question: I am creating a .SH script for setting up automatically my dev environment in Azure ML, according to this:
https://learn.microsoft.com/en-gb/azure/machine-learning/how-to-customize-compute-instance
The script looks like this:
#!/bin/bash

set -e
# https://pypi.org/project/azure-ai-ml/
# Requires: Python <4.0, >=3.7
# This script creates a custom conda environment and kernel based on a sample yml file.

conda env create  python=3.10
#conda env create -f env.yml

echo "Activating new conda environment"
conda activate envname
conda install -y ipykernel
echo "Installing kernel"
sudo -u azureuser -i <<'EOF'
conda activate envname
python -m ipykernel install --user --name envname --display-name "mykernelp310v2"
echo "Conda environment setup successfully."
pip install azure-ai-ml
EOF

my env looks like this:
name: p310v2

dependencies:
  - python=3.10
  - numpy
  - matplotlib
  - pandas
  - scikit-learn
  - pip:
       -kaggle==1.5

When I check this document:
https://carpentries-incubator.github.io/introduction-to-conda-for-data-scientists/04-sharing-environments/index.html
I am confused between the dependencies section and the pip section.  For example scikit-learn I could put in dependencies but also on the pip section, so whats the deal here?
Answer: dependencies are conda dependencies; listing them is equivalent to run conda install <deps>. For example conda installs numpy from https://anaconda.org/conda-forge/numpy .
pip means pip dependencies for pip install command; pip installs them from PyPI.org. For example, https://pypi.org/project/numpy/
The same for scikit-learn: https://anaconda.org/search?q=scikit-learn and https://pypi.org/search/?q=scikit-learn
See also https://stackoverflow.com/search?q=%5Bconda%5D+%5Bpip%5D+difference
Comment: @LuisValencia No, there're packages available only on Anaconda/conda or only on PyPI/pip. Some package are available on both channels, in that case using `conda` is preferable if you already use `conda`. Use `pip` for projects where you don't use `conda` at all or where packages at Anaconda are not available.
Comment: so I could install  any pip package in the conda dependencies or viceversa, the end result will be the same?


If we draw 7 cards from a standard 52 card deck

Question: If we draw 7 cards from a standard 52-card deck, what is the probability that all 7 cards are hearts?
Probability =
I already did (13/52), (12/51), (11/50), (10/49),(9/48), and (8/47), and it is (7/46) as the answer once I put in as the answer for the problem. I got it wrong. What did I do wrong?
Comment: What have you tried?
Comment: Can you solve it for $1$ card? how about $2$?
Comment: Well, I thought so.  sorry I am not smart
Comment: It looks like you gave the (conditional) probability ($\frac{7}{46}$) of getting a heart on the seventh card given that the first six cards all were hearts.
Answer: Thanks for putting in your attempt. You have the right pieces, you just need to put them together:

The probability of the first card being a heart is indeed $13/52$.
The probability of the second card being a heart given that the first card was a heart is indeed $12/51$.
The probability of the third card being a heart given that the first two cards were both hearts is indeed $11/50$.
And so on.

In these situations, since you need all seven events to happen to succeed, the probabilities must be multiplied together:
\begin{align}
P(\text{all seven cards are hearts})
    & = \frac{13}{52} \times \frac{12}{51} \times \frac{11}{50} \times
        \frac{10}{49} \times \frac{9}{48} \times \frac{8}{47} \times
        \frac{7}{46} \\
    & = \frac{13 \times 12 \times 11 \times 10 \times 9 \times 8 \times 7}
             {52 \times 51 \times 50 \times 49 \times 48 \times 47 \times 46}
        \\
    & = \cdots
\end{align}
You can, I imagine, do the cancellation yourself. Note that the fraction in the second line can be written more succinctly, as in Vadim Chernetsov's answer, as
$$
P(\text{all seven cards are hearts}) = \frac{\binom{13}{7}}{\binom{52}{7}}
$$
where
$$
\binom{n}{k} = \frac{n!}{k!(n-k)!}
$$
is the binomial coefficient. The reasoning, which is more concise, but requires you familiarize yourself with the binomial coefficient's interpretation, is that there are $\binom{52}{7}$ ways to select $7$ cards out of $52$ (all equally likely), of which $\binom{13}{7}$ consist of all hearts.
Answer: $$
\frac{\binom{13}{7}}{\binom{52}{7}}.
$$


jQuery function not called in jsFiddle

Question: Here is my code in jsFiddle:
http://jsfiddle.net/AXXGZ/4/

html

        aa

javascript
$('#a').click(function(){
    alert ('aa');

})

run
onLoad with MooTools 1.3.2

Why is my click callback function not called?
Comment: Too difficult to post your code here?
Comment: @Oded wouldn't have helped any, the issue was in the fiddle
Comment: @mazlix - fair enough, in this case.
Comment: @hristo you gave the solution first could u post it as an answer so i can mark it
Answer: Because, you're using mootools on the fiddle... always happens to me too :p
http://jsfiddle.net/mazlix/AXXGZ/6/
Answer: You aren't using jQuery. Select it from the drop-down at the left and your code works.
However your HTML also has a syntax error; you should remove the comma from this tag:
aa

Answer: You're not using jQuery in your fiddle
http://jsfiddle.net/AXXGZ/14/
Answer: You're using mootools, look
http://jsfiddle.net/AKbnp/4/
Edit: Damn...Almost 3 answers before mine...
Answer: When jsfiddle loads, it sets Mootools as the default JavaScript Framework. Your syntax looks like jQuery... so you should select it.

I hope this helps.
Hristo

jQuery function not called in jsFiddle


Consultar um único item no banco de dados PHP

Question: A minha consulta só retorna um valor, e esse valor preciso usar em outra consulta. Como posso pegar esse valor sem colocar em um array?
Como está feito no código ele coloca o valor em um array, assim não consigo colocar na consulta.
<code>       <?php

        $login_email;
        $login_senha;
        $sql = "SELECT idCliente FROM CLIENTES WHERE dsEmail='$login_email' and dsSenha='$login_senha'";

        $result = mysqli_query($conn, $sql);

        while ($idCliente = mysqli_fetch_array($result, MYSQLI_NUM)){
            echo $idCliente[0];
        }

        $sql = "SELECT dsProduto, vlUnitario from produtos, carrinhos_produtos,carrinhos where (produtos.idProduto = carrinhos_produtos.idProduto)
        and (carrinhos_produtos.idCarrinho = carrinhos.idCarrinho) and ($idCliente = carrinhos.idCliente)";
        $result = mysqli_query($conn, $sql);
    ?>
</code>
Answer: É só você ler apenas uma linha com fetch_assoc e utilizar posteriormente no que deseja
<code>   <?php
        $login_email;
        $login_senha;
        $sql = "SELECT idCliente FROM CLIENTES WHERE dsEmail='$login_email' and dsSenha='$login_senha'";

        $result = mysqli_query($conn, $sql);
        $row = $result->fetch_assoc();
        $idCliente = $row['idCliente'];

        $sql2 = "SELECT dsProduto, vlUnitario from produtos, carrinhos_produtos,carrinhos where (produtos.idProduto = carrinhos_produtos.idProduto)
                and (carrinhos_produtos.idCarrinho = carrinhos.idCarrinho) and ($idCliente = carrinhos.idCliente)";
                $result2 = mysqli_query($conn, $sql2);
        ...
    ?>
</code>


Fullcalendar event url - add class if url contains

Question: Some of my Fullcalendar events have links.  The links point to either public webpages, pdf documents or webpages which are restricted access.
I would like to add a class to format the links to add an icon, based on url string.
If the url contains:

"pdf" addclass "fc-pdf"
"restricted" addclass "fc-lock"

I assume it should be with and eventRender... but I'm having trouble find the right syntax.  Can someone help me with this?
http://jsfiddle.net/lbriquet/oez9Ltym/
    $('#calendar').fullCalendar({
          header: {
            left: 'prev,next today',
            center: 'title',
            right: 'listDay,listWeek,month'
          },
          views: {
            listDay: {
              buttonText: 'list day'
            },
            listWeek: {
              buttonText: 'list week'
            }
          },
          defaultView: 'listDay',
          defaultDate: '2016-09-12',
          navLinks: true, // can click day/week names to navigate views
          events: [{
            title: 'Conference (website)',
            start: '2016-09-11',
            end: '2016-09-13',
            url: "https://www.ted.com/talks"
          }, {
            title: 'Meeting (download document)',
            start: '2016-09-12T10:30:00',
            end: '2016-09-12T12:30:00',
            url: "http://storage.ted.com/tedx/manuals/tedx_speaker_guide.pdf"
          }, {
            title: 'Lunch',
            start: '2016-09-12T12:00:00'
          }, {
            title: 'Meeting (members only)',
            start: '2016-09-12T14:30:00',
            url: "http://www.dictionary.com/browse/restricted"
          }, {
            title: 'Happy Hour',
            start: '2016-09-12T17:30:00'
          }, {
            title: 'Dinner',
            start: '2016-09-12T20:00:00'
          }],
        eventRender: function eventRender(event, element, view) {
        }
        });

Answer: The way I got this to work was by adding a type to the events simply because I think it would be easier than dealing with regex that might not always work. So events don't need a type but they can have a type pdf, restricted or whatever else you need. In eventRender I added the following:
eventRender: function eventRender(event, element, view) {
  if(typeof event.type !== 'undefined') {
    if(event.type === 'pdf') {
        element.addClass('fc-pdf');
    } else if(event.type === 'restricted') {
        element.addClass('fc-lock');
    }
  }
}

A check to see if the type is provided or not and then if statements for adding the class based on the type. I also had to make a small change to the css selector, changing a.fc-lock to .fc-lock a  to allow it to display properly. Here is the JS Fiddle showing this.
Comment: Thank you very much @Ryan89
This does what I need!!


Angular reactive forms: sync multiple inputs with a single formControlName

Question: I'm building a reactive form in Angular 11. It's split up across multiple divs, and the project owner wants a few repeated inputs in each of those divs so that a user can edit an input for some field A, and all of the divs' inputs for field A will show the updated value.
I like corylan's approach:
<input [formControl]="myCtrl" [value]="myCtrl.value" />
<input [formControl]="myCtrl" [value]="myCtrl.value" />
<input [formControl]="myCtrl" [value]="myCtrl.value" />

...but I want to achieve this with formControlName instead of formControl so that I can take advantage of formGroups (and not have each form control be a member of my component object). However, lacking a reference to the the actual myCtrl would ruin the binding at [value].
Is there a good strategy for me to specify the form control by name only and have all of these inputs use a single control? Or is there a different good way to sync inputs in Angular reactive forms when there are quite a few different sets to sync?
Comment: @akkonrad kind of, but there are two problems: (1) unless I'm working with inputs that lend themselves to an array, the use of of FormArray would make the surrounding component brittle. (If I ever need to add or remove an element, the indicies for all subsequent elements needs to be changed. And if one of our html/css guys adds/removes an input, he's going to have no idea why everything broke, and (2) my ng app still wouldn't compile because my inputs exist before some of the controls.
Comment: I you can try it with [FormArray](https://angular.io/api/forms/FormArray)
Answer: This can be achieved by setting value to the forms controls actual value.
<form [formGroup]="searchForm">
  <input placeholder="search" formControlName="search" [value]="searchForm.value.search" />
  <input placeholder="search" formControlName="search" [value]="searchForm.value.search" />
  <input placeholder="search" formControlName="search" [value]="searchForm.value.search" />
</form>

STACKBLITZ: https://stackblitz.com/edit/angular-y6gxf6?file=src%2Fapp%2Fapp.component.html
Comment: Good answer. I would add that you can also use `searchForm.value.search` for the value property.


Regular action and integers modulo $p-1$ and $p$

Question: For $p$ a prime number, let's denote:
$$G:=\mathbb Z/(p-1)\mathbb Z = \{[i]_{p-1}\mid i=0,1,\dots,p-2\}$$
and:
$$X:=\mathbb Z/p\mathbb Z\setminus \{[0]_p\} = \{[j]_p\mid j=1,2,\dots,p-1\}$$
Does $G$ regularly (=transitively+freely) act on $X$, somehow?
My first idea was to try with $[i]_{p-1}\mapsto([j]_p\mapsto[i+j]_p)$, but of course it can't work, as $[i+j]_p=[0]_p$ as soon as $i+j=p$, and hence $[i+j]_p$ may well not even lie in $X$.
Edit. In the spirit of the question, I "don't know" that $(\mathbb Z/p\mathbb Z)^\times$ is cyclic (of order $p-1$).
Comment: The answer to the question that you asked is yes because $|G| = |X|$. The result follows from Cayley's Theorem. The structure of $({\mathbb Z}/p{\mathbb Z})^*$ is irrelevant.
Comment: The *group* $X=(\Bbb Z/p\Bbb Z)^*$ is *isomorphic* to $G$. The [action by translations of any group on itself](https://en.wikipedia.org/wiki/Cayley%27s_theorem) is transitive and free.
Comment: Does this answer your question? [Show that the multiplicative group $(\mathbb{Z}/p\mathbb{Z})^*$ is cyclic](https://math.stackexchange.com/questions/2349414/show-that-the-multiplicative-group-mathbbz-p-mathbbz-is-cyclic) (and every cyclic group $G$ of order $n$ is naturally isomorphic to $(\Bbb Z/n\Bbb Z,+)$, once you choose a generator of $G$)
Comment: Sure! $G\stackrel{Cayley}{\hookrightarrow}S_G\stackrel{|G|=|X|}{\cong} S_X$. And Cayley's embedding is (equivalent to) a regular action. I'll try to build them (composition) up explicitly. Thank you, @DerekHolt.
Comment: Is there any chance to deal directly with $G$ for what it is, namely the additive group of the integers modulo $p-1$, @AnneBauval?
Answer: Each group acts on itself transitively and freely, and $\Bbb Z/(p-1)\Bbb Z\cong\Bbb Z_p^*$.
Note: This is CW. Credit to @AnneBauval. See the comments.
Comment: Note that as I pointed out in a comment, you don't actually need the fact that $Z/(p-1)Z$ and $Z_p^*$ are isomorphic to answer the question. It is enough that they have the same order.
Comment: (+1 to CW) Maybe you were right to edit an answer. I was intending to link instead as a duplicate, but didn't know which one of the 2 parts of the argument was less known to the OP.
Comment: Why to mention $Z_p^*$ at all, @DerekHolt?
Comment: Because you mentioned it yourself in the question.
Comment: Not originally, only later when others' answer and comments brought it into the discussion.


Encontrar horário dentro de um range de horas

Question: Estou tentando desenvolver uma lógica onde existirá um horário qualquer que eu preciso encontrar dentro de um range de horas (Hora inicial e hora final)
Porém não consigo fazer a comparação corretamete e/ou não estou tratando certo.
Nos testes usei a hora de comparação: 03:37:33 para encontrar nos ranges
Segue código:
    class Program
    {
        static void Main(string[] args)
        {
        DateTime dtImportacao = new DateTime(2019,07,01,03,33,37);

        TimeSpan[] datasInicias = new TimeSpan[]
        {

        new TimeSpan(06,00,00),
        new TimeSpan(00,00,00),
        new TimeSpan(23,00,00),
        new TimeSpan(06,00,00),
        new TimeSpan(19,00,01),
        new TimeSpan(06,00,00),
        new TimeSpan(23,00,00),
        new TimeSpan(08,00,00),
        new TimeSpan(19,00,00),
        new TimeSpan(19,00,00),
        new TimeSpan(06,00,00),
        new TimeSpan(22,00,00),
        new TimeSpan(23,00,00),
        new TimeSpan(06,00,01)
    };
        TimeSpan[] datasFinais = new TimeSpan[]
        {
        new TimeSpan(23,00,00),
        new TimeSpan(23,59,59),
        new TimeSpan(06,00,00),
        new TimeSpan(19,00,00),
        new TimeSpan(05,59,59),
        new TimeSpan(23,00,00),
        new TimeSpan(06,00,00),
        new TimeSpan(20,00,00),
        new TimeSpan(06,00,00),
        new TimeSpan(05,45,59),
        new TimeSpan(22,00,00),
        new TimeSpan(06,00,00),
        new TimeSpan(06,00,00),
        new TimeSpan(22,59,59)
        };

        for (int i = 0; i < datasInicias.Length; i++)
        {

            if (TimeSpan.Compare(dtImportacao.TimeOfDay, datasInicias[i]) == -1 || TimeSpan.Compare(dtImportacao.TimeOfDay, datasFinais[i]) == 1)
            {
                Console.WriteLine("Parametro de Comparação: {0}   | {1}  Até {2} Fora", dtImportacao.TimeOfDay, datasInicias[i], datasFinais[i]);
            }
            else
            {
                Console.WriteLine("Parametro de Comparação: {0}   | {1}  Até {2} Dentro", dtImportacao.TimeOfDay, datasInicias[i], datasFinais[i]);
            }

        }

        Console.ReadKey();
    }
}

Retorno do console:
//Parametro de Comparação: 03:33:37 | 06:00:00  Até 23:00:00 Fora
//Parametro de Comparação: 03:33:37 | 00:00:00  Até 23:59:59 Dentro
//Parametro de Comparação: 03:33:37 | 23:00:00  Até 06:00:00 Fora
//Parametro de Comparação: 03:33:37 | 06:00:00  Até 19:00:00 Fora
//Parametro de Comparação: 03:33:37 | 19:00:01  Até 05:59:59 Fora
//Parametro de Comparação: 03:33:37 | 06:00:00  Até 23:00:00 Fora
//Parametro de Comparação: 03:33:37 | 23:00:00  Até 06:00:00 Fora
//Parametro de Comparação: 03:33:37 | 08:00:00  Até 20:00:00 Fora
//Parametro de Comparação: 03:33:37 | 19:00:00  Até 06:00:00 Fora
//Parametro de Comparação: 03:33:37 | 19:00:00  Até 05:45:59 Fora
//Parametro de Comparação: 03:33:37 | 06:00:00  Até 22:00:00 Fora
//Parametro de Comparação: 03:33:37 | 22:00:00  Até 06:00:00 Fora
//Parametro de Comparação: 03:33:37 | 23:00:00  Até 06:00:00 Fora
//Parametro de Comparação: 03:33:37 | 06:00:01  Até 22:59:59 Fora

Como deveria sair:
Comment: Porque está a comparar `TimeSpan` com `DateTime`?
Comment: TimeSpan são intervalos de tempo, não são datas como você indica nas suas variáveis.
Answer: A expressão está verificando se o horário está dentro do período específico, mas você não está contando se o período for outro dia, portanto, se passar das 24hrs, o resultado não estará dentro do campo do dia anterior.
A expressão que você precisa é:
bool dentroDoPeriodo = !(min <= max ? (val >= min && val <= max) : (val >= min || val <= max));

Explicação da expressão:
var min = datasInicias[i];
var max = datasFinais[i];
var val = dtImportacao;

bool dentroDoPeriodo =
! (                       // Inverte o resultado lógico da expressão
    min <= max            // Se o horário inicial for < que o final       [1]
    ?                     // Início da condição em-linha
    (                     // (Condição Verdadeira de [1]) Se [1] == True
        val >= min        // Se o horário de importação for maior ou igual ao inicial
        &&                // E também se
        val <= max        // o mesmo for menor ou igual ao horário final
    ) : (                 // (Condição Falsa de [1]) Se [1] == False
        val >= min        // Se o horário de importação for maior ou igual ao inicial
        ||                // Ou também se
        val <= max        // o mesmo for menor ou igual ao horário final
    )                     // Retorna o sub-circuíto de [1].
);                        // Retorna o circuíto [1]

Além disso, a comparação de DateTime e TimeSpan não faz sentido nesta situação. Você está comparando horas com horas, não datas com horas. Mude no seu código:
de DateTime dtImportacao = new DateTime(2019,07,01,03,33,37);
para: TimeSpan dtImportacao = new TimeSpan(03, 37, 33);

Veja funcionando no .NET Fiddle.
Comment: Estou adaptando seu código para javascript, muito bom.
Answer: Você não está considerando que as horas possam atravessar o dia.
Basicamente, o que você precisa é alterar a validação para algo como:
Inicio > Fim
 ? data <= Inicio && data <= Fim
 : data >= Inicio && data <= Fim

O que pode ser simplificado para:
(Inicio > Fim && data <= Inicio || data >= Inicio) && data <= Fim;

Veja o código completo. Tentar dar uma melhorada na estrutura do código pra ficar mais legível.
using System;
using static System.Console;

struct Intervalo
{
    public Intervalo(TimeSpan inicio, TimeSpan fim)
    {
        Inicio = inicio;
        Fim = fim;
    }

    public TimeSpan Inicio { get; set; }
    public TimeSpan Fim { get; set; }
    public bool AtravessaDia => Inicio > Fim;

    public bool EstáNoIntervalo(TimeSpan data)
    {
        return AtravessaDia
            ? data <= Inicio && data <= Fim
            : data >= Inicio && data <= Fim;
    }
}

class Program
{
    static void Main(string[] args)
    {
        DateTime dtImportacao = new DateTime(2019, 07, 01, 03, 33, 37);

        var intervalos = new []
        {
            new Intervalo(new TimeSpan(06, 00, 00), new TimeSpan(23, 59, 00)),
            new Intervalo(new TimeSpan(23, 00, 00), new TimeSpan(02, 00, 00)),
            new Intervalo(new TimeSpan(00, 00, 00), new TimeSpan(23, 59, 59)),
            new Intervalo(new TimeSpan(23, 00, 00), new TimeSpan(06, 00, 00)),
            new Intervalo(new TimeSpan(06, 00, 00), new TimeSpan(19, 00, 00)),
            new Intervalo(new TimeSpan(19, 00, 01), new TimeSpan(05, 59, 59)),
            new Intervalo(new TimeSpan(06, 00, 00), new TimeSpan(23, 00, 00)),
            new Intervalo(new TimeSpan(23, 00, 00), new TimeSpan(06, 00, 00)),
            new Intervalo(new TimeSpan(08, 00, 00), new TimeSpan(20, 00, 00)),
            new Intervalo(new TimeSpan(19, 00, 00), new TimeSpan(06, 00, 00)),
            new Intervalo(new TimeSpan(19, 00, 00), new TimeSpan(06, 00, 00)),
            new Intervalo(new TimeSpan(02, 00, 00), new TimeSpan(04, 00, 00)),
            new Intervalo(new TimeSpan(02, 59, 00), new TimeSpan(03, 00, 00)),
            new Intervalo(new TimeSpan(03, 34, 00), new TimeSpan(03, 40, 00)),
            new Intervalo(new TimeSpan(03, 32, 00), new TimeSpan(03, 40, 00)),
            new Intervalo(new TimeSpan(03, 40, 00), new TimeSpan(03, 34, 00)),
            new Intervalo(new TimeSpan(03, 40, 00), new TimeSpan(03, 32, 00)),
        };

        WriteLine($"Parâmetro de Comparação: {dtImportacao.TimeOfDay}\n");
        foreach(var intervalo in intervalos)
            WriteLine($"{intervalo.Inicio} - {intervalo.Fim} = {(intervalo.EstáNoIntervalo(dtImportacao.TimeOfDay) ? "Dentro" : "Fora")} ");
    }
}

Veja funcionando no Repl.it
Comment: Não sabia que você era o @jfbueno até ver este link.
Comment: @CypherPotato Como assim? Não sabia que eu era o jfbueno da onde?
Comment: Já tinha visto esse nick em algum lugar, provavelmente aqui, *repl.it/@jfbueno*