Resultado php em um Modal W3.CSS

Question: Olá! estou testando o W3.CSS e gostei bastante do que vi até que travei em um form com o resultado dentro de um Modal.
Minha dificuldade é quando o evento "onclick" submete o form, ele abre o modal e a página dá um refresh sem passar os dados para o Modal.
GitHub

<!DOCTYPE html>

 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <title>FORM + W3.CSS</title>
 <link rel="stylesheet" href="https://www.w3schools.com/lib/w3.css">

Meu Form

 <form action="#" class="w3-content w3-container" style="width: 500px;">

   Nome
   <input id="nome" class="w3-input" type="text" name="nome">

    <button onclick="abreModal()" class="w3-button">Abrir Modal</button>

</form>

      ×
       <?php
        $nome= $_GET['nome'];
   echo $nome;
  ?>

Answer: Amigo,
Se eu entendi corretamente apenas falta a execução do método que abre a modal, que seria abreModal().
Pela simplicidade do código, isso já funcionaria:

Em tempo, se o seu aprendizado é apenas com o comportamento da modal, você não precisaria nem envolver o php, tratando dinamicamente o conteúdo do HTML:

<!DOCTYPE html>

 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <title>FORM + W3.CSS</title>
 <link rel="stylesheet" href="https://www.w3schools.com/lib/w3.css">

Meu Form

 <form class="w3-content w3-container" style="width: 500px;" action="javascript:void(0)">

   Nome
   <input id="nome" class="w3-input" type="text" name="nome">

    <button onclick="abreModal()" class="w3-button">Abrir Modal</button>

 </form>

    ×

Resultado php em um Modal W3.CSS


How to define the category Pos of posets as a presheaf

Question: The category of Sets, $\textbf{Set}$, can be described as a presheaf, namely, take the category of one object with the identity morphism, the functors from that to Sets give the different sets in $\textbf{Set}$.
How can you describe the category $\textbf{Pos}$ of posets this way? I thought that you could take another category with one object, with the identity arrow, but also other arrows that then give the relations in the poset. Maybe an arrow can describe a relation if the functor maps it to a function in sets, that maps an element to another element that is the most closely related and otherwise just to itself? (so if $x \leq y \leq z$, then the function in Sets maps $x$ to $y$, $y$ to $z$ and the rest to itself?)
Answer: This is not possible: there are properties that every presheaf category has that $\mathbf{Pos}$ does not.  For instance, in any presheaf category, any morphism that is both monic and epic is an isomorphism (proof sketch: a morphism is monic iff it is pointwise injective and epic iff it is pointwise surjective).  But this is not true in $\mathbf{Pos}$.  For instance, let $X=\{a,b\}$ with the discrete ordering ($a$ and $b$ are incomparable) and let $Y=\{a,b\}$ with the ordering $a\leq b$.  Then the identity map $X\to Y$ is order-preserving and is both monic and epic in $\mathbf{Pos}$, but is not an isomorphism (its inverse is not order-preserving).
Answer: No, not as an arbitrary presheaf. We're sunk pretty much from the get-go. The theory of posets consists of a binary relation symbol, i.e. a monomorphism $R\rightarrowtail X\times X$ so already we need the functors to preserve finite products and monomorphisms. Typically what are used are what are called left exact (lex) or finite limit theories (these are synonyms) or (ambiguously) cartesian theories, and we then require the functors to be left exact/finite limit preserving/cartesian(again, ambiguously).  A left exact theory is more than we need (per Kevin Carlson's comment and the linked paper, a Horn theory suffices), but we still need more structure (such as finite products) than an arbitrary functor will preserve.
Comment: Your complaint about $\exists$ doesn't quite go through here if we view the edges as an extra sort and associativity as a composition function-a poset is just a special category, after all! Indeed, posets are (finitely accessibly) reflective in categories-identify isomorphic objects and parallel arrows. Thus posets are finitely presentable, and must model a finite limit theory. In fact, posets can be axiomatized in Horn logic, the logic of functions, relations, equality, and finite conjunctions! Generally, we can avoid your situation with $\exists$ by assuming $y$ as a context.
Comment: @KevinCarlson Good point. I was uncertain about this but an obvious resolution didn't jump to mind. It felt wrong though, so thank you for the comment.


Better way to add a number to itself and print the last value only

Question: I want to fetch the amount from database and want to store total of those amount in a variable and print that variable. I searched and got a link to add a number to itself and tried it in my code but i didn't get the output as was expected.
Here is my code..
 <?php
 $cid = $_REQUEST['cname'];
 $cmd = mysql_query("SELECT amount FROM fund WHERE clientid = $cid");
 while($row = mysql_fetch_array($cmd)) {
    $acnt += $row['amount'];
    echo $acnt;
 }
 ?>

The output that I have got through this is like- 10001200130015002000.
But I am just expecting the last added value that is 2000 only as my output.
Comment: Try echoing $acnt after the while loop. You should also set $acnt = 0 before the loop starts. And you could do this faster with a SUM in MySQL.
Comment: you can print $row['amount'] outside the while loop. It will display only the last value added in the variable.
Comment: this question is confusing-

you are expecting `2000` which is last inserted value.

But, outputting the variable `$acnt` which mentioning summation of `amount`
Comment: @Kumar you may using Insert record wizard on your page so please use of `isset` to perform your particular task on your submit button click.
Comment: I always use isset command before submitting values but still the same problem occurs
Comment: This question is unclear; on one hand you're asking for what seems to be a simple summation problem, but at the same time you're asking another question about insertion ... which is it?
Comment: Explain me these - a. `10001200130015002000`, b. `total of those amount`, c. `last added value`, d. `2000`. Question is totally unclear. You were totally vice-versa one point from another point.
Comment: @kumar Follow this link to solve you second problem on submit button http://www.webdeveloper.com/forum/showthread.php?235322-multiple-submit-buttons-on-a-single-form
Answer: Let MySQL do the work for you instead of doing the loop:
$cmd = mysql_query("select sum(amount) amount from fund where clientid = '$cid'");
$row = mysql_fetch_assoc($cmd);
$acnt = $row['amount'];
echo $acnt;

Btw, you must escape raw input or use a formatting function like this:
$sql = sprintf('select sum(amount) amount from fund where clientid = %d', $cid);
$cmd = mysql_query($sql);
// ...

Or better yet, use either PDO or mysqli and learn about prepared statements.
Answer: Try This Code:
You don't have need to use of loop.on behalf that just do sum of amount using sql query.
$cmd = mysql_query("select sum(amount) amount from fund where clientid = $cid");
$row = mysql_fetch_array($cmd);
$acnt = $row['amount'];
echo $acnt;

Comment: One more question. Why the value get added to database just on refreshing page in ? how can we stop this?
Comment: what is your question?
Comment: are you using of submit button to retrieve data from database?
Comment: Actually when ever i refresh my page the values that i had put as input in the last operation gets added to my data base just on refreshing the page without giving any input..
Comment: are you using insert record wizard on your page to insert new record in database?
Comment: why somebody just passed and voted down to all answers?
Comment: All answers except yours now :)
Comment: As you said you are using Insert command on your submit button so use of different submit button to get the sum of amount and this you can get by the use of isset on your page.
Comment: @jack I don't know why?Even your answer  is better then my answer.
Answer: You are echoing the value each time inside the while loop that's why you are getting the amount displayed each time. Echo the amount after the while loop.
 while($row = mysql_fetch_array($cmd))
   {
    $acnt += $row['amount'];
  }
echo $acnt;

Comment: One more question. Why the value get added to database just on refreshing page in ? how can we stop this?
Comment: Is there any insert query in the page associated with this?


Angular (2+): HttpClient, subscribe, xhr

Question: Situation:
I'm using Angular CLI. And I'm trying to receive data from the server side (node.js, express). I created new component card-object. I copied this code from the example on this page: https://angular.io/guide/http
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
import { MatGridListModule, MatCardModule } from '@angular/material';

import { AppComponent } from './app.component';
import { CardObjectComponent } from './card-object/card-object.component';

@NgModule({
  declarations: [
    AppComponent,
    CardObjectComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    MatGridListModule,
    MatCardModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html:
<app-card-object></app-card-object>

card-object.component.ts:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-card-object',
  templateUrl: './card-object.component.html',
  styleUrls: ['./card-object.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class CardObjectComponent implements OnInit {
  results: string[];

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('http://localhost:3000/?cll=bjc').subscribe(data => {
      this.results = data['results'];
    });
   }
}

card-object.component.html:

{{results[0]}}

some text

node.js:
app.get('/', (req, res) => {
    var reqCard = {
        results: ['text 1', 'text 2']
    };
    res.json(reqCard);
});

Problem:
I see that json data I receive successfully (I can see them in google DevTool => Network => XHR). But everything that I see in my angular app is 'some text'. And I see ERROR TypeError: Cannot read property '0' of undefined in my DevTool console.
Question:
Where is a mistake? What have I missed?
Comment: Possible duplicate of [Angular2: Cannot read property 'name' of undefined](https://stackoverflow.com/questions/39755336/angular2-cannot-read-property-name-of-undefined)
Answer: Initialize your array so that it has a value before the async call completes:
  ngOnInit(): void {
    this.results = []
    this.http.get('http://localhost:3000/?cll=bjc').subscribe(data => {
      this.results = data['results'];
    });
   }

Bind if results has data:

{{results.length > 0 ? results[0]: ''}}

some text

Comment: Thanks, I don't have any error messages in DevTool console. But I still can't see _'text 1'_ in my angular app.
Comment: I can't possibly see how your code will work without errors, unless you do what I have suggested above, at a minimum
Comment: show us the content of `results` : `console.log(results)`
Comment: @BougarfaouiElhoucine `results is not defined`
Comment: sorry this : console.log(this.results)
Comment: @BougarfaouiElhoucine console.log in subscribe function gives me nothing;
console.log after subscribe functiongives me empty array
Comment: so your array is empty so there's no data to show in your html
Comment: @BougarfaouiElhoucine I understand that, but I can see received data in DevTools in tab Network: xhr. As I understand the problem is in setting value, but I can't solve it.


Setar item selecionado da ComboBox conforme clicado na jTable

Question: Estou tentando preencher os campos de um formulário conforme o item clicado na jTable. Os campos de textos são preenchidos normalmente, mas a comboBox permanece com o valor default selecionado.
//método que preenche a comboBox
public void fillCBFornecedor(){
    fornCtrl = new FornecedorControle();
    cbFornecedor.removeAllItems();

    for(Object fornecedor: fornCtrl.listar()){
        cbFornecedor.addItem(fornecedor);
    }
}//aqui eu preencho a ComboBox com os itens trazidos da camada de controle(abaixo) que usa a camada DAO para fazer a busca no banco

//método que preenche a jTable
private void fillJTProdutos(){
    prodCtrl = new ProdutoControle();

    jtProdutos.removeAll();
    jtProdutos.setModel(prodCtrl);
}//aqui eu uso a camada de controle que implementa uma AbstractTableModel para preencher minha JTable

//preenche os campos conforme o item clicado
private void fillCampos(){
    txtProduto.setText((String) jtProdutos.getValueAt(jtProdutos.getSelectedRow(), 0));
    cbFornecedor.setSelectedItem(jtProdutos.getValueAt(jtProdutos.getSelectedRow(), 1));
    cbMarca.setSelectedItem(jtProdutos.getValueAt(jtProdutos.getSelectedRow(), 2));
    cbGenero.setSelectedItem(jtProdutos.getValueAt(jtProdutos.getSelectedRow(), 3));
    txtValor.setText(String.valueOf((Float) jtProdutos.getValueAt(jtProdutos.getSelectedRow(), 4)));
    txtMin.setText(String.valueOf((Integer) jtProdutos.getValueAt(jtProdutos.getSelectedRow(), 5)));
    txtMax.setText(String.valueOf((Integer) jtProdutos.getValueAt(jtProdutos.getSelectedRow(), 6)));
}
//atributos e métodos da camada de controle
public class ProdutoControle extends AbstractTableModel{

private final ProdutoDAO pDAO = new ProdutoDAO();
private Produto produto;
private Marca marca;
private Genero genero;
private Fornecedor fornecedor;

@Override
public String getColumnName(int coluna) {
    return colunas[coluna];
}

@Override
public int getRowCount() {
    return pDAO.buscar().size();
}

@Override
public int getColumnCount() {
    return colunas.length;
}

@Override
public Object getValueAt(int linha, int coluna) {
    switch(coluna){
        case 0:
            return pDAO.buscar().get(linha).getDescricao();
        case 1:
            return pDAO.buscar().get(linha).getMarca();
        case 2:
            return pDAO.buscar().get(linha).getGenero();
        case 3:
            return pDAO.buscar().get(linha).getFornecedor();
        case 4:
            return pDAO.buscar().get(linha).getValor_unitario();
        case 5:
            return pDAO.buscar().get(linha).getEstoque_min();
        case 6:
            return pDAO.buscar().get(linha).getEstoque_max();
        default:
            return null;
    }
}

//atributos e métodos da camada DAO
public class ProdutoDAO {

private Connection con = null;
private PreparedStatement stmt = null;
private ResultSet rs = null;
String sql = null;

private Produto produto;
private Fornecedor fornecedor;
private Marca marca;
private Genero genero;

public List<Produto> buscar(){
    con = ConexaoBanco.getConexao();
    List<Produto> produtos = new ArrayList<>();

    sql = "SELECT * FROM view_produtos";

    try{
        stmt = con.prepareStatement(sql);

        rs = stmt.executeQuery();

        while(rs.next()){
            fornecedor = new Fornecedor();
            marca = new Marca();
            genero = new Genero();
            produto = new Produto(marca, genero, fornecedor);

            produto.setId(rs.getInt(1));
            produto.setDescricao(rs.getString(2));
            produto.getMarca().setDescricao(rs.getString(3));
            produto.getGenero().setDescricao(rs.getString(4));
            produto.getFornecedor().setRazao_social(rs.getString(5));
            produto.setValor_unitario(rs.getFloat(6));
            produto.setEstoque_min(rs.getInt(7));
            produto.setEstoque_max(rs.getInt(8));
            produto.setAtivo(rs.getInt(9));

            produtos.add(produto);
        }
    }
    catch(SQLException ex){
        JOptionPane.showMessageDialog(null, ex, "Erro", 0);
    }
    finally{
        ConexaoBanco.fechar(con, stmt, rs);
    }
    return produtos;
}//na camada DAO faço um select na view de produtos e preencho um objeto com os dados trazidos.

//Inicialização da ComboBox

cbFornecedor = new javax.swing.JComboBox();
cbFornecedor.setToolTipText("");

//evento click do mouse na tabela
private void jtProdutosMouseClicked(java.awt.event.MouseEvent evt) {
    fillCampos();
}

Há alguma forma de definir o item selecionado na ComboBox conforme o item selecionado na JTable?
Comment: E se nenhuma linha estiver selecionada? Desativou multiseleção de linhas?
Comment: Não fiz nenhum tratamento do tipo. Do jeito que o código está agora os campos atualizam sempre que eu altero a seleção de linha (estou usando o método fillCampos() no evento MouseClicked da JTable). Quando não há nada selecionado na tabela (no carregamento da tela por exemplo) os campos simplesmente ficam vazio
Comment: Marca, Genero e Fornecer possuem algum campo de identificacao unico, como id? O motivo de não selecionar é que o objeto do combo não é o mesmo da sua tabela, pelo menos ao java. Você precisa "ensinar" o java como saber quando eles são iguais.
Comment: Sim, todos possuem um id. Como fazer essa verificação?
Answer: O método setSelectedItem() compara o objeto passado como parâmetro com os já existentes no combo utilizando o método equals()(código fonte deste método pode ser visto no grepcode) que é herdado por todas as classes de Object.
Só que cada objeto criado não é igual a outro, mesmo que possuam os mesmos parâmetros e sejam do mesmo tipo, você pode fazer o teste imprimindo os objetos criados com os mesmos parâmetros dentro de um System.out.println(), o resultado será no formato ClasseDoObjeto@hascode e será diferente. Veja um teste no ideone.
Uma solução mais simples seria sobrescrever este método equals das classes Marca, Genero e Fornecedor, de modo a "ensinar" ao compilador em quais circunstâncias objetos destes tipos são iguais. Para ilustrar isso melhor, veja o método equals deste exemplo:
class MyClass {

    private int id;
    private String desc;

    public MyClass(int id, String desc) {
        this.id = id;
        this.desc = desc;
    }

    public int getId() {
        return this.id;
    }

    public String getDesc() {
        return this.desc;
    }

    @Override
    public boolean equals(Object obj) {
            return  obj instanceof MyClass && this.id == ((MyClass)obj).getId();
    }
}

Só retornará true se os dois objetos forem do mesmo tipo e tiverem o campo id iguais.
No entanto, recomendo a leitura desta resposta em seus parágrafos finais, que fala sobre como seria a forma correta de sobrescrever este método e quais consequências de não seguir as recomendações.

Referência:

Compare two objects with .equals() and == operator
Comment: Funcionou, obrigado! Além do seu código, percebi também que eu estava passando o número da coluna errado nos parâmetros, agora está funcionando perfeitamente.


Ansible - delete all partitions on a given list of disks

Question: I'm having serious trouble to do something that seems very trivial, I guess I'm probably going on the wrong way.
The scenario is quite simple, I have a host_group in which I have a list of disks like:
disks: "['sdb', 'sdc']"
Then on a task I have:
#Read device information (always use unit when probing)
- parted: device=/dev/{{ item }} unit=MiB   register: "{{ item }}_info"   with_items:
    -  "{{ disks }}"

This will read the information of the disks and store it in 2 variables: sdb_info and sdc_info
The problem starts when I try to delete all the partitions on the given disks, the normal task to do this is:
# Remove all partitions from disk
- parted:
    device: /dev/sdc
    number: "{{ item.num }}"
    state: absent   with_items:
    - "{{ sdc_info.partitions }}"

That works fine but I cannot adapt it to support the list of disks.
I'm doing something like:
# Remove all partitions from disk
- parted:
    device: /dev/{{ item[0] }}
    number: "{{ item[1].num }}"
    state: absent   with_nested:
    - "{{ disks }}"
    - "{{ {{ disks }}_info.partitions }}"

The issue seems to be "{{ {{ disks }}_info.partitions }}" because I cannot loop over a loop.
I'm probably choosing a very dum approach.... any help will be much appreciated.
Answer: Register to single variable info.
    - parted:
        device=/dev/{{ item }}
        unit=MiB
      register: info
      loop: "{{ disks }}"

Use subelements to iterate the disks and partitions. For example
    - hosts: localhost
      vars:
        disks:
          - sda
          - sdc
      tasks:
        - parted:
            device: "/dev/{{ item }}"
            unit: MiB
          register: info
          loop: "{{ disks }}"
        - debug:
            msg: "{{ item.0.disk.dev }} {{ item.1.num }}"
          loop: "{{ info.results|subelements('partitions') }}"

gives
    "msg": "/dev/sda 1"
    "msg": "/dev/sda 2"
    "msg": "/dev/sda 3"
    "msg": "/dev/sda 5"
    "msg": "/dev/sdc 1"

Answer: The following could be used to wipe out all of the existing partitions in a single task:
- command: wipefs -a {{ selected_device_id_path }}

Aside from it being a single command, the advantage here is that the partition removal process is not fragile to failures while calling parted info on devices that might have been (intentionally) altered in a way that parted did not expect.  One such case of this is if passing through a device (via virtio-blk) to a VM and setting its block size to its native value, which may not be the same as QEMU's default (512bytes).


Há algum design pattern que possa auxiliar nesse problema?

Question: Estou com um problema que me parece ser razoavelmente comum. O problema, no caso concreto, é o seguinte: o usuário quer registrar no sistema os serviços disponiveis para venda juntamente com os valores. Ao vender um serviço, o usuário quer que o serviço fique ativo para o cliente.
Finalmente, para alguns serviços há regras e propriedades específicas que o sistema precisa consultar. Um exemplo seria serviço de suporte, que tem as horas que o cliente paga por mês. Esse serviço tem uma regra específica: só pode ser realizado se as horas ainda não foram gastas no mês, e tem uma propriedade específica: o número de horas.
Agora vamos ver o problema: se o usuário cadastra os serviços manualmente, não tem como a principio o sistema saber por exemplo qual serviço é o de suporte. Na verdade, para o sistema vão ser todos iguais.  Isso porque em tese haverá uma única classe com propriedades gerais, cujas instâncias são os serviços cadastrados para venda.
Isso claramente conflita com precisar especificar regras e detalhes para tipos específicos de serviço.
Como eu disse, eu acho que isso pode ser mais comum do que parece a princípio. Eu citei um caso concreto, mas poderiamos abstrair da seguinte forma: o usuário quer cadastrar de forma personalizada alguns objetos, porém esses objetos precisam ter comportamentos específicos, com propriedades específicas e regras específicas, o que conflita com o usuário querer cadastrá-los a vontade.
Nesse sentido a solução que eu identifiquei foi a seguinte: identificar os tipos de serviço, criar uma classe para cada tipo, e no cadastro pedir para o usuário escolher o tipo, abrindo possibilidade da personalização. Aqui parece que caberia o uso de herança, mas eu sei que isso é sutil.
Fora isso pensei nos bounded contexts do DDD. Cheguei a pensar se o problema não seria o termo "Serviço" estar sendo usado em dois contextos diferentes, representando coisas diferentes. O problema é que apesar de identificar o problema, não identifiquei como lidar com a questão do "tipo do serviço".
Como isso me parece até comum, pensei se não haveria um design pattern que trata disso. Esse tipo de situação é assunto de algum design pattern? Existe uma solução conhecida e testada que dê conta desse tipo de problema?
Ou a solução que eu propus de criar uma classe para cada tipo de serviço, abstraindo suas caracteristicas principais, permitindo ao usuário escolher o tipo no cadastro seria a melhor solução?
Comment: Sem conhecer detalhes da implementação, eu acredito que seu último parágrafo é o melhor caminho.
Comment: @Renan, não dei detalhes de implementação, porque achei que a pergunta seria melhor recebida de uma forma mais genérica. Você acha que ela poderia ficar melhor dando detalhes? Além disso, com relação a implementação, só achei um problema: como eu deixaria o usuário escolher o tipo que será usado para criar o serviço, ao final? Uma enum com os tipos possíveis e então um mapeamento dos valores da enum para as classes?
Answer: Feature Flags
Esse é nome do pattern que procura. Você pode ler mais sobre isso nessa outra resposta do StackOverflow, ou no Wikipedia sobre Feature Toggle.
Uma Feature Flag (ou Feature Toggle) é a habilidade de ativar/desativar recursos (sub-seções) do seu aplicativo facilmente:

Através de um rebuild, ou
de área interna onde páginas/características/recursos possam ser alternadas com efeito imediato.

É conveniente ter o controle de cortar ou ativar um conjunto de recursos, no caso de precisar, por exemplo, reduzir o número de consultas no BD, se a carga estiver muito alta.
Há montes de outros motivos que você iria querer usar este recurso - um dos principais é permitir a implementação contínua: publicar novidades para produção tendo o novo recurso desabilitado até que ela esteja concluído. Muitas vezes usamos o que chamamos de um 'cookie dev' para mostrar características não concluídas para a equipe do colaborador. Desta forma podemos testar recursos parcialmente concluídos já em produção. E quando essas estiverem prontos, basta ativar o recurso para que ele se torne público à todos.
Este é um simples pacote que ajuda você a fazer isso com ASP.NET MVC: https://github.com/cottsak/DevCookie
Fowler também tem um artigo antigo com muito mais detalhes.
Comment: *Ativar ou desativar funcionalidades ou características específicas* não parece o mesmo conceito de *escolher uma dentre muitas formas de realizar um certo processo*.
Comment: Depende da sua implementação. Você pode facilmente fazer uma "feature" tipo "ProcessoQualquer:EnviaEmail" e por cliente vc ativa ou desativa. E no fim, essa feature será apenas um passo do seu fluxo/processo.
Answer: Modelagem do Código
Do ponto de vista do código, o problema soa exatamente como o Strategy Pattern.
Exemplo:
abstract class CalculoHoras {
  int calcularHoras(int mes) {
    List<Servico> servicosDoMes = carregarServicosDoMes(mes);
    int horasAPagar = calcularHorasAPagar(servicosDoMes);
    cobrarCliente(horasAPagar);
  }
  abstract int calcularHorasAPagar(List<Servico> servicosDoMes);
}

A partir daí, você pode criar quaisquer estratégicas para calcular as horas extendendo a classe. Então, de acordo com a configuração do sistema, você instancia uma das implementações na hora de realizar o cálculo.
Outra forma, sem usar herança, seria criar uma interface:
interface MetodoCalculoHorasAPagar {
  int calcularHorasAPagar(List<Servico> servicosDoMes);
}

Aí você cria as implementações que desejar e consome uma delas cada vez que for realizar o cálculo:
class CalculoHoras {
      int calcularHoras(int mes, MetodoCalculoHorasAPagar metodo) {
        List servicosDoMes = carregarServicosDoMes(mes);
        int horasAPagar = metodo.calcularHorasAPagar(servicosDoMes);
        cobrarCliente(horasAPagar);
      }
    }
Observações:

Usar delegação e interfaces é em geral uma prática melhor do que usar herança, ainda que em geral o padrão de projetos original use herança.
Os nomes e métodos usados acima são apenas ilustrativos, use conforme o seu caso.

Design geral
Padrões de projetos são interessantes, mas quase sempre não são uma solução por si sós, além de serem de muito baixo nível.
Pensar no design de uma solução para tornar uma funcionalidade flexível envolve pensar em variados aspectos, tais como:

Quem vai usar tal funcionalidade
Como ela será usada
Flexibilidade vs Complexidade
Segurança

E por aí vai. Só então o código passa a ser importante.
A primeira pergunta a ser feita neste contexto é: é possível identificar um conjunto finito, limitado de possíveis estratégicas de cálculo?
Se a resposta for afirmativa, então basta identificar e implementar tais estratégicas. Do ponto de vista dos usuários, se ele tentar realizar o cálculo sem selecionar uma estratégia, dê uma resposta visual dizendo que o resultado estará indisponível até que ele define a estratégia.
Se a reposta for negativa, então uma possível solução seria ter um conjunto de estratégicas comuns e permitir a extensão das regras. Este é um ponto complicado, pois existem várias formas de se fazer isto:

A mais básica e manual é oferecer um serviço onde o cliente manda uma especificação e você implementa conforme ele quer. Para poucos clientes é simples, mas para muitos é uma dor de cabeça. Não é uma boa solução caso as regras variem com frequência.
Talvez seja possível identificar as variáveis envolvidas na definição de novas regras e criar uma regra configurável via tela. Esta solução permite um pouco de flexibilidade, mas ainda assim envolve determinar tudo o que pode variar.
Se o problema puder ser resolvido com uma fórmula matemática ou financeira e algumas variáveis de entrada, seria possível permitir ao usuário entrar tal fórmula usando algum interpretador de expressões matemáticas.
Por fim, você pode permitir que os usuários contribuam com regras via código. Você pode se aproveitar do fato de que existem várias linguagens dinâmicas que rodam dentro da JVM de forma segura e permitir que o usuário escreva, por exemplo, uma função JavaScript num campo do sistema e você executa tal função no servidor. Esta solução é interessante de os seus clientes são da área de TI ou possuem setores de TI administrando os sistemas da empresa. Na verdade, você pode implementar esta solução para você mesmo, pois desta forma você poderia escrever a regra, colocar o script no banco do cliente por alguma tela administrativa ou script SQL e ter uma nova função no sistema sem ter que gerar uma nova versão.


How does Keras work with probabilities and Sigmoid function?

Question: I am trying to clasify a text by the main sentiment, positive or negative, with Keras. However, even though the code works, i don't completely understand two things.
1.How does the Dense layer with Sigmoid function work in order to clasify the text, considering that from what i understood, the "sigmoid" function returns a number between 0 and 1?
Does Keras by default consider 0 negative and 1 positive?
2.When using binary_crossentropy, what difference are we exactly calculating? I know that the differece is between the ground truth and our prediction. But which is which?
This is my code:
<code>train_validation_split = tfds.Split.TRAIN.subsplit([6, 4])
(train_data, validation_data), test_data = tfds.load(
    name="imdb_reviews",
    split=(train_validation_split, tfds.Split.TEST),
    as_supervised=True)

train_examples_batch, train_labels_batch = next(iter(train_data.batch(7)))
print(train_examples_batch)
print(train_labels_batch)
embedding = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(embedding, input_shape=[],
                           dtype=tf.string, trainable=True)
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(20, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
model.summary()
model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy'])
model.fit(train_data.shuffle(10000).batch(512),
                    epochs=25,
                    validation_data=validation_data.batch(512),
                    verbose=1)

results = model.evaluate(test_data.batch(512), verbose=2)

for name, value in zip(model.metrics_names, results):
  print("%s: %.3f" % (name, value))
</code>
Thank you so much!
Comment: I don't understand what you're asking in your second question. Binary cross entropy loss is $-\sum_i y_i \log(p_i) + (1 - y_i) \log(1 - p_i)$ where $y_i \in \{0, 1\}$ is a binary label and $p_i \in [0,1]$ is the model's estimate of the probability that a sample is labeled 1. Does this answer your question, or are you asking something else?
Comment: @SycoraxsaysReinstateMonica Pretty much. How do we know what the 1 label means, however? Do we always have 0 and 1 in binary classification? Also, my question was how does the neural network optimize based on the loss function and optimizer?
Comment: My answer addresses the questions you ask in your post. We have lots of threads describing [tag:backpropagation] and [tag:gradient-descent]  in general and [tag:adam] in particular. Please take a look at these threads first, and if you still have questions you can ask a new question explaining what you know, what you'd like to know, and where you're stuck.
Answer:
When the output of a network is a single sigmoid unit, you can consider the output the probability that the input is 1, i.e. $P(y = 1 | x)$ for a label $y$ and input $x$. Relating the notation $y=1$ to your particular positive/negative sentiment task depends on how you've chosen to encode positive and negative sentiments. Did you choose the encoding $\text{Positive} := 1$ and $\text{Negative} := 0$ or vice-versa? Or did you use a different encoding?
Binary cross entropy loss is $-\sum_i y_i \log(p_i) + (1 - y_i) \log(1 - p_i)$ where $y_i \in \{0, 1\}$ is a binary label and $p_i \in [0,1]$ is the model's estimate of the probability that a sample is labeled 1.


PostgreSQL task: trigger to calculate average

Question: I need help with the following problem.
Let two tables and relation between them:
CREATE TABLE A (
    id SERIAL PRIMARY KEY,
    val REAL
);

CREATE TABLE B (
    id SERIAL PRIMARY KEY,
    val REAL
);

CREATE TABLE A_B (
    a_id INT NOT NULL,
    b_id INT NOT NULL,
    FOREIGN KEY (a_id) REFERENCES A (id) ON DELETE CASCADE,
    FOREIGN KEY (b_id) REFERENCES B (id) ON DELETE CASCADE
);

I need to set B (val) so that it is always average of all A (val) if and only if relation between them exists in A_B. How to use trigger for it? Thanks and sorry for grammar.
Comment: If data in table b getting a bit stale is okay, I would suggest a materialized view.
Answer: I would suggest creating a view to expose this derived information. Actually storing it makes little sense, and maintaining integrity will be tedious.
create view view_b as
select b.id, avg(a.val) val
from b
left join a_b ab on ab.b_id = v.id
left join a on a.id = ab.a.id
group by b.id


How can I get rid of zig zag artifact on sphere surface in vispy?

Question: I'm working on the 3D visualization of planets in the solar system. As I am going to apply texture, I have manually computed the texture coordinates (texcoords), however, I get zig-zag artefacts appeearing in the image.
I believe that my computation might be wrong. I have attached the texcoords computation below:
# Compute Texture Coordinates
def get_texcoords(vertices):
    texcoords = []
    for v in vertices:
        #thresholding
        for i in range(3):
            if np.abs(v[i]) > 1e-6:
                v[i] = v[i]
            elif np.abs(v[i]) < 1e-6:
                v[i] = 0.0

        # Compute position in uv-space
        radius = np.sqrt(v[0]**2 + v[1]**2 + v[2]**2)

        latitude = np.arcsin(v[2]/radius)
        longitude = np.arctan2(v[1],v[0])

        # Convert to texture coordinates
        u = round(0.5 + longitude/(2*np.pi),5)
        v = round(0.5 + latitude/np.pi,5)

        texcoords.append([u,v])

    return np.array(texcoords)

Is there any way to remove the artefacts? Or is there a smarter way to obtain texture coordinates in vispy?
Answer: maybe using "for v in vertices:" in conjunction with using texture cordinate variable names to be "u" and "v" ?? I'm not sure it would produce that artifact, but it is definitely not recommended to modify your iterator inside its loop without being extremely cautious. Not recommended in any manner, actually. That's my initial take. I'm using this same algorithm so once I get mine working I'll know if it's the cause of your issue.
I just found this link which explains the error lurking in the uv mapping algorithm:   https://mft-dev.dk/uv-mapping-sphere/
In a nutshell, some of the mesh triangles cross the texture boundary, and some of those end up getting 'flipped' (i.e. their face normal points inward rather then outward). The article in the link shows how do find these rogue faces and fixes them.
I have been scratching my head over this one for a day or so.
Answer: Here is a code snippet that will generate a proper mesh without the zig-zag artefact:
Code sourced from from: https://www.songho.ca/opengl/index.html
colstep = 2 * pi / cols
    rowstep = pi / rows
    num_v = -1  # these counters are for logging/debuging
    num_f = -1
    num_e = -1
    num_eh = -1
    num_ev = -1

    for row in range(0, rows + 1):

        phi = pi / 2 - row * rowstep
        xy = radius[1] * cos(phi)
        z = radius[2] * sin(phi)

        for col in range(0, cols + 1):
            theta = col * colstep
            x = xy * cos(theta)
            y = xy * sin(theta)
            vert = np.array([x, y, z])
            # print(vert)
            self._verts.append(vert)
            self._norms.append(vert / np.sqrt(vert.dot(vert)))
            self._txcds.append(np.array([(col / cols), (row / rows)]))
            num_v += 1
    logging.info('----->>> Generated %r vertices...', num_v)

    for i in range(0, rows):

        k1 = i * (cols + 1)
        k2 = k1 + cols + 1

        for j in range(0, cols):

            if i != 0:
                self._faces.append(np.array([k1, k2, k1 + 1]))
                self._edges.append(np.array([k1, k2]))
                self._edges.append(np.array([k2, k1 + 1]))
                self._edges.append(np.array([k1 + 1, k1]))
                self._edge_colors.append((0, 0, 0, 1))
                self._edge_colors.append((0, 0, 0, 0))
                self._edge_colors.append((0, 0, 0, 1))
                num_f += 1
                num_e += 3
            if i != (rows - 1):
                self._faces.append(np.array([k1 + 1, k2, k2 + 1]))
                self._edges.append(np.array([k1 + 1, k2]))
                self._edges.append(np.array([k2, k2 + 1]))
                self._edges.append(np.array([k2 + 1, k1 + 1]))
                self._edge_colors.append((0, 0, 0, 0))
                self._edge_colors.append((0, 0, 0, 0))
                self._edge_colors.append((0, 0, 0, 0))
                num_f += 1
                num_e += 3

            k1 += 1
            k2 += 1

            self._v_edges.append(np.array([k1, k2]))
            num_ev += 1
            if i != 0:
                self._h_edges.append(np.array([k1, k1 + 1]))
                num_eh += 1


CUDA atomicAdd() with long long int

Question: Any time I try to use atomicAdd with anything other than (*int, int) I get this error:
error: no instance of overloaded function "atomicAdd" matches the argument list

But I need to use a larger data type than int. Is there any workaround here?
Device Query:
/usr/local/cuda/samples/1_Utilities/deviceQuery/deviceQuery Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

Detected 1 CUDA Capable device(s)

Device 0: "GeForce GTX 680"
  CUDA Driver Version / Runtime Version          5.0 / 5.0
  CUDA Capability Major/Minor version number:    3.0
  Total amount of global memory:                 4095 MBytes (4294246400 bytes)
  ( 8) Multiprocessors x (192) CUDA Cores/MP:    1536 CUDA Cores
  GPU Clock rate:                                1084 MHz (1.08 GHz)
  Memory Clock rate:                             3004 Mhz
  Memory Bus Width:                              256-bit
  L2 Cache Size:                                 524288 bytes
  Max Texture Dimension Size (x,y,z)             1D=(65536), 2D=(65536,65536), 3D=(4096,4096,4096)
  Max Layered Texture Size (dim) x layers        1D=(16384) x 2048, 2D=(16384,16384) x 2048
  Total amount of constant memory:               65536 bytes
  Total amount of shared memory per block:       49152 bytes
  Total number of registers available per block: 65536
  Warp size:                                     32
  Maximum number of threads per multiprocessor:  2048
  Maximum number of threads per block:           1024
  Maximum sizes of each dimension of a block:    1024 x 1024 x 64
  Maximum sizes of each dimension of a grid:     2147483647 x 65535 x 65535
  Maximum memory pitch:                          2147483647 bytes
  Texture alignment:                             512 bytes
  Concurrent copy and kernel execution:          Yes with 1 copy engine(s)
  Run time limit on kernels:                     Yes
  Integrated GPU sharing Host Memory:            No
  Support host page-locked memory mapping:       Yes
  Alignment requirement for Surfaces:            Yes
  Device has ECC support:                        Disabled
  Device supports Unified Addressing (UVA):      Yes
  Device PCI Bus ID / PCI location ID:           1 / 0
  Compute Mode:
     < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 5.0, CUDA Runtime Version = 5.0, NumDevs = 1, Device0 = GeForce GTX 680

Comment: Can you work with `unsigned long long int` or does it have to be `long long int`?  If you can use the unsigned version, it should work.  If you must use the signed 64 bit version, you can make a variant of the example given in [the documentation](http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#arithmetic-functions) for arbitrary atomic access using atomicCAS.  If you need help with that, respond accordingly and I can give you an example.
Answer: My guess is wrong compile flags. You're looking for anything other than int, you should be using sm_12 or higher.
As stated by Robert Crovella the unsigned long long int variable is supported, but the long long int is not.
Used the code from: Beginner CUDA - Simple var increment not working
#include <iostream>

using namespace std;

__global__ void inc(unsigned long long int *foo) {
  atomicAdd(foo, 1);
}

int main() {
  unsigned long long int count = 0, *cuda_count;
  cudaMalloc((void**)&cuda_count, sizeof(unsigned long long int));
  cudaMemcpy(cuda_count, &count, sizeof(unsigned long long int), cudaMemcpyHostToDevice);
  cout << "count: " << count << '\n';
  inc <<< 100, 25 >>> (cuda_count);
  cudaMemcpy(&count, cuda_count, sizeof(unsigned long long int), cudaMemcpyDeviceToHost);
  cudaFree(cuda_count);
  cout << "count: " << count << '\n';
  return 0;
}

Compiled from Linux: nvcc -gencode arch=compute_12,code=sm_12 -o add add.cu
Result:
count: 0
count: 2500

Comment: @Adam27X My guess is that on the NVidia architecture, the size of a `long` and the size of an `int` are the same, but the `long long int` is larger.
Comment: Why does `unsigned long long int` appear as an overload for `atomicAdd()` in the documentation but not `unsigned long int`?

CUDA atomicAdd() with long long int


Receiving two subscriptions emails when run cron using rules

Question: I need to send subscriptions immediately to users upon updating content. It is sending one subscriptions email when I run cron manually. But, when I run cron using rules, it send two subscriptions emails.
I have checked and found that I get one email only when I use rule to send test email.
Subscriptions setting: Users are not subscribed to content type...they are subscribed to taxonomy terms only.
Using modules for mail setup:
1. Mail system.
2. Mimemail.
3. Subscriptions.
4. Mail templates.
How can I send one subscriptions email only to each users upon updating content?
Answer: I finally solved this. I noticed that it was rules who was getting trigger two times. This  link  help me.  I thetrigger me to disable another rule on same event condition.


go bin - just 3 files

Question: I installed Go 1.6.2 on Windows but in my bin directory I now have only 3 files:
 go.exe
 godoc.exe
 gofmt.exe

I wonder if that's normal or my installation didn't go quite well.
Answer: That's normal. If you're looking for all the other executables (like linker, compiler etc.), check the:
%GOROOT%/pkg/tool/windows_amd64

(or similar) folders. These are not placed in the bin folder because you don't need to call these (they are called by the go.exe tool). bin contains only the tools you interact with, and is recommended to add %GOROOT%/bin to your PATH.
For example in my pkg/tool/windows_amd64 folder I have the following additional binaries:
addr2line.exe
api.exe
asm.exe
compile.exe
cover.exe
dist.exe
doc.exe
fix.exe
link.exe
nm.exe
objdump.exe
pack.exe
pprof.exe
tour.exe
trace.exe
vet.exe
yacc.exe

Comment: I see. Thanks. I was just worried that my installation did not go through quite fine.

go bin - just 3 files


Problema com alocação dinâmica - realloc()

Question: Estou fazendo um programa que funcione como um sistema de folha de pagamento, mas estou com problemas na parte da alocação dinâmica. O programa executa apenas uma vez e para. No int(main) eu coloquei:
    printf("Sizeof : %d\n",sizeof(funcionarios));
    printf("Executou: %d\n",i+1);
    printf("Tamanho: %d\n\n",tamanho);

Pra tentar identificar onde estava o erro. Na segunda execução o sizeof() retorna o mesmo valor o que me levou a crer que o realloc() não realocou a memória. Posso estar errado, estou aprendendo ainda. Peço ajuda a alguém mais esclarecido que eu.
Código completo abaixo:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <locale.h>

typedef struct{
    int matricula;
    float salario;
}Funcionario;

int ler_dados(void){
    int dado;
    printf("Digite a matrícula:\t");
    scanf(" %d",&dado);
    return dado;
}
float ler_salario(void){
      float salario;
      printf("Digite o valor do salário:\t");
      scanf(" %f",&salario);
      return salario;
}
int inserir_funcionario(Funcionario *funcionarios, int tamanho){
    int qntd = sizeof(funcionarios) * (tamanho + 1);
    funcionarios = realloc(funcionarios, qntd);
    funcionarios[tamanho].matricula = ler_dados();
    funcionarios[tamanho].salario = ler_salario();
    tamanho++;
    return tamanho;
}
int main(void){
    setlocale(LC_ALL,"Portuguese");
    int i;
    Funcionario *funcionarios = malloc(sizeof(funcionarios));
    int tamanho = 0;
    for(i=0; i<5; i++)
    {
        printf("Sizeof : %d\n",sizeof(funcionarios));
        printf("Executou: %d\n",i+1);
        printf("Tamanho: %d\n\n",tamanho);
        tamanho = inserir_funcionario(funcionarios, tamanho);
    }
}

Answer: O erro foi até meu na sua pergunta anterior. Eu foquei no problema principal e deixei passar outro erro. Mas lembro que ficar relocando desse jeito continua sendo inadequado como falei antes, e este novo problema é fruto disso. Complica muito. O gerenciamento de memória deveria ser tratado de uma forma isolada e preferencialmente no mesmo local onde a variável foi criada, fica muito mais fácil.
Este problema ocorreu porque está passando o ponteiro da memória a ser tratada, e isto permite que você altere os dados que estão neste local da memória. Mas não permite você alterar o ponteiro. Até pode mudar, mas ele só será visto dentro da função onde foi alterado. Quando dá o realloc() ele muda o ponteiro dentro de inserir_funcionario(), mas fora dela o ponteiro não foi modificado, e aí começa a confusão. Na próximo execução da função ela está recebendo o ponteiro original não relocado, e em algum momento causará problema de corrupção ou até, por sorte, quebrar a aplicação.
A solução é passar até o ponteiro por referência, então acaba tendo fazer um duplo ponteiro na passagem, e tem que derreferenciá-lo para usar.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

typedef struct {
    int matricula;
    float salario;
} Funcionario;

int ler_dados(void) {
    int dado;
    printf("Digite a matrícula:\t");
    scanf(" %d", &dado);
    return dado;
}
float ler_salario(void) {
      float salario;
      printf("Digite o valor do salário:\t");
      scanf(" %f", &salario);
      return salario;
}
int inserir_funcionario(Funcionario **funcionarios, int tamanho) {
    *funcionarios = realloc(*funcionarios, sizeof(Funcionario) * (tamanho + 1));
    (*funcionarios)[tamanho].matricula = ler_dados();
    (*funcionarios)[tamanho].salario = ler_salario();
    return ++tamanho;
}
int main(void) {
    setlocale(LC_ALL,"Portuguese");
    Funcionario *funcionarios = malloc(sizeof(Funcionario));
    int tamanho = 0;
    for (int i = 0; i < 5; i++) {
        printf("Sizeof : %lu\n", sizeof(Funcionario));
        printf("Executou: %d\n", i + 1);
        printf("Tamanho: %d\n\n", tamanho);
        tamanho = inserir_funcionario(&funcionarios, tamanho);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Para simplificar pode fazer assim:
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>

typedef struct {
    int matricula;
    float salario;
} Funcionario;

int ler_dados(void) {
    int dado;
    printf("Digite a matrícula:\t");
    scanf(" %d", &dado);
    return dado;
}
float ler_salario(void) {
      float salario;
      printf("Digite o valor do salário:\t");
      scanf(" %f", &salario);
      return salario;
}
int inserir_funcionario(Funcionario *funcionarios, int tamanho) {
    funcionarios[tamanho].matricula = ler_dados();
    funcionarios[tamanho].salario = ler_salario();
    return ++tamanho;
}
int main(void) {
    setlocale(LC_ALL,"Portuguese");
    Funcionario *funcionarios = malloc(sizeof(Funcionario));
    int tamanho = 0;
    for (int i = 0; i < 5; i++) {
        printf("Sizeof : %lu\n", sizeof(Funcionario));
        printf("Executou: %d\n", i + 1);
        printf("Tamanho: %d\n\n", tamanho);
        funcionarios = realloc(funcionarios, sizeof(Funcionario) * (tamanho + 1));
        tamanho = inserir_funcionario(funcionarios, tamanho);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


Information about In-functions Variables Besides locals() Dictionary

Question: This code, as expected, raises an UnboundLocalError.
x = 3

def f():
    print("locals: " + str(locals()))
    if x==3:
        print("x is 3!")
    x = 1

f()

However, as we can see from the output, locals() is an empty dictionary at the beginning:
locals: {}
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/try/scatch.py", line 10, in <module>
    f()
  File "C:/Users/user/PycharmProjects/try/scatch.py", line 6, in f
    if x==3:
UnboundLocalError: local variable 'x' referenced before assignment

From what I gathered, locals dictionary holds all of the information about the in-functions variables that Python knows. Clearly, this is not the case: there must be some information about the variables inside of the function besides locals().
My question is - what is this information exactly? Can we access at the beginning of the function to the list of the variables inside it?
Comment: `locals()` would give you give you local variables that have been bound (assigned to) at the point you access them. Variables considered local in given context as per scope rules are not the same thing. However, I do not recall their being an iface to access list of those from any point within a given block.
Comment: @JohnGordon - Python 'knows' that x variable will be redefined later. Since this info isn't included over locals(), there must be another place which holds it.
Comment: @OndrejK. - that's what I meant :) perhaps I wasn't clear enough
Comment: _Clearly, this is not the case_ Why do you say that?  At the point in the function where you call `locals()`, there are no local variables.  `x = 1` does not occur until later in the function...
Answer: The answer you're looking for in CPython is f.__code__.co_varnames documented in the inspect module.
>>> def f():
...     print(f.__code__.co_varnames)
...     x = 1
...     y = 2
>>> f()
('x', 'y')

Answer: While f.__code__.co_varnames (as pointed out in orlp's answer) works, here's way to find local assignments with AST:
import inspect,ast

x = 3

def find_ass_in_func(func):
    f_src = inspect.getsource(f)
    f_ast = ast.parse(f_src)
    return find_ass_in_src(f_ast.body)
def find_ass_in_src(bodies):
    ass = set()
    for b in bodies:
        if isinstance(b, ast.Assign):
            ass |= set(t.id for t in b.targets)
        if(hasattr(b, "body")):
            ass |= find_ass_in_src(b.body)
    return ass

def f():
    print("locals: " + str(locals()))
    print("local variables:", find_ass_in_func(f))
    if x==3:
        print("x is 3!")
        x = 5
        y = 6 # just for demonstration purpose
    x = 1

f()

Output:
locals: {}
local variables: {'x', 'y'}
Traceback (most recent call last):
  File "test.py", line 27, in <module>
    f()
  File "test.py", line 21, in f
    if x==3:
UnboundLocalError: local variable 'x' referenced before assignment


Google Places API not showing latest reviews

Question: I'm using google places api to get google reviews. I know that google limits it to 5 or 6 but I would have thought it would show the latest 5/6. But it isnt really showing the new reviews. The format I am requesting the json file is as follows:
<code>https://maps.googleapis.com/maps/api/place/details/json?key=API-KEY&placeid=ChIJqRTobkcMdkgRuCUbYZAvhKI
</code>
Is there some sort of sort order to add in the querystring?
Answer: There's this googlecode ticket with the same query but unfortunately, there doesn't seem to be any updates for it.


Visual Studio Team Services Rest API unauthorized_client error

Question: I am developing an JavaScript app to create work items in Visual Studio Team Services (was Visual Studio Online). But While authenticating I am getting the below error.

{"Error":"unauthorized_client","ErrorDescription":null}

I don't want to write any C# code so I am doing it all on html/javascript way.
I am getting the Auth_Code but access_token.
<code><form method="post" action="https://app.vssps.visualstudio.com/oauth2/token?   redirect_uri=http://mycallbackurl" id="accesstoken" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="client_assertion_type" value="urn:ietf:params:oauth:client-assertion-type:jwt-bearer" />
<input type="hidden" id="client_assertion" name="client_assertion" value="appSecret" />
<input type="hidden" name="grant_type" value="urn:ietf:params:oauth:grant-type:jwt-bearer" />
<input type="hidden" id="assertion" name="assertion" value="auth_code" />
</code>

I am submitting the above form and In that I am getting this error.
I have even tried to do the same using $.ajax but the same result.
Please help me in this.
Answer: You cannot send a authorize users via client side code as per the FAQ on the Auth page of the API documention.

Q: Can I use OAuth with my phone app?
A: No. Right now, Visual Studio Team Services only support the web
  server flow, so there's no supported way to implement OAuth for Visual
  Studio Team Services from an app like a phone app, since there's no
  way to securely store the app secret.

https://www.visualstudio.com/en-us/integrate/get-started/auth/oauth
You have to do the OAuth handshake via server side code.
Comment: @Aaron I am getting the same error when I do this from server side in node.js using request package
Comment: Can you provide the raw HTTP requests you are sending? Maybe you are not setting up the requests correctly.
Comment: Does this mean it's not possible to make updates (e.g. to Work Items) in Ajax calls too? I've got all of the OAuth stuff working in C# for obtaining an Access Token for the user and querying Work Items and so on, and I've got a nice UI working with Ajax updates to VSTS using a Personal Access Token of my own. I'd like to use the user's OAuth Access Token for the Ajax calls instead of my PAT. Is that possible (and if so how? - I've been trying to figure it out for hours!).
Comment: Philip, typically, OAuth APIs will allow you to fetch an access token on behalf of the user via server side code. You could fetch the token for the user, then send that to your frontend, from which you could make authorized Ajax requests on behalf of the user. However, the ideal scenario for security would be to proxy user authenticated requests via the server side and keep the  user token in a database for reuse.


Are all Monte Carlo algorithms to approximate $\pi$ equivalent?

Question: There are several ways one can approximate $\pi$ using a Monte-Carlo type algorithm. For example, one can draw random points in the unit square, and approximate $\pi$ via the ratio of points that fall in the unit disk. Another way would be to use an algorithm based on Buffon's needle problem: from the proportion of needles that fall across the parallel lines, one can approximate $\pi$. One can presumably devise many other random algorithms to estimate $\pi$.
My question is: in terms of speed of convergence, are all these algorithms equivalent? Or are there some that will yield correct decimals of $\pi$ faster? What is the Monte Carlo method to estimate $\pi$ that has the fastest convergence?
Comment: Different Monte Carlo procedures converge at different rates, so Yes there can be more and less efficient simulation algorithms to approximate $\pi.$
Comment: There is a very simple algorithm that can calculate an approximation of $\pi$ that is accurate to within 47 decimal places using only an average of 2 random coin flips.
Comment: @Michael Flip a coin until heads comes up and then look up and write down $\pi$ to $47$ places?
Comment: @BruceET - since you are the first to answer, I added a more difficult question for you ;-)
Comment: @Frank while it's unlikely this is the *best* monte carlo integration technique, a good starting point for research is the "Metropolis Hastings algorithm". From the cursory looking I've seen, many modern techniques are directly related to this.
Comment: @Mark - how do you use Metropolis Hastings to calculate $\pi$? (which is the scope here, not what is the best Monte Carlo method in general)
Comment: @spaceisdarkgreen  : Exactly!
Comment: @Frank let $f(x,y)$ be the indicator function of the circle, so $f(x,y) = 1$ if $x^2+y^2 \leq 1$. Then, you want to use monte carlo integration to approximate the integral $\int_{[-1,1]^2}f(x,y)dxdy$. To do this integration, you can use any monte carlo method such as Metropolis hastings.
Answer: Trying to keep this simple, answering your original very good question.(+1) Using Riemann approximation by rectangles
to get the area under the curve $y = \sqrt{1-x^2},$ for $0 < x < 1,$
and multiplying by 4, you can get pretty close to $\pi$ with only a dozen
rectangles. Closer if you use trapezoids. This is not a Monte Carlo
method, but the first method below is somewhat analogous (using random
points $x,$ instead of a deterministic grid of center points as bases of
rectangles).
set.seed(430)  # retain for exactly the same simulation
m = 10^6;  x = runif(m);  h = sqrt(1-x^2)
mean(h)*4
[1] 3.142033           # estimate of pi
2*4*sd(h)/sqrt(m)
[1] 0.001784625        # rough 95% margin of simulation error

So a million random $x$-values gives $3.1420 \pm 0.0018.$
An acceptance-rejection method similar to the one you suggested is
somewhat less efficient.
set.seed(430)
m = 10^6;  x = runif(m);  y=runif(m)
acc = y <+ sqrt(1-x^2)
mean(acc)*4
[1] 3.143212           # aprx pi
2*4*sd(acc)/sqrt(m)
[1] 0.003282115        # marg of sim err

Here we get $3.1433 \pm 0.0033,$ which indicates somewhat slower convergence.
Notes: (a) My purpose here is not to give best simulation methods for
approximating $\pi,$ but to answer your question by showing two commonly used methods with different rates of convergence. (b) I do not challenge the importance of the Metropolis-Histings algorithm in
simulation, but in my experience it is more useful in dimensions higher than
one or two. (c) I am not from the 'show-me' state of Missouri, but I have
a sister who lives there; if there is a way to get $\pi$ to 47 decimal
places by simulating a couple of coin flips, that's news to me and I'd
want to see an authoritative reference for that. (d) I have illustrated
other Monte Carlo methods on another page; some of them
can be adapted to your question.
Answer: All random algorithms that approximate $\pi$ by trying something that succeeds with probability $f(\pi)$ lots of times, getting an estimate of $f(\pi)$, and using that to estimate $\pi$ will be approximately equivalent. (Whether the thing we try is "drop a needle that interects a line" or "pick a point that lands inside a circle" or anything else.)
The reason is that their convergence rate will have nothing to do with the method at all. If the probability we're trying to estimate is $p$, then after $n$ trials the number of successes will follow a binomial distribution, and the typical number of successes will be $np \pm C \sqrt{np(1-p)}$. This gives an estimate of $p$ to within $O(\frac1{\sqrt n})$ error, which means millions of trials before we can estimate $p$ to three decimal places.
I only say "approximately" equivalent because the probability we're estimating can depend on $\pi$ in lots of ways. If the probability of success is $\frac12 + \frac{\pi}{1000}$, then it will take many trials before our estimate of this probability becomes significantly better than "it's about $\frac12$". On the other hand, if the probability of success is $10000\pi - 31415$, then estimating that the probability is approximately $0.9$ is enough to give use $\pi$ to five digits after the decimal: $\pi \approx 3.14159$.
Comment: One possibility, using [this integral](https://en.wikipedia.org/wiki/Proof_that_22/7_exceeds_%CF%80), is to sample a point from $[0,1] \times [0,\frac1{320}]$ and check if it's below the curve $\frac{x^4(1-x)^4}{1+x^2}$: the probability is $320(\frac{22}{7}-\pi)$. But philosophically, all that these methods are doing is offloading a few already-known digits of $\pi$ into the setup of the method itself, not accelerating the speed at which new digits are found.
Comment: So, according to your last paragraph, can we find a shape in the "pick a point that lands inside a circle" that would have a better relationship between $p$ and $\pi$ than the circle?
Comment: Nice - I hear you about the offloading going on here. Just out of curiosity, is there a systematic way to build a series of polynomials that take on more and more decimals of $\pi$ (or any number), or are these polynomials discovered through chance?
Comment: All I know is what you can find in the references in the Wikipedia article I linked to. So it seems there are some systematic approaches.


Solving ODE by substitution. Where does $dy$ goes

Question: When solving ODE by substitution, where does $dy$ goes from the following example?
$$\left(1+\frac{sin(y)}{cos(y)}\right)dy=x dx$$
Let $u=-cos(y)$. Hence $du = sin(y)$, which results in the following:
$$\left(1-\frac{1}{u}\right)du=xdx$$
But intuitively I want to write: $$\left(\left(1-(\frac{1}{u}du\right)\right)dy=xdx$$
So where did $dy$ go, could someone point out what logic eliminates $dy$ please?
Comment: Edits and improvements are welcome.
Comment: @Moo, Yes. Thank you for pointing that out
Answer: The substitution should be $du \equiv \sin{(y)}dy$.
We define $u = -\cos{(y)}$, and so $$\frac{du}{dy} = \sin{(y)}.$$ By abuse of notation, we can intuitively "multiply this fraction" by $dy$— which would intuitively make $du \equiv \sin{(y)}dy$.
The equation $\left(1 + \frac{\sin{y}}{\cos{y}}\right) dy = x \,dx $ becomes
$$\left(1 + \frac{du}{-u}\right) = x \,dx$$
or just
$$\left(1-\frac{1}{u}\right)du = x \,dx.$$
Comment: O-o-o-h-h... That's what I was missing! $$du = sin(y)du$$ $$\frac{du}{dy}=sin(y)$$ Thank you!


Change layout of views page based on taxonomy term field

Question: I have a taxonomy term page being displayed via a Views 'page' display. I need to change a value in the header of the site (above the level of the view) based on the value of one of the fields in the taxonomy term.
The problem is that I can't find the right hook for this. If I hook into hook_preprocess_views_view, it's too late. The wrapper that includes the site header has already fired. If I try to run hook_preprocess_page, there isn't yet any information in the $variables arg to give me the taxonomy ID so I can look up the field value. Unless there is are variables available to the hook in addition those that are passed into function as args, I don't see how I can get the requisite information. Are there other variables I could use that are undocumented or global variables available that just aren't passed to the function/hook?
Answer: What you can do is in the hook_preprocess_page use the following code :
$arg = arg();
if (count($arg) == 3 && $arg[0] == 'taxonomy' && $arg[1] == 'term' && is_numeric($arg[2])) {
  $term = taxonomy_term_load($arg[2]);
  if ($term->vid == $my_vocab_id) {
    # code...
  }
}

Then change the value of the header as you want in the # code... part.
Basically you check if the URL is a taxonomy term page and then  you can check that the term vid correspond to its proper vocabulary id.
Hope that will help you.
Comment: I see. That function is helpful. That's exactly what I needed.


Correção na apresentação da barra de status criada com o plugin Airline

Question: Instalei o plugin Airline com o objetivo de ter uma barra de status personalizada no meu editor, conforme visto na figura abaixo:

No entanto, a barra de status do meu editor está apresentando os símbolos <, >> e <. Como corrigir este problema?
Answer: A resolução do problema relatado consiste em baixar as fontes do projeto Powerline e instalá-las no sistema, pois as fontes deste projeto fornecem símbolos customizados. Vamos aos passos:

Donwload das fontes

Primeiramente, faça o download das fontes. Estas podem ser obtidas a partir do link do projeto, no github ou a partir do comando:
git clone https://github.com/powerline/fonts.git

Instalação
Após a obtenção do pacote de fontes, você deve executar o arquivo .install para que ele faça a instalação destas. Será criado o diretório ~/.fonts, caso este não exista. Este diretório é usado no linux para a instalação de fontes.
Configuração do terminal
Altere o tipo de fonte usado em seu terminal de comandos. No caso de utilização do gnome-terminal, você vai em Editar > Preferências do perfil e edite o tipo de fonte para uma das fontes Powerline. No meu caso, escolhi a fonte Meslo LG S Regular for Powerline.
Resultado
O resultado é uma barra de status mais elegante, mais útil, que permite a identificação mais rápida dos modos de edição usados no momento da edição do texto, dando possibilidade ao aumento de produtividade.

Referências
https://vi.stackexchange.com/questions/3359/how-to-fix-status-bar-symbols-in-airline-plugin


What unblocked ports are necessary for github to work?

Question: My work has blocked github. Attempting to pull from a github repo produces this message:
ssh: connect to host github.com port 22: Operation timed out

Does this mean only port 22 needs to be unblocked? Or should more be unblocked? They have told me that if I provide the instructions, they will unblock github.
Comment: That error message alone is sufficient for competent IT staff to figure out what needs to be unblocked. They should not be making the developers do their jobs.
Answer: You just need to unblock port 22.
Since you are in an network check that you have the right proxy settings. (and git uses them)
Also see that you can resolve github.com (ping github.com)


Show that $n^n>(n+1)!$ for all $n\ge3$

Question: Show that $n^n>(n+1)!$ for all $n\ge3$
For $n=3$ it is to prove.
assumed it true for some fixed $n\in \mathbb{N}$.
Then tried to prove for $n+1$
$(n+1)^{n+1}=(n+1)^n(n+1)>n^n(n+1)>(n+1)!(n+1)$
Got stuck.
Comment: $2^{2n}>{2n \choose n}=(2n)!/(n!)^2$, $2^{2n}(n^{n})^2>2^{2n}(n!)^2> (2n)!$, $(2n)^{2n}>(2n)!$. Similarly for $2n+1$.
Answer: $$\frac{n^n}{n!}=\frac n1\cdot\frac n2\cdot\frac n3\cdots\frac nn>\frac n1\cdot\frac n2>n+1.$$
Comment: Yves Beautiful.
Comment: Induction is unnecessary. The second inequality holds because $(n-1)^2/2>3/2$.
Comment: @PeterSzilas ;-)
Answer: HINT
For the induction step assuming that $n^n>(n+1)!$ is true we have
$$(n+2)!=(n+2)(n+1)!\stackrel{Ind. Hyp.}<(n+2)n^n\stackrel{?}<(n+1)^{n+1}$$
thus we need to prove that
$$(n+2)n^n<(n+1)^{n+1} \iff 1 + \frac1{n+1}<\left(1+\frac1n\right)^n$$
Answer: Hint: Note that$$\frac{(n+1)^{n+1}}{n^n}=(n+1)\left(1+\frac1n\right)^n$$and that$$\frac{(n+2)!}{(n+1)!}=n+2.$$It is not hard to prove that$$(\forall n\in\mathbb{N}):\left(1+\frac1n\right)^n>\frac{n+2}{n+1}.$$
Answer: With Bernoulli's inequality
$$\left(1+\dfrac{1}{n}\right)^n\geq1+n\dfrac{1}{n}=2>1+\dfrac{1}{n+1}$$
then
$$(n+1)^{n+1}>(n+2)n^n>(n+2)!$$
Answer: I'll start with the inductive hypothesis:
$n^n>(n+1)!$
Then the inductive step:
$(n+1)^{n+1}>(n+2)!$
I will prove this for
$(n+1)^{n+1}>n^n(n+2)$ because $n^n(n+2) > (n+2)!$ given the inductive hypothesis. And therefore, if $(n+1)^{n+1}$ is  bigger than $n^n(n+2)$, it must also be bigger than $ (n+2)!$.
$(n+1)^{n+1}>n^n(n+2)$
$(n+1)^{n+1}>n^{n+1}+2n^n$
By binomial expansion, the first 2 terms of $(n+1)^{n+1}$ will be:
$n^{n+1}$ and $n+1$ choose 1 multiplied to $n^n$
So we need to prove $n^{n+1}+(n+1)Choose1.......>n^{n+1}+2n^n$
We can simplify $(n+1)Choose1$ given the combinations formula: $$\frac{n!}{k!(n-k)!}$$ We know k=1 and n=n+1. This simplifies to n+1. And n+1 must be at least 4, since $n>=3$
Therefore even the first 2 terms of: $n^{n+1}+(n+1)n.....>n^{n+1}+2n^n$
This proves the statement.

Show that $n^n>(n+1)!$ for all $n\ge3$


Question of the minimal sufficient statistics of beta-distribution

Question:
The beta distribution with parameters $\alpha>0$ and $\beta>0$ has
density$$f(x|\alpha,\beta)=\frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)}x^{\alpha-1}(1-x)^{\beta-1},0<x<1$$
Suppose $X_1,...,X_n$ are independently and identically distributed
from a beta distribution.

Determine a minimal sufficient statistic (for the family of joint    distributions) if $\alpha$ and $\beta$ very freely
Determine a minimal sufficient statistic if $\alpha=2\beta$
Determine a minimal sufficient statistic if $\alpha=\beta^2$

The above is the setup of our homework question for the statistical inference course. For (a),
$$\prod f(y_i|\alpha,\beta)=\frac{1}{B^n(\alpha,\beta)}\exp\{(\alpha-1)\sum\log y_i+(\beta-1)\sum\log(1-y_i)\}$$
$$\frac{\prod f(x_i|\alpha,\beta)}{\prod f(y_i|\alpha,\beta)}=\exp\{(\alpha-1)\sum(\log x_i-\log y_i)+(\beta-1)\sum(\log(1-x_i)-\log(1-y_i))\}$$
If $\sum\log x_i=\sum\log y_i, \sum \log(1-x_i)=\sum\log(1-y_i)$, the ratio is constant, therefore by Lehmann-Scheffe theorem, $$\{T_1=\sum\log x_i,T_2=\sum\log(1-x_i)\}$$ is a minimal sufficient statistic for $(\alpha,\beta)$.
The above is how I approached this question. I first used the factorization criterion to find the sufficient statistics and prove it is also minimal sufficient. However, coming to the second part, I tried to approach the question the same way:
$$f(x|\beta)=\frac{\Gamma(3\beta)}{\Gamma(2\beta)\Gamma(\beta)}x^{2\beta-1}(1-x)^{\beta-1}$$
$$=\frac{\Gamma(3\beta)}{\Gamma(2\beta)\Gamma(\beta)}\frac{1}{x(1-x)}\exp\{2\beta\log x+\beta\log (1-x)\}$$
$$=\frac{\Gamma(3\beta)}{\Gamma(2\beta)\Gamma(\beta)}\frac{1}{x(1-x)}\exp\{\beta(2\log x+\log(1-x))\}$$
$$=\frac{\Gamma(3\beta)}{\Gamma(2\beta)\Gamma(\beta)}\frac{1}{x(1-x)}\exp\{\beta\log x^2(1-x)\}$$
$$T(X)=\sum\log x_i^2(1-x_i)=2T_1+T_2$$
However, what I have done so far, in my view, is merely showing that the statistic is sufficient but how to show it is also the minimal sufficient statistic I do not know. I tried to find the answer online and found This material from Purdue's website. The question looks exactly the same, and the procedure for the first two questions seem not so different from what I have done. I am perplexed about how come the answer directly jump to that the statistic is also minimal sufficient? Did I miss any theorem? Also does $T(X)=\sum\log x_i^2(1-x_i)=2T_1+T_2$ actually carry with some implications?
Also, when approaching this question I have a more general and vague question that I want to ask. It appears that other than making a exponential family in an exponential form, Fisher-Neyman Factorization Theorem is enough to establish the sufficient statistics, an it is usually in the product form: here is just an example for your reference . It always appear that the product can be transformed to summation through exponential and logarithm somehow. But when I studied the concepts in statistics I always struggled to make distinctions between the distribution of a statistic and the joint distribution of a set of random variables. I guess it is because most of the time I am dealing with normal distribution; therefore the summation of x and x-square just naturally appear in the joint distribution and I always thought when we take the product we obtain something connects with mean and variance. But these concepts turn out very confusing when I am dealing with other distributions.
For example, the beta distribution. So far from what I have learnt online, both $\prod x_i$,$\prod (1-x_i)$ and $\sum\log x_n , \sum \log (1-x_n)$ seem both valid. However, when considering them as statistics I feel very hard to understand what we are trying to estimate from these statistics. Also it appear to me they are estimating totally different thing, how come they are both efficient? If they are both efficient there must be a one-to-one correspondence if I am not mistaken. How should I link the concept of sufficient statistics with through estimates I obtained from LME and other estimation techniques?
I hope my question make sense. Thank you so much for your time and patience!
Comment: $\sum\log x_n$ is a bijective function of $\prod x_i$ and so on.  Remember that a statistic is not the same as an estimator: instead, an estimator will usually be calculated from statistics
Comment: For showing minimal sufficiency, did you try using the method you used in the first one?
Comment: @StubbornAtom I tried but I don't know how to put that $\frac{1}{1(1-x)}$outside of the exponential form...
Comment: @Henry I think I can understand what you mean.. that's mainly motivated me to ask the last part of the question ... As I feel I may misunderstand the purpose of having sufficient statistic. I automatically connect this concept with the concept of an estimator
Comment: @StubbornAtom also for the link I provided on Purdue's website, I don't quite get in the last question, he merely showed T1 and T2 are minimal sufficient... then he suddenly jumped to conclude T is a minimal sufficient statistic. I don't quite get what he's doing there unless I missed some important concepts in minimal sufficient statistic
Comment: In the third problem, you can check by factorization that $ T=(\sum \ln X_i,\sum \ln (1-X_i))$ is sufficient for $\beta$. For minimal sufficiency you have to follow the usual method, i.e. show that $f_\beta(\boldsymbol x)/f_\beta(\boldsymbol y)$ is independent of $\beta$ iff $T(\boldsymbol x)=T(\boldsymbol y)$ for $\boldsymbol x\ne \boldsymbol y$. It is not the case that the components $T_1,T_2$ of $T$ are individually sufficient/minimal sufficient.
Comment: In the solution for the second problem, they are using [this](https://books.google.com/books?id=1HQmBKMgDaMC&lpg=PR1&pg=PA110#v=onepage&q&f=false) (proposition 2.1) property of exponential family from which it follows that $\sum\log X_i^2(1-X_i)$ is a complete sufficient statistic for $\beta$. In this setup, a complete sufficient statistic (if it exists) is usually also minimal sufficient. Similar argument works for the first problem but not for the third problem.
Comment: @StubbornAtom Sorry for my late reply. We just covered the complete concept today I think I got your reply for that part. For (c) do you mean we are considering $T=\{T_1,T_2\}$ as a whole instead of individually?
Answer: $a)$ We have that $T(\mathbf{X})=\left(\sum_{i=1}^n\log(X_i),\sum_{i=1}^n\log(1-X_i)\right)$ is sufficient for the family $\{B(\alpha,\beta),\alpha>0,\beta>0\}$ since for all $\mathbf{x}\in\mathbb R^n$, $\alpha>0$, and $\beta>0$,
$$\begin{align*}
f(\mathbf{x}\mid\alpha,\beta)
&=\left[\frac{\Gamma\left(\alpha+\beta\right)}{\Gamma\left(\alpha\right)\left(\beta\right)}\right]^n\left(\prod_{i=1}^n x_i\right)^{\alpha-1}\left(\prod_{i=1}^n (1-x_i)\right)^{\beta-1}\prod_{i=1}^n\mathbb{1}_{[0,1]}(x_i)\\\\
&=\underbrace{\exp\left[\left(\alpha-1\right)\sum_{i=1}^n\log(x_i)+(\beta-1)\sum_{i=1}^n\log(1-x_i)+n\log\left(\frac{\Gamma\left(\alpha+\beta\right)}{\Gamma\left(\alpha\right)\left(\beta\right)}\right)\right]}_{g(T(\mathbf{x})\mid\alpha,\beta)}\underbrace{\mathbb{1}_{[0,1]}(x_{(1)})\mathbb{1}_{[0,1]}(x_{(n)})}_{h(\mathbf{x})}
\end{align*}$$
We also have that $T(\mathbf{X})=\left(\sum_{i=1}^n\log(X_i),\sum_{i=1}^n\log(1-X_i)\right)$ is a minimal sufficient statistic since for any two possible sample points $\mathbf{x}$ and $\mathbf{y}$
$$\begin{align*}
\frac{f\left(\mathbf{x}\mid\alpha,\beta\right)}{f\left(\mathbf{y}\mid\alpha,\beta\right)}
&=\frac{\exp\left[\left(\alpha-1\right)\sum_{i=1}^n\log(x_i)+(\beta-1)\sum_{i=1}^n\log(1-x_i)+n\log\left(\frac{\Gamma\left(\alpha+\beta\right)}{\Gamma\left(\alpha\right)\left(\beta\right)}\right)\right]}{\exp\left[\left(\alpha-1\right)\sum_{i=1}^n\log(y_i)+(\beta-1)\sum_{i=1}^n\log(1-y_i)+n\log\left(\frac{\Gamma\left(\alpha+\beta\right)}{\Gamma\left(\alpha\right)\left(\beta\right)}\right)\right]}\\\\
&=\exp\left[\left(\alpha-1\right)\left[\sum_{i=1}^n\log(x_i)-\sum_{i=1}^n\log(y_i)\right]+(\beta-1)\left[\sum_{i=1}^n\log(1-x_i)-\sum_{i=1}^n\log(1-y_i)\right]\right]
\end{align*}$$
does not depend on $\alpha$ or $\beta$ if and only if $T(\mathbf{x})=\left(\sum_{i=1}^n\log(x_i),\sum_{i=1}^n\log(1-x_i)\right)$ equals $T(\mathbf{y})=\left(\sum_{i=1}^n\log(y_i),\sum_{i=1}^n\log(1-y_i)\right)$
$b)$ We have that $T(\mathbf{X})=\sum_{i=1}^n\log\left(X_i^2(1-X_i)\right)$ is sufficient for the family $\{B(\alpha,\beta),\alpha=2\beta,\beta>0\}$ since for all $\mathbf{x}\in\mathbb R^n$ and $\beta>0$,
$$\begin{align*}
f(\mathbf{x}\mid\alpha=2\beta,\beta)
&=\left[\frac{\Gamma\left(2\beta+\beta\right)}{\Gamma\left(2\beta\right)\left(\beta\right)}\right]^n\left(\prod_{i=1}^n x_i\right)^{2\beta-1}\left(\prod_{i=1}^n (1-x_i)\right)^{\beta-1}\prod_{i=1}^n\mathbb{1}_{[0,1]}(x_i)\\\\
&=\exp\left[\left(2\beta-1\right)\sum_{i=1}^n\log(x_i)+(\beta-1)\sum_{i=1}^n\log(1-x_i)+n\log\left(\frac{\Gamma\left(3\beta\right)}{\Gamma\left(2\beta\right)\left(\beta\right)}\right)\right]\mathbb{1}_{[0,1]}(x_{(1)})\mathbb{1}_{[0,1]}(x_{(n)})\\\\
&=\exp\left[(\beta-1)\sum_{i=1}^n\log\left(x_i^2(1-x_i)\right)+\sum_{i=1}^n\log(x_i)+n\log\left(\frac{\Gamma\left(3\beta\right)}{\Gamma\left(2\beta\right)\left(\beta\right)}\right)\right]\mathbb{1}_{[0,1]}(x_{(1)})\mathbb{1}_{[0,1]}(x_{(n)})\\\\
&=\underbrace{\exp\left[(\beta-1)\sum_{i=1}^n\log\left(x_i^2(1-x_i)\right)+n\log\left(\frac{\Gamma\left(3\beta\right)}{\Gamma\left(2\beta\right)\left(\beta\right)}\right)\right]}_{g(T(\mathbf{x})\mid\alpha=2\beta,\beta)}\underbrace{\exp\left(\sum_{i=1}^n\log(x_i)\right)\mathbb{1}_{[0,1]}(x_{(1)})\mathbb{1}_{[0,1]}(x_{(n)})}_{h(\mathbf{x})}\\\\
\end{align*}$$
We also have that $T(\mathbf{X})=\sum_{i=1}^n\log\left(X_i^2(1-X_i)\right)$ is a minimal sufficient statistic since for any two possible sample points $\mathbf{x}$ and $\mathbf{y}$
$$\begin{align*}
\frac{f\left(\mathbf{x}\mid\alpha=2\beta,\beta\right)}{f\left(\mathbf{y}\mid\alpha=2\beta,\beta\right)}
&=\frac{\exp\left[\left(\beta-1\right)\sum_{i=1}^n\log\left(x_i^2(1-x_i)\right)+n\log\left(\frac{\Gamma\left(3\beta\right)}{\Gamma\left(2\beta\right)\left(\beta\right)}\right)\right]\exp\left(\sum_{i=1}^n\log(x_i)\right)}{\exp\left[\left(\beta-1\right)\sum_{i=1}^n\log\left(y_i^2(1-y_i)\right)+n\log\left(\frac{\Gamma\left(3\beta\right)}{\Gamma\left(2\beta\right)\left(\beta\right)}\right)\right]\exp\left(\sum_{i=1}^n\log(y_i)\right)}\\\\
&=\exp\left[\left(\beta-1\right)\left[\sum_{i=1}^n\log\left(x_i^2(1-x_i)\right)-\sum_{i=1}^n\log\left(y_i^2(1-y_i)\right)\right]+\left[\sum_{i=1}^n\log(x_i)-\sum_{i=1}^n\log(y_i)\right]\right]
\end{align*}$$
does not depend on $\beta$ if and only if $T(\mathbf{x})=\sum_{i=1}^n\log\left(x_i^2(1-x_i)\right)$ equals $T(\mathbf{y})=\sum_{i=1}^n\log\left(y_i^2(1-y_i)\right)$
$c)$ We have that $T(\mathbf{X})=\left(\sum_{i=1}^n\log(X_i),\sum_{i=1}^n\log(1-X_i)\right)$ is sufficient for the family $\{B(\alpha,\beta),\alpha=\beta^2,\beta>0\}$ since for all $\mathbf{x}\in\mathbb R^n$ and $\beta>0$,
$$\begin{align*}
f(\mathbf{x}\mid\alpha=\beta^2,\beta)
&=\left[\frac{\Gamma\left(\beta^2+\beta\right)}{\Gamma\left(\beta^2\right)\left(\beta\right)}\right]^n\left(\prod_{i=1}^n x_i\right)^{\beta^2-1}\left(\prod_{i=1}^n (1-x_i)\right)^{\beta-1}\prod_{i=1}^n\mathbb{1}_{[0,1]}(x_i)\\\\
&=\underbrace{\exp\left[\left(\beta^2-1\right)\sum_{i=1}^n\log(x_i)+(\beta-1)\sum_{i=1}^n\log(1-x_i)+n\log\left(\frac{\Gamma\left(\beta^2+\beta\right)}{\Gamma\left(\beta^2\right)\left(\beta\right)}\right)\right]}_{g(T(\mathbf{x})\mid\alpha=\beta^2,\beta)}\underbrace{\mathbb{1}_{[0,1]}(x_{(1)})\mathbb{1}_{[0,1]}(x_{(n)})}_{h(\mathbf{x})}
\end{align*}$$
We also have that $T(\mathbf{X})=\left(\sum_{i=1}^n\log(X_i),\sum_{i=1}^n\log(1-X_i)\right)$ is a minimal sufficient statistic since for any two possible sample points $\mathbf{x}$ and $\mathbf{y}$
$$\begin{align*}
\frac{f\left(\mathbf{x}\mid\alpha=\beta^2,\beta\right)}{f\left(\mathbf{y}\mid\alpha=\beta^2,\beta\right)}
&=\frac{\exp\left[\left(\beta^2-1\right)\sum_{i=1}^n\log(x_i)+(\beta-1)\sum_{i=1}^n\log(1-x_i)+n\log\left(\frac{\Gamma\left(\beta^2+\beta\right)}{\Gamma\left(\beta^2\right)\left(\beta\right)}\right)\right]}{\exp\left[\left(\beta^2-1\right)\sum_{i=1}^n\log(y_i)+(\beta-1)\sum_{i=1}^n\log(1-y_i)+n\log\left(\frac{\Gamma\left(\beta^2+\beta\right)}{\Gamma\left(\beta^2\right)\left(\beta\right)}\right)\right]}\\\\
&=\exp\left[\left(\beta^2-1\right)\left[\sum_{i=1}^n\log(x_i)-\sum_{i=1}^n\log(y_i)\right]+(\beta-1)\left[\sum_{i=1}^n\log(1-x_i)-\sum_{i=1}^n\log(1-y_i)\right]\right]
\end{align*}$$
does not depend on $\beta$ if and only if $T(\mathbf{x})=\left(\sum_{i=1}^n\log(x_i),\sum_{i=1}^n\log(1-x_i)\right)$ equals $T(\mathbf{y})=\left(\sum_{i=1}^n\log(y_i),\sum_{i=1}^n\log(1-y_i)\right)$


WSOD and Drush cc all fail after deleting a view of a long-time-ago deleted module

Question: Background
Drupal 7.40 site, all is up2date, the site itself worked, until the last hour, just fine.
The problem
I once had a module named Flexslider and have deleted it 5 months ago. One of it's views and/or content types stayed alive and I've deleted it in the last hour; Since then there is a WSOD in my site and each time I try to flush all caches with Drush I get the following error about the impossibility to access a Flexslider file.
Any ideas why would that happen?

Image update for user - Les Lim:
Answer: Since I happen to know from WSOD afte uninstalling the Memcache module and deleting it's folder that you just stopped using Memcache, then I know that your Drupal site has just reverted back to using the database cache.
You probably had entries in your database cache from before you switched to Memcache in the first place.  Those really old database cache entries are now back in use.
You're trying to clear caches, which is absolutely the correct thing to do. However, there's a nasty bug in CTools that prevents you from clearing the cache if a particular CTools cache entry is broken: https://www.drupal.org/node/1775612
In this case, though, the manual fix is pretty simple. You need to truncate the cache table in your database. That should allow the cache to rebuild itself normally.
Comment: TRUNCATE in SQL means delete all the rows from a table. I think you should be able to use Drush for this, even if the site is unresponsive. Try the following command: drush sqlq "TRUNCATE TABLE cache;"
Comment: If you have PHPMyAdmin, I think it's called "Empty Table" in that interface. I'm not sure.
Comment: You can list the names of all tables that have the string "cache" in its name, just to check. That command is this: drush sqlq "SHOW TABLES LIKE '%cache%'"
Comment: You found the right table. Go ahead and empty that one.
Comment: Thanks for your answer so much! I'm not sure what "truncate" means - I saw 3 different definitions in the dictionary, lol... Anyway, It sounds to me like partially deleting something from the *cache* table in my database? I guess anything that has to do with Flexslider? If yes, I guess I would be able to do so via PHPmyadmin > search > type there "flexslider" > set it to search at cache table > delete ?
Comment: In Drush, I get the output: ERROR 1146 (42S02) at line 1: Table 'zantech0_Benia.cache' doesn't exist
Query failed.
Comment: Well that's not good. Did you install the site with a table prefix? The table won't be called "cache" exactly, then.
Comment: I believe there is a table prefix for all my tables and that this prefix is "4bn_". I've no idea why it's there, maybe it's because the first time I installed the site was with softaculous, maybe it's because someone of the server support once changed it \ or it was added by a machine in some occasion --- In anyway I've updated the question with a screenshot with the table that I think I should empty (after a backup of course).
Comment: Worked! Thank you very very much for all the didactic and detailed help!, It enlightened me with both knowledge and confidence to do such actions in the future (I'm but a humble Javascript student). So, Thank you again! ^__^


Calendário que mostre a diferença entre duas datas

Question: Quero fazer um calculador de diferença entre datas. Um que dê para fazer uma diferença em dias, horas, etc.
Exemplo: Inicial - 17/07/2019 para Final - 29/07/2020. Quanto tempo (em dias) é da data inicial para a data final? E quantas horas?
Estou com o seguinte código:

    //CALCULAR DIAS

        function CalcDias(){
                var data1 = new Date(document.getElementById("data1").value);
                var data2 = new Date(document.getElementById("data2").value);
                return parseInt((data1 - data2) / (24 * 3600 * 1000));
        }

    //CALCULAR HORAS

        function CalcHoras(){
                var data1 = new Date(document.getElementById("data1").value);
                var data2 = new Date(document.getElementById("data2").value);
                return parseInt((data1 - data2) / (24 * 3600 * 1000));
        }

    //CALCULAR SEGUNDOS

       function CalcSegundos(){
                var data1 = new Date(document.getElementById("data1").value);
               var data2 = new Date(document.getElementById("data2").value);
                return parseInt((data1 - data2) / (24 * 3600 * 1000));
        }

    //MOSTRAR RESULTADOS

        function result(){
        if(document.getElementById("data1")){
            document.getElementById("result_dias").value=CalcDias();
            document.getElementById("result_horas").value=CalcHoras();
            document.getElementById("result_segundos").value=CalcSegundos();

        }
    }

Primeira data:<input type="date" class="textbox" id="data2" name="data_2" onchange="result()"/>

Segunda data:<input type="date" class="textbox" id="data1" name="data_1" onchange="result()"/>

Diferença em Dias:<input type="text" class="textbox" id="result_dias" name="dias"/>

Eu só coloquei os valores "horas e segundos" para demonstrar como eu quero, porém apenas a quantidade de dias funciona.
Teria um jeito de realizar um código parecido com esse de dias para um de HORAS/SEGUNDOS/MESES/ANOS?
Comment: Oi @Danna. Vi que voce é uma usuária nova aqui, recomendo que veja os seguintes links antes: [Tour StackOverflow](https://pt.stackoverflow.com/tour) e [Help StackOverflow](https://pt.stackoverflow.com/help), pois nesses links, explicam como é o ambiente aqui e também como fazer perguntas no Stack Overflow. Porque aqui nao criamos código e entregamos para as pessoas que pedem e sim ajudamos com dúvidas em códigos das pessoas que fazem as perguntas.
Comment: Óh sim, me perdoe. Não soube explicar muito bem! Eu até tenho um código montado, seria um problema se eu editasse a pergunta e mostrasse o meu código? assim eu poderia pedir auxilio de um jeito mais fácil.
Comment: Veja o conceito de dia juliano e aí basta fazer a diferença. É como a maioria dos softwares faz.
Answer: Como você está usando campos input type="date", quer dizer que eles só possuem o dia, mês e ano, sem nenhuma informação sobre o horário. Então não vejo como calcular a diferença em horas, a menos que você assuma que uma diferença de X dias é o equivalente a X * 24 horas (e nesse caso, considera-se que estamos comparando o mesmo horário dos dois dias).
De qualquer forma, o valor de um input type="date" é sempre retornado como uma string no formato "yyyy-mm-dd" (também conhecido como formato ISO 8601). E quando você cria um Date passando uma string neste formato, ela é interpretada como sendo aquela data, à meia-noite, em UTC. Ou seja, as datas criadas estão no mesmo horário.
E quando você subtrai duas instâncias de Date, o resultado é a diferença entre elas, em milissegundos. Como nesse caso as duas datas possuem o mesmo horário (e ainda é referente ao UTC, que não possui anomalias como o horário de verão, que poderiam interferir nos resultados), é seguro assumir que este valor da diferença é múltiplo de 24 horas.
Por isso, para calcular a diferença em segundos, basta dividir este valor por 1000. Para obter a diferença em minutos, divida por (1000 * 60), e assim por diante:

// diferença em milissegundos
function diffMs(data1, data2) {
    return data2 - data1;
}

// diferença em segundos
function diffSecs(data1, data2) {
    return diffMs(data1, data2) / 1000;
}

// diferença em minutos
function diffMins(data1, data2) {
    return diffSecs(data1, data2) / 60;
}

// diferença em horas
function diffHoras(data1, data2) {
    return diffMins(data1, data2) / 60;
}

// diferença em dias
function diffDias(data1, data2) {
    return diffHoras(data1, data2) / 24;
}

function calcula(sel) {
    let data1 = document.getElementById('data1').value;
    let data2 = document.getElementById('data2').value;
    if (data1 && data2) { // se os 2 campos estão preenchidos
        let op = sel.options[sel.selectedIndex];
        let d1 = new Date(data1);
        let d2 = new Date(data2);
        let diff;
        switch (op.value) {
            case 'ms':
                diff = diffMs(d1, d2);
                break;
            case 's':
                diff = diffSecs(d1, d2);
                break;
            case 'm':
                diff = diffMins(d1, d2);
                break;
            case 'h':
                diff = diffHoras(d1, d2);
                break;
            case 'd':
                diff = diffDias(d1, d2);
                break;
        }
        if (diff !== undefined) {
            document.getElementById('resultado').innerHTML = `${diff} ${op.text}`;
        }
    }
}
<form>

Primeira data:<input type="date" class="textbox" id="data1" name="data1" />

Segunda data:<input type="date" class="textbox" id="data2" name="data2" />

Escolha o cálculo:
    <select onchange="calcula(this)">
      <option value="">escolha</option>
      <option value="ms">milissegundos</option>
      <option value="s">segundos</option>
      <option value="m">minutos</option>
      <option value="h">horas</option>
      <option value="d">dias</option>
    </select>

Diferença:

</form>

Diferença em meses e anos
Esse cálculo já é um pouco mais complicado, como já explicado aqui. Muitos podem sugerir apenas para pegar a diferença em dias e dividir por 30 (ou por 365.25 / 12, ou por qualquer outro valor médio arbitrário), e em seguida arredondar o resultado. Mas esses valores só te darão aproximações, e estão sujeitos a muitos erros.
Usando os exemplos do link acima citado, entre 01/01/2019 e 01/02/2019 há 31 dias. Dividindo por 30 e arredondando, dá 1 mês.
Mas entre 01/02/2019 e 01/03/2019 há 28 dias. Dividindo por 30, dá 0,93: se arredondar pra baixo, dá zero meses. Mas entre 1 de fevereiro e 1 de março a diferença não é de um mês? Então devemos arredondar pra cima nesse caso?
Mas e se fosse entre 01/01/2019 e 29/01/2019, a diferença também é de 28 dias. Só que entre 1 de janeiro e 29 de janeiro ainda não se passou 1 mês, então eu não posso arredondar pra cima nesse caso. "Ah, então eu só arredondo pra cima se não estiver no mesmo mês".
Aí você vê que entre 01/01/2019 e 27/02/2019 a diferença é de 57 dias, que dividido por 30 dá 1,9. Se arredondar pra cima dá 2, mas entre 1 de janeiro e 27 de fevereiro ainda não se passaram dois meses. E agora?
Dividir por 30 (ou por qualquer outro valor "médio" arbitrário) sempre terá esse problema. Isso acontece porque meses têm tamanhos variados (podem ter 28, 29, 30 ou 31 dias) e a quantidade exata de meses equivalente aos dias vai depender das datas envolvidas. O mesmo vale para anos, pois eles podem ter 365 ou 366 dias, e a quantidade exata de anos também depende das datas envolvidas.
Sendo assim, uma alternativa seria usar o mesmo algoritmo sugerido da resposta supracitada:
function ajustaMesAno(date) {
    return date.getUTCFullYear() * 12 + date.getUTCMonth();
}

function diffMeses(data1, data2) {
    return ajustaMesAno(data2) - ajustaMesAno(data1);
}

O código acima desconsidera o dia do mês (ou seja, a diferença entre qualquer data em janeiro e qualquer data em fevereiro é 1 mês). Mas você também pode considerar que, se a data inicial é 10/01/2019, então até o dia 09/02/2019 ainda não completou 1 mês (somente a partir de 10/02 é que podemos considerar que já se passou 1 mês). Nesse caso, o código ficaria:
function diffMeses(data1, data2) {
    let meses = ajustaMesAno(data2) - ajustaMesAno(data1);
    if (data1.getUTCDate() > data2.getUTCDate()) {
        meses--;
    }
    return meses;
}

Qual dos dois é o correto? Depende de como você quer calcular essa diferença. Não existe uma regra "oficial" para fazer esses cálculos, como existe na matemática. O que existem são implementações diferentes, e algumas são mais "aceitas", mas tudo depende de cada caso. Aritmética de datas não é nada óbvia, e há vários casos bem estranhos e contra-intuitivos.
E quanto aos anos? Podemos pegar a diferença em meses e dividir por 12:
function diffAnos(data1, data2){
    return diffMeses(data1, data2) / 12;
}

Se vamos levar em conta o dia do mês ou não, isso é definido pela implementação que escolhemos para diffMeses. Se quiser, ainda pode arredondar o resultado como bem entender. Fica o seu critério.
E há ainda o caso de 29 de fevereiro.
Se alguém nasceu em 29/02/2000, em 28/02/2001 podemos considerar que a pessoa já fez 1 ano? Afinal, ainda falta um dia para o aniversário - só que o dia seguinte é 1 de março, então como faz? Novamente, não há uma regra oficial para isso: algumas APIs consideram que o resultado é zero anos, outras consideram que é 1. Cabe a você escolher como vai tratar esses casos.
Enfim, aritmética de datas não é tão simples assim, quando você começa a pensar nos detalhes. Não é à toa que há tantas APIs diferentes para trabalhar com datas, cada uma adotando abordagens diferentes, e muitas estão longe de serem consideradas bem sucedidas. De qualquer forma, a ideia "básica" foi dada...

Moment.js
Se quiser, pode usar o Moment.js, que possui o método diff, muito melhor para trabalhar com datas:

function calcula(sel) {
    let data1 = document.getElementById('data1').value;
    let data2 = document.getElementById('data2').value;
    if (data1 && data2) { // se os 2 campos estão preenchidos
        let op = sel.options[sel.selectedIndex];
        let d1 = moment(data1);
        let d2 = moment(data2);
        let diff;
        switch (op.value) {
            case 'ms': // milissegundos, usar o método normal
                diff = d2 - d1;
                break;
            default: // para todos os outros casos, usar o moment
                if (op.value) {
                    diff = d2.diff(d1, op.value);
                }
        }
        if (diff !== undefined) {
            document.getElementById('resultado').innerHTML = `${diff} ${op.text}`;
        }
    }
}

<form>

Primeira data:<input type="date" class="textbox" id="data1" name="data1" />

Segunda data:<input type="date" class="textbox" id="data2" name="data2" />

Escolha o cálculo:
    <select onchange="calcula(this)">
      <option value="">escolha</option>
      <option value="ms">milissegundos</option>
      <option value="seconds">segundos</option>
      <option value="minutes">minutos</option>
      <option value="hours">horas</option>
      <option value="days">dias</option>
      <option value="months">meses</option>
      <option value="years">anos</option>
    </select>

Diferença:

</form>
Comment: Muito obrigada pela ajuda! Me ajudou a compreender mais sobre o conteúdo em si e agora pude conseguir concluir uma parte do meu projeto. Muito obrigada mesmo! De coração.
Comment: @Danna Fiz uma correção na função `diffMeses`, tinha invertido a ordem das datas...
Answer: Pega o resultado da subtração das duas, em milissegundos, e divide pelo valor que tu quer.
exemplo:
var horas = Math.abs(data1 - data2) / (60*60*1000);

obs: Obviamente, dependendo de como tu configurou os campos de entrada, isso poderá te retornar um número decimal. Tu terás que decidir se quer pegar somente a parte inteira ou arredondar.