Clientes não se comunicam no mesmo jogo multiplayer em Java

Question: Estou tentando fazer um jogo multiplayer simples de tanque implementando chat.
O jogo e o chat estão tudo ok! Porém, eu não consigo fazer com que 2 clientes visualizem o mesmo objeto Arena.
No caso, cada cliente que ingressar cria um tanque na arena. Porém, sempre que tento executar, ele cria uma arena diferente para cada jogador.
public class Arena extends JComponent implements MouseListener, ActionListener, KeyListener {
    private Tanque apontado;
    private int largura, altura;
    private HashSet<Tanque> tanques;
    private Tiro tiro;
    private Timer contador;
    private long agora;

    public Arena(int largura, int altura) {
        this.largura = largura;
        this.altura = altura;
        tanques = new HashSet<Tanque>();
        tiro = new Tiro(-40, -10, 0, null, -1);
        addMouseListener(this);
        addKeyListener(this);
        setFocusable(true);
        contador = new Timer(40, this);
        contador.start();
        agora = 1;
    }

    public void adicionaTanque(Tanque t) {
        tanques.add(t);
    }

    public Dimension getMaximumSize() {
        return getPreferredSize();
    }

    public Dimension getMinimumSize() {
        return getPreferredSize();
    }

    public Dimension getPreferredSize() {
        return new Dimension(largura, altura);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(new Color(245, 245, 255));
        g2d.fillRect(0, 0, largura, altura);
        g2d.setColor(new Color(220, 220, 220));
        for (int _largura = 0; _largura <= largura; _largura += 20)
            g2d.drawLine(_largura, 0, _largura, altura);
        for (int _altura = 0; _altura <= altura; _altura += 20)
            g2d.drawLine(0, _altura, largura, _altura);
        // Desenhamos todos os tanques
        for (Tanque t : tanques) {
            t.draw(g2d);
        }
        tiro.draw(g2d);

    }

    public void mouseClicked(MouseEvent e) {
        for (Tanque t : tanques)
            t.setEstaAtivo(false);
        for (Tanque t : tanques) {
            boolean clicado = t.getRectEnvolvente().contains(e.getX(), e.getY());
            if (clicado) {
                t.setEstaAtivo(true);
                apontado = t;
            }
        }
        repaint();
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void actionPerformed(ActionEvent e) {
        for (Tanque t : tanques) {
            t.mover();
            t.calculaTempo();
        }
        colisao();
        tiro.mover();
        repaint();
    }

    public void colisao() {
        if (tiro.estaAtivo) {
            for (Tanque t : tanques) {
                if (t.getId() != tiro.getId()) {
                    double dist = Math.sqrt(Math.pow(tiro.x - t.x, 2) + Math.pow(tiro.y - t.y, 2));
                    if (dist <= 20) {/* Distancia de acerto */
                        tiro.x = -10;
                        tiro.y = -10;
                        tanques.remove(t);
                        tiro.estaAtivo = false;
                        break;
                    }
                    /* Tanque detecta o míssil e tenta se esquivar */
                    if (dist < 100) {
                        t.setTempo(System.currentTimeMillis());

                        if (agora % 2 == 0)
                            t.girarAntiHorario(7);
                        else
                            t.girarHorario(7);

                        t.velocidade = 6;
                    }
                }

            }
        }
        for (Tanque t : tanques) {
            autoColisao(t);
        }

    }

    public void autoColisao(Tanque tanque) {
        for (Tanque t : tanques) {/* verifica a distancia para checar colisão entre os tanques */
            if (tanque.getId() != t.getId()) {
                double dist = Math.sqrt(Math.pow(tanque.x - t.x, 2) + Math.pow(tanque.y - t.y, 2));
                if (dist <= 30) { /* Colisão entre tanques */
                    if (t.velocidade > 0) {
                        t.velocidade *= -1;
                        t.girarAntiHorario(7);
                    } else {
                        t.velocidade = 2;
                        t.girarHorario(7);
                    }
                }

                if (dist < 80 && tanque.estaAtivo) {/* tanque inimigo tenta fugir */
                    t.setTempo(System.currentTimeMillis());
                    if (agora % 2 == 0)
                        t.girarAntiHorario(5);
                    else
                        t.girarHorario(5);

                    t.velocidade = 6;
                }

            }
        }
    }

    public void keyPressed(KeyEvent e) {
        for (Tanque t : tanques) {
            t.setEstaAtivo(false);
            if (t == apontado) {
                t.setEstaAtivo(true);
                switch (e.getKeyCode()) {
                case KeyEvent.VK_LEFT:
                    t.girarAntiHorario(3);
                    break;
                case KeyEvent.VK_UP:
                    t.aumentarVelocidade();
                    break;
                case KeyEvent.VK_DOWN:
                    t.diminuirVelocidade();
                    break;
                case KeyEvent.VK_RIGHT:
                    t.girarHorario(3);
                    break;
                case KeyEvent.VK_SPACE: {
                    atirar(t.getId());
                    agora = System.currentTimeMillis();
                }
                    break;
                }
                break;
            }
            repaint();
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    public void atirar(int id) {
        for (Tanque t : tanques) {
            if (t.estaAtivo) {
                if (!tiro.estaAtivo) {
                    tiro.x = t.x;
                    tiro.y = t.y;
                    tiro.angulo = t.angulo;
                    tiro.cor = Color.RED;
                    tiro.setId(t.getId());
                    tiro.estaAtivo = true;
                }
            }
        }
    }
}

Código Servidor:
public class Servidor extends Thread {

/* Aqui vou criar um Array list para armazenar o BufferedWiter de cada
 * jogador que se conecta no site.
 * O restante das variaveis tem nomes sugestivos
 */
private static ArrayList<BufferedWriter> clientes;
private static ServerSocket servidor;
private String nickname; /*essa variavel vai servir para armeznar o nome do jogador cliente que o servidor recebe*/
private Socket conexao;
private InputStream entrada;
private InputStreamReader leitura_entrada;
private BufferedReader buffer;

Arena arena = new Arena(640, 480);
JFrame janela = new JFrame("JTank");

public Servidor(Socket conexao) {

    this.conexao= conexao;
    try {

        entrada  = conexao.getInputStream();
         leitura_entrada = new InputStreamReader(entrada);
         buffer = new BufferedReader(leitura_entrada);
  } catch (IOException e) {
         e.printStackTrace();
  }
}

public void run(){

 janela.getContentPane().add(arena);
    janela.setResizable(false);
    janela.pack();
    janela.setVisible(true);
    arena.adicionaTanque(new Tanque(500, 50, 180, Color.BLUE, 1));

  try{
    String mensagem;
    OutputStream ou =  this.conexao.getOutputStream();
    Writer ouw = new OutputStreamWriter(ou);
    BufferedWriter bfw = new BufferedWriter(ouw);
    clientes.add(bfw);
    nickname = mensagem = buffer.readLine();

    while(!"Sair".equalsIgnoreCase(mensagem) && mensagem != null)
      {

       mensagem = buffer.readLine();
       sendToAll(bfw, mensagem);
       System.out.println(mensagem);

       }

   }catch (Exception e) {
     e.printStackTrace();

   }
}

public void sendToAll(BufferedWriter bwSaida, String msg) throws  IOException
{
BufferedWriter bwS;

for(BufferedWriter bw : clientes){
bwS = (BufferedWriter)bw;
if(!(bwSaida == bwS)){

 bw.write(nickname + " -> " + msg+"\r\n");
 bw.flush();
}
}
}

public void chama_arena() {

}

public static void main(String []args) {

try{

JLabel lblMessage = new JLabel("Porta do Servidor:");
JTextField txtPorta = new JTextField("12345");
Object[] texts = {lblMessage, txtPorta };
JOptionPane.showMessageDialog(null, texts);
servidor = new ServerSocket(Integer.parseInt(txtPorta.getText()));
clientes = new ArrayList<BufferedWriter>();
JOptionPane.showMessageDialog(null,"Servidor ativo na porta: "+
txtPorta.getText());

 while(true){
 System.out.println("Aguardando conexão...");
 Socket conexao = servidor.accept();
 System.out.println("Cliente conectado...");
 Thread t = new Servidor(conexao);
  t.start();
   }

}catch (Exception e) {

e.printStackTrace();
}

}

}

Código cliente:
public class Cliente extends JFrame implements ActionListener, KeyListener {

    private static final long serialVersionUID = 1L;
    private JTextArea texto;
    private JTextField txtMsg;
    private JButton btnEnviar;
    private JButton btnSair;
    private JLabel lblHistorico;
    private JLabel lblMsg;
    private JPanel pnlContent;
    private Socket socket;
    private OutputStream ou;
    private Writer ouw;
    private BufferedWriter bfw;
    private JTextField txtIP;
    private JTextField txtPorta;
    private JTextField txtNome;

    public Cliente() throws IOException {
        JLabel lblMessage = new JLabel("Verificar!");
        txtIP = new JTextField("127.0.0.1");
        txtPorta = new JTextField("12345");
        txtNome = new JTextField("Cliente");
        Object[] texts = { lblMessage, txtIP, txtPorta, txtNome };
        JOptionPane.showMessageDialog(null, texts);
        pnlContent = new JPanel();
        texto = new JTextArea(10, 20);
        texto.setEditable(false);
        texto.setBackground(new Color(240, 240, 240));
        txtMsg = new JTextField(20);
        lblHistorico = new JLabel("Histórico");
        lblMsg = new JLabel("Mensagem");
        btnEnviar = new JButton("Enviar");
        btnEnviar.setToolTipText("Enviar Mensagem");
        btnSair = new JButton("Sair");
        btnSair.setToolTipText("Sair do Chat");
        btnEnviar.addActionListener(this);
        btnSair.addActionListener(this);
        btnEnviar.addKeyListener(this);
        txtMsg.addKeyListener(this);
        JScrollPane scroll = new JScrollPane(texto);
        texto.setLineWrap(true);
        pnlContent.add(lblHistorico);
        pnlContent.add(scroll);
        pnlContent.add(lblMsg);
        pnlContent.add(txtMsg);
        pnlContent.add(btnSair);
        pnlContent.add(btnEnviar);
        pnlContent.setBackground(Color.LIGHT_GRAY);
        texto.setBorder(BorderFactory.createEtchedBorder(Color.BLUE, Color.BLUE));
        txtMsg.setBorder(BorderFactory.createEtchedBorder(Color.BLUE, Color.BLUE));
        setTitle(txtNome.getText());
        setContentPane(pnlContent);
        setLocationRelativeTo(null);
        setResizable(false);
        setSize(250, 300);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    /* Vou criar aqui um método chamado conectar.. Se conecta ao servidor */

    public void conectar() throws IOException {

        socket = new Socket(txtIP.getText(), Integer.parseInt(txtPorta.getText()));
        ou = socket.getOutputStream();
        ouw = new OutputStreamWriter(ou);
        bfw = new BufferedWriter(ouw);
        bfw.write(txtNome.getText() + "\r\n");
        bfw.flush();

    }

    /*
     *  metodo Enviar mensagem é responsável pela troca de mensagens dentro do servidor
     */
    public void enviarMensagem(String msg) throws IOException {

        if (msg.equals("Sair")) {
            bfw.write("Desconectado \r\n");
            texto.append("Desconectado \r\n");
        } else {
            bfw.write(msg + "\r\n");
            texto.append(txtNome.getText() + " diz -> " + txtMsg.getText() + "\r\n");
        }
        bfw.flush();
        txtMsg.setText("");

    }

    /*
     * Método para ler as mensagens recebidas pelo servidor
     */
    public void escutar() throws IOException {

        InputStream in = socket.getInputStream();
        InputStreamReader inr = new InputStreamReader(in);
        BufferedReader bfr = new BufferedReader(inr);
        String msg = "";

        while (!"Sair".equalsIgnoreCase(msg))

            if (bfr.ready()) {
                msg = bfr.readLine();
                if (msg.equals("Sair"))
                    texto.append("Servidor caiu! \r\n");
                else
                    texto.append(msg + "\r\n");
            }
    }

    /*
     * Método usado quando o usuário clica em sair
     */
    public void sair() throws IOException {

        enviarMensagem("Sair");
        bfw.close();
        ouw.close();
        ou.close();
        socket.close();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        try {

            if (e.getActionCommand().equals(btnEnviar.getActionCommand()))
                enviarMensagem(txtMsg.getText());
            else if (e.getActionCommand().equals(btnSair.getActionCommand()))
                sair();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {

        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            try {
                enviarMensagem(txtMsg.getText());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub
    }

    public static void main(String[] args) throws IOException {

        Cliente app = new Cliente();

        app.conectar();
        app.escutar();
    }

}

Comment: Por favor, acesse o link que segue para aprender a fornecer um **[mcve]** para que possamos executar o código e simular o problema.
Comment: Caroline, porque você acha que há duas arenas? Mais especificamente, em que ponto do debug você parou e inspecionou e viu que havia duas instâncias de Arena?
Comment: Quando cada cliente se conecta, ele deve crisr um tanque dentro da Arena. Mas, ele exibe uma Arena com apenas um tanque. Não mostra o tanque do adversário
Comment: Oi Caroline. Isso eu entendi, mas é preciso que você diga como você sabe isso, o que aparece no debug, etc.
Comment: P.s.: Quando responder a um comentário coloque para quem é com @CarolineTeixeira, por exemplo. Você recebe todas as notificações de comentários, mas os outros não. Por isso só vi seu novo comentário hoje.
Answer: O problema é que seu objeto Arena não é static, assim ele é um atributo da classe Servidor. Isso significa que cada vez que um objeto Servidor for criado um novo objeto Arena também será criado.
E isso acontece porque no código de tratamento de recebimento de conexões, em cada accept você cria um novo objeto Servidor, provavelmente porque no seu projeto você fez o Servidor herdar de Thread e imaginou que deveria criar uma nova instância para cada novo cliente (o que é parcialmente verdade).
Dito isso, se você tornar a Arena static vai resolver (parcialmente) o seu problema, mas o ideal seria revisar o projeto de forma que você separasse o tratamento dos clientes conectados do objeto que controla a arena por exemplo. No lado do servidor poderia repensar as tarefas que são executadas para ser mais modularizado.
Seria bom, como eu disse, separar pelo menos o tratamento de rede do tratamento de Arena.


FasterXML Jackson?

Question: I'm switching to jackson json because it's apparently faster than minimal-json. I am however confused to how it works as the documentation is confusing.
Is it:
import com.fasterxml.jackson...
or:
import org.codehaus.jackson...
I have tried both, I have the file jackson-core-2.5.0.jar and the import com.fasterxml.jackson works, however I am not able to do the following:
ObjectMapper mapper = new ObjectMapper();

Comment: It's not about not understanding or wasting time, etc. Stack Overflow is not _for you_. It's for everyone. If you put all the relevant information and not leave room for interpretation, you'll get better answers, your question will be indexed better and therefore it will be easier for people to find it. You can choose not to, fine, but I suggest you do.
Comment: You need `com.fasterxml.jackson-core:jackson-databind:2.5.0`
Comment: What does _I am not able to do the following_ mean?
Comment: @SotiriosDelimanolis You know what it means, stop playing dumb ;) The object ObjectMapper is not recognized.
Comment: Always include such information, with its exact error message.
Comment: @SotiriosDelimanolis Feel sorry for you if you require(or don't understand) such information for such an obvious error setting. Wasting time in software development isn't what I'm here to do.
Comment: Assuming things and not being specific is bad practice across wide array of disciplines. It has very little to do with software but rather problem solving in general. Imagine going into a car forum and saying "I was driving my car and it stopped working please fix it.. Oh its Ford.. Come on You know what the problem is"... That was basically your question.
Comment: @AdamGent Are you seriously comparing cars to programming? I mentioned a line of code that did not work which is common to write in Jackson, I also pointed out possibilities of what could be wrong (the package). In car terms it should be, "I was driving my car and it stopped working. A light stating the engine has overheated is blinking, I don't know if the radiator is broken of I need to refill it with more coolant." *That* was basically my question. Also Sotirios also answered fully including additional information, so apparantly it was clear enough for him.
Comment: @KarlMorrison You had to state in a comment "*The object ObjectMapper is not recognized*" for SotiriosDelimanolis and myself to figure out your problem. And then afterwards you insult someone trying to help you. Any number of things could have happen besides compile errors for "*I am not able to do the following: ObjectMapper mapper = new ObjectMapper();*". Its like saying I'm not able to start the car. ObjectMapper could have thrown an exception. You could have the incorrect dependencies (ie an old JDK). Even saying it makes a red squiggle line in Eclipse would have been more helpful.
Comment: @AdamGent I am sorry if you feel like I've insulted him, that's your thoughts. Had to and had to is your personal opinion. Again it is more like "I am not able to start the car because either the radiator is broken or I need to fill it with more coolant", where would you look, yes of course, at the radiator as I so happened to point out (in the case of the question, the packages) in which where the problem did reside. I am running Android Studio with my own personalized specific color scheme with the latest JDK.
Answer: Jackson 1 was part of org.codehaus. Jackson 2 is now part of com.fasterxml and is in no way backwards compatible.
The ObjectMapper type is in the package com.fasterxml.jackson.databind.
Comment: Ahh, perfect thanks mate. The documentation is pretty confusing now that they have changed, you cleared it all up now!

FasterXML Jackson?


how to run a sql function in pl sql developer

Question: I am new to oracle. I created one function in oracle database using pl sql developer, and I executed successfully. Now I want to run that function from same pl sql developer by query. but it is not working properly.
Below is my function.
create or replace function com.my_first_test_function(module_code out varchar2,
bpm_process_name out varchar2,module_name out varchar2,input in number)return number is
y_return number(1)
N_return varchar(200)
begin
if input='yes' then
Y_return :=select module_code ,bpm_process_name,module_name from com_tm_bpm_process_details;

if input='no' then nested_procedure_exception exception

but when I try to run this function using below query it is throwing some error message. can any one tell me how to call the function from pl sql developer.
select * from  com.my_first_test_function(java.sql.Types.VARCHAR,java.sql.Types.VARCHAR,java.sql.Types.VARCHAR,'yes')

here I tried without out parameter values also but still no use.
Comment: `executed successfully`: I doubt that this function compiled. You are missing semicolons, `select` cannot be called like that and your `if`-statements are incomplete.
Answer: To call a function in a SQL statement is intended to compute some return value, reading informations from parameters; so, functions with OUT parameters make not sense in SQL.
If you need something that could handle OUT parameters, you can use procedures, within a PL/SQL block, passing variables as OUT parameters.
About calling a FUNCTION, you can use a PL/SQL block, with variables:
SQL> create or replace function f( n IN number) return number is
  2  begin
  3      return n * 2;
  4  end;
  5  /

Function created.

SQL> declare
  2      outNumber number;
  3  begin
  4      select f(10)
  5      into outNumber
  6      from dual;
  7      --
  8      dbms_output.put_line('outNumber: "' || outNumber || '"');
  9  end;
 10  /
outNumber: "20"

PL/SQL procedure successfully completed.

or even call it directly in a SQL query:
SQL> select f(10) from dual;

     F(10)
----------
        20

Comment: There's no reason why a function can't have one or more OUTPUT parameters, but doing so will make that function impossible to call from SQL.
Comment: You're absolutely right; I was thinking to SQL, but I wrote  something else; I'll fix the answer, thanks
Comment: thanks for your reply. finally i found the answer that how to call a sql function from pl sql developer.  select * from table(name of the function(in and out parameters)). this will work.


Inequality properties between their multiplications

Question: If $A>B>C>D$ then will $$(A/B * A/C * A/D) > (B/A * B/C * B/D) > (C/A * C/B * C/D) > (D/A * D/B * D/C)$$ be always true? If not, in what intervals will it not be true?
Obviously $A,B,C,D \geq 0$  and they take values in the interval of ${\Bbb R}_+$, that is positive real numbers only.
Answer: First of all, we're dividing by $A,B,C,D$ so none can be $0$. Hence, in this answer, we assume $A,B,C,D>0$.

Anyway, since $A>B>C>D>0$, we know that
$$A^4>B^4>C^4>D^4$$
and now since $ABCD>0$, we may divide by $ABCD$ without flipping any signs:
$$\frac{A^3}{BCD}>\frac{B^3}{ACD}>\frac{C^3}{ABD}>\frac{D^3}{ABC}$$
which is the exact same as the thing you were trying to prove.
Answer: Yes---compare term by term e.g. $A/B > B/A$, $A/C > B/C$, $A/D > B/D$ which will give you the first result, and so on.


How do I get the user ID for the currently logged-in user?

Question: I want to get current user object (user information) in Drupal 8.
I know in Drupal 7 there was a global $user variable; I want to know how I can get current user object in Drupal 8.
Answer: $user = \Drupal::currentUser();

See the Drupal class. There are a lot of helper methods; most of them are shortcuts for services, so you don't have to call \Drupal::service() directly.
Note that the current user is not the user entity, it is just user proxy. You can get some basic information from it but fields or other entity-specific logic is not present. To access the user entity you have to load it manually:
$user = User::load(\Drupal::currentUser()->id());

Unfortunately there is no direct method like \Drupal::currentUser()->getEntity() :(
Comment: User roles can be accessed without loading user entity.
`\Drupal::currentUser()->getAccount()->getRoles(TRUE);`
Comment: There's an issue for this: [Add API for "upcasting" from AccountInterface to a full User entity?](https://www.drupal.org/project/drupal/issues/2123883).
Answer: Example of how to load current user and retrieve field data from user object.
<?php
// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// retrieve field data from that user
$website = $user->get('field_website')->value;
$body = $user->get('body')->value;

$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;
?>

Answer: Accessing methods on the \Drupal global class (like ::currentUser()) is OK in procedural code (e.g. in your mymodule.module file) but in your own OO code you should try to access the @current_user service, via a standard pattern called dependency injection (DI):
<?php

namespace Drupal\mymodule;

use Drupal\Core\Session\AccountProxyInterface;

class MyClass {
  /**
   * @var AccountProxy
   */
  protected $currentUser;

  public function __construct(AccountProxyInterface $currentUser) {
    $this->currentUser = $currentUser;
  }

  public function doSomething() {
    $currentUserId = $this->currentUser->id();
    /* ... */
  }
}

This pattern permits your code to be tested in complete isolation, with a dummy $currentUser object (anything which implements AccountProxyInterface, and can hugely reduce maintenance overheads.
However, DI isn't very intuitive and takes a while to understand. How you get the service into your object constructor depends on what the object actually is in Drupal e.g. plugins behave differently from registered services. There's more information on DI in Drupal 8 in the d.o docs.
[edit] A suggested edit to this answer (which was rejected by moderators) introduced public static function create() into the code, with no further explanation. However, it'd be misleading to add this class method without any further discussion.
For reference, this is what the create() function would look like:
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user')
    );
  }

The class method is not used by any services you register via a module's mymodule.services.yml: for these, the container calls the constructor directly. It's only ever useful for injecting into non-service classes; for example:

creating a custom form: you must declare you implement ContainerInjectionInterface so that the container knows to look for ::create().
creating a Drupal Plugin, using the wider Plugin architecture: you must declare you implement ContainerFactoryPluginInterface, which demands a different method signature for ::create().

This isn't the place to expand too much on dependency injection, but further information about the ::create() method is available on this blogpost.
Comment: I believe you would need to mention adding the @current_user argument to the services.yml file of the module we are writing.


Performance-optimizing Oracle 10g on a server that is also a Tomcat JSP app server?

Question: I have inherited a simple RedHat 5 - 64bit platform.
It has SCSI disks on RAID1, with 16GB of RAM. Double Core CPU.
Oracle 10g, Release 2.
This would be a decent platform for running the DB only, perhaps, but the same server in an "A-A mode" clustering (very simple) also runs Tomcat and there are several Java servlets running on this.
Sadly there is no caching platform etc. We only use an external CDN for some html caching.
I am personally more familiar with web environments on the LAMPP platform (apache, php, mysql, postgresql).
PROBLEM:
Because the server has both Tomcat JSP/Java and Oracle 10g running on the same server, with no caching, I have some issues of the server going down. Often, sadly.
QUESTION:
What are my options in terms of improving performance of all these different apps?

Connection Pooling? Example, in Postgresql world we have PgBouncer, which really helps things. Does Oracle have something similar? Or is there a famous Java-based external pooler that people use in production environments? (I'm not familiar with Java)
Any "SQL cache" as in the MySQL and Postgresql world?
Any other kind of application cache, as "APC" or "eAccelarator" in the PHP world?
The "OSCache" stuff from the Java world (JSP thingie I found on Google: http://onjava.com/pub/a/onjava/2005/01/05/jspcache.html?page=2)

...
What else?
Sorry if this is a noob question. I have googled and googled, but problem is I don't know what to google for, other than the broad general concepts above. So if not full answers, I would even appreciate basic pointers and I am happy to JFGI myself.
Thanks!
Answer: I believe Tomcat provides several options for connection pooling, although StackOverflow may be a better place to discuss these possibilities.
As for the rest:
Oracle bottlenecks and performance tuning is a wide and complicated field, and the same goes for J2EE applications, containers and caching.
A number of commercial and open source tools exist that should be of use, some go a long way towards both identifying possible problems and educating the user. One such commercial tool is Spotlight on Oracle by Quest Software. Quest also provides Performasure which I find to be an excellent solution for low level application diagnostics. http://www.quest.com/
Oracle provides a wealth of free documentation for their database platform on http://docs.oracle.com and http://tahiti.oracle.com including books on performance considerations and tuning.
Similarly, IBM Red Series include free books that cover performance tuning and bottlenecks related to anything from Oracle, J2EE, Linux, storage to generic system design. http://www.redbooks.ibm.com/
While not free, Oracle Database 10g Performance Tuning: Tips & Techniques is a great introductory book, so is Oracle Essentials: Oracle Database 10g if you need better understand the fundamentals of Oracle databases. You can read both online at http://www.safaribooks.com/ and I do believe they offer a free trial.
A good place to start, or at least as good as any, is to figure out what system resources are being strained, and who is using them. Is the CPU load high? If so, it caused by waiting on I/O? How is memory being used, is lack of memory causing additional I/O? Is the application or the database CPU intensive? Is the database workload CPU or I/O bound? Is the instability related to performance or could there be other issues on the system. Getting a few fundamental questions answered should at least get you on your way.
Answer: You should assure that the Tomcat JRE runs in server-mode (not client). This should be displayed on startup and is not always to be given. This should be an equal step to using eAccellerator in PHP-world - Servlets are compiled on load.
Connectionpooling is obviously neccessary. I don´t think there is a big chance to have an application without pooling. But better check it. E
In web applications I always got big improvements adding HTTP-Header (Pragma cache, Expires) to enforce caching static elements.
If you are capable of changing the programming, looking at SQL-Plans (explain) is always helpful ... it often showed me where I´m missing indexes.
And implementing caching of often used elements of course...
Another possibility to look could be increasing the Heap of the Tomcat (-Xmx....) - perhaps this helps if Tomcat runs out of memory and starts garbage collection.
What exactly do you mean with "going down"? Is the server getting slow or crashing?


Change workbench moderation state with VBO does not work properly

Question: I have two workbench moderation states draft and publihsed
When I try to change the state of a node from draft to published using VBO's set moderation state action, It actually republish the published revision. While it should publish the draft revision.

In the screenshot, it move the draft to published with revision 4 and that should be the published revision. But it is pointing to the revision 3 that this is the published revision.
Is there any workaround for this issue?
Any hint where to look?
Answer: The patch in https://www.drupal.org/project/workbench_moderation/issues/3160301#comment-13758806 fixes the issue.


formatar timestamp Excel

Question: Existe alguma formula no excel para formatação na coluna timestamp e passar para 1 coluna tipo hora que é o valor que me interessa.
Answer: Com Tue Apr 23 2019 11:49:21 GMT+0100 (GMT+01:00) em A2.
A seguinte função:
=TEXTO(EXT.TEXTO($A2;LOCALIZAR(":";$A2)-2;8);"hh:mm:ss")
Retorna:
Comment: Insiro a fórmula em A2?
Comment: Em outra coluna/célula, em A2 está o dado original

formatar timestamp Excel


How to search previous strings in a list until match found

Question: This question is derived from a previous question I have asked here but I've changed the input list and the question is different:
In brief, I am trying to extract the presence of an 'event' from an event list and once detected, I am looking for the location of the event from a location list. I look first in the sentence that the event happened in and then in the previous sentence. I want to find the occurrence of the location that is the nearest written location (prior to the event in the text) in the raw report
The problem I have is that the location may be in a sentence that is two or three sentences previous to the sentence with the event in so I would like to detect these too.
My input nested list is:
list(c("Oesophagus irregular z-line as previously.", " quad biopsies at ,,,m"
), c("Normal examination", "cardia mild inflammation."
), c("stomach normal", "No problems here",
"Everything  normal", "Small polyp EMR and completely removed", "GOJ normal",
"Nodule seen which was normal", "This was removed by EMR",
"All other sites normal  normal", " A small area of residual stomach was removed by APC "))

The event list
EventList<-c("RFA","EMR","APC")

The location list
LocationList<-function(){

  tofind <-paste(c("Stomach","Antrum","Duodenum","Oesophagus","GOJ"),collapse = "|")

  return(tofind)

}

My desired output is:
""
""
"stomach:EMR, goj:EMR, stomach:APC"

Attempt 1
@akrun very helpfully helped me to create the solution ( as long as only one previous sentence in the list of sentences is being searched for the location) as follows:
sapply(text,function(x) {

           x1 <- str_extract_all(tolower(x),tolower(paste(EventList, collapse="|")))
           i1 <- which(lengths(x1) > 0)
           if(any(i1)) {
             paste(unlist(Map(c, str_extract_all(tolower(x[i1-1]),
                                         tolower(LocationList())),
                       str_extract_all(tolower(x[i1]), tolower(LocationList())))),
                        toupper(x1[i1]), sep=":", collapse=", ")

           } else ""

             }

             )

It seems like I actually don't need to keep the input list as a nested list (and it is probably easier to keep it as a full text so I can use a regex on the whole thing for a positive lookbehind) and so the function above can be redefined (with the pseudocode for the part I am having trouble constructing)
sapply(text,function(x) {

text<-lapply(text,function(x) paste(x,collapse=";"))
text<-unlist(text)

               x1 <- str_extract_all(tolower(x),tolower(paste(EventList, collapse="|")))
               i1 <- which(lengths(x1) > 0)
               if(any(i1)) {

              #How to iterate through all the events found in the x1 and then search the nearest location (from the location list) behind this in each report?

} else ""

                 }
)

Answer: Check my solution:
library(tidyverse)
library(wrapr)

tofind <-paste(c("Stomach", "Antrum", "Duodenum", "Oesophagus", "GOJ"),collapse = "|")

EventList<-c("RFA","EMR","APC")

words <-
  YOURS_LIST %>%
  unlist() %>%
  str_replace_na()%>%
  str_c(collapse = ' ') %>%
  str_split(' ') %>%
  `[[`(1)

EventList %>%
  map(
    ~words %>%
      str_which(paste0('^.*', .x)) %>%
      map_chr(
        ~words[1:.x] %>%
          str_c(collapse = ' ') %>%
          str_extract_all(regex(tofind, ignore_case = TRUE)) %>%
          `[[`(1) %.>%
          .[length(.)]
      ) %>%
      paste0(':', .x)
  ) %>%
  unlist() %>%
  str_subset('.+:')

Comment: Hi @PawelChabros I get the error : Error: `.x` is not a vector (closure) in the EventList part and the words returns NA. Is it because some of my strings are empty maybe? If so, can this be accomodated?
Comment: It works perfectly on both of my computers. Did you assign your list to the variable `YOURS_LIST`?
Comment: OK @PawelChabros I got it to work. Thanks. I just had to add str_rename_na() just before str_c(collapse = ' ') %>%. Can you explain it especially the map ?
Comment: First map finds all positions for all `EventList` words. Then it cuts whole text from the beggining till that position, finds all words from `tofind` and takes the last one.


Certain js File Not Working in Drupal

Question: I'm trying to render one div before another.
I've tested the js on my local machine to make sure it works by creating a simple page. The code is as follows:
<!DOCTYPE html>

IMAGE

BODY

I've added the following code to a js file on my Drupal site:
(function ($, Drupal, window, document, undefined) {

    $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples

})(jQuery, Drupal, this, this.document);

My .info file links to the js and it is loading. Other elements that require javascript are working too. I've even tried adding the script in the html.tpl file, but that did not work either.
The divs I am trying to affect are nested deep within the html markup, and have several classes applied to them, compared to the simple version I have made. Could that be the reason? Am I not being specific enough?
Answer: This will help you
(function ($) {

Drupal.behaviors.exampleModule = {
attach: function (context, settings) {
  $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples

}

};
})(jQuery);

Read this https://drupal.org/node/756722 It will definitely help you.
Answer: It's most likely because you're attaching the event before the DOM is fully loaded (so the element you're trying to attach to doesn't exist yet). In your example HTML the JS is included after the DOM is loaded which is why it works.
Try this:
(function ($, Drupal, window, document, undefined) {
  $(function() {
    $('.content .body').insertBefore('.content .field-name-field-image-one'); // check before() examples
  });

})(jQuery, Drupal, this, this.document);

Certain js File Not Working in Drupal


synchronous vs async nodejs

Question: Say I have a sample code running in NodeJS
 function (){
   ///OPERATION 1

   ///OPERATION 2

}

Considering none of the operations require any sort of time out, by default would javascript run both at the same time or finish operation 1 then operation 2?
Comment: operation 1 then operation 2
Comment: If both operations are asynchronous... They would *start* in order. But, the bulk of their work (the actual I/O, etc.) would be done in parallel and they could complete (their callback is invoked) in either order.
Comment: @JonathanLonowski - since node js (and most engines) is single threaded, nothing is ever done in parallel.
Comment: @niry The JavaScript code can't be run in parallel, but the fully-native portion of the work – the portion actually reading the file's contents, querying the database for records, etc., that's written in C/C++ (as [addons](https://nodejs.org/dist/latest-v7.x/docs/api/addons.html) for Node.js) – can make use of additional threads.
Comment: @JonathanLonowski agree.
Comment: @JonathanLonowski Ok, we are playing catch with deleting messages.
Answer: No two lines of JavaScript ever run simultaneously within the same process. Ever.
See concurrency vs parallelism.
Asynchronous code in Node.js - assuming there are no worker processes involved - is always running with concurrency and never parallelism. Concurrency is easier to program and helps us build complex machinery quickly. To "scale up" you may need to bring in worker processes to do work in parallel.
In your example, if both operations are synchronous, they will run in the order they are written (1, 2). In fact, if operation 1 is synchronous it will always run first no matter what. If both are asynchronous, then how you experience it depends on how long they each take to complete! If operation 1 is asynchronous but operation 2 is synchronous, then they will seem to run in reverse order (2, 1). This has to do with the way functions get scheduled on the event loop, so understanding that will help this all make sense.

Take a breath. Time for a deep dive.

To be clear, in reality, lines of code always get executed in order. We don't have GOTO and the JavaScript engine does not mysteriously jump around to different places. The key thing to understand is that when someone says a function is asynchronous it is really also partly synchronous. Something is happening synchronously. Otherwise it would be an empty function. Instead, it just means that only a tiny bit of work is done synchronously, usually that simply consists of scheduling work for later, and then the rest of it happens later.
So above when I said that if they are both asynchronous then "it depends", it's merely the completion or result of that function (which you experience via a callback or Promise) whose order is undefined in relation to the completion of other asynchronous functions. This isn't the case for fully synchronous functions simply because the world stops for synchronous functions.
If you have two functions both trying to retrieve the same data from two different sources, one from your hard disk and one from the internet, which will finish first? If they are both asynchronous, then  it's a trick question. Probably the hard disk is faster, but don't bet your life on it. Still, one of them technically gets kicked off first, synchronously.
This paradigm of scheduling things for later and not waiting for the result before continuing (non-blocking) is one of the ways Node.js manages to have such great performance even without worker processes / parallelism. For I/O in particular, such as reading a file from the disk, there are "quiet periods" of inactivity where there is nothing for the process to do. In this case, waiting before continuing is a huge waste of time. It is more appropriate to use that opportunity to interleave other functions in the meantime. This is what asynchronous functions do. They delay work to allow us to interleave other work. Usually they achieve this via process.nextTick() or setImmediate().
All that said, nothing in life is free. Delaying work has a cost and if you misuse timers you will slow down your program. The goal is to make everything that has unavoidable delays (like I/O) asynchronous and almost nothing else. However asynchronous behavior "pollutes the stack". Anything that uses an asynchronous function becomes asynchronous in nature. You could return a value synchronously and pretend like it's not the case (make it invisible to the outside world), but that is usually a bad idea because then you cannot propagate errors or the result at all.
If you are still confused about how to look at a program and figure out when everything runs, have a look at async and await. It is a wonderful way to write asynchronous code that looks like more traditional synchronous code. And it is arriving in Node 7.
Comment: What does it mean for an operation to be 'async'?
Comment: @DilllyBar, that you know when it is started, and have no idea when it will be completed. It could be 1 ms, 1 hour or never. And you don't want your code to wait because, as mentioned, **everything** written in JS *(in that application)* will be frozen untill you got a result. Therefore you use a callback to be notified when you have a response/result, and to process that result *(as soon as it is available)*.
Comment: @Thomas, thanks a lot! Then what about sync operations? When do they end? What is the difference?
Comment: @DilllyBar, They also start immediately and they run as long as it takes to complete. And during that time JS can not do anything else (single thread). It simply executes the code; line by line, left to the right.
Comment: @Thomas, then how can I tell the difference between these two types when looking at a code? For example a Mongoose query is async, but I didnt know that
Comment: I added more detail. Hope it helps. As for "how can I tell", great question! it's difficult if you aren't looking at a full example or the source code. Today, looking at projects that use databases or the filesystem you may see code that looks like `foo().then(bar)`. The use of `.then()` is a clue that `foo()` may return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), making it async. Soon you will start seeing the [async keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function).
Comment: @DilllyBar, besides the mentioned `async` keyword, you can assume that async code will expect you to provide them some kind of "callback" function. Either as an additional argument to the async function or by registering an eventListener before starting the process *(like the complete event on XMLHttpRequest, before you call `send()`)*, maybe as a property on the config-object, and even the function you pass to as promises `then()` can be seen as a callback-function. So if a function doesn't return a result, but instead expects you to register a callback-function in any way, I'd call it async.
Comment: Indeed. Callbacks can fool you, though. For example, [Array#forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) does not return anything and does require a callback, but nothing about it is async. The [jQuery API](http://api.jquery.com/) has many similar examples. So you should be cautious about assuming a callback means async behavior. Take the time to read the docs, which will often specify if an API is async.

synchronous vs async nodejs


Avoiding framed forwarding for web app on port 8080 with DNS

Question: I have a play application running on port 8080. I currently forward to this by using
<code>http://ip_address:8080
</code>
as my 'URL to forward to' in my forwarding service control panel.
The problem with this is: frame forwarding is used and I think this may be stopping Google Analytic for working.
I have control over DNS
A, CNAME, AAAA, TXT and NS records
&
DNS Service records
For other websites in the past running on port 80 I have simply created an A record with the destination as the server IP address, however because I am using port 8080 in this case, this does not work.
What is the best way to go about getting away from framed forwarding?
Answer: You can't put port numbers into the DNS resource record (there's a notable exception, namely SRV records, but as client support for those is rather spotty, those won't be much help). A nameserver commonly resolves hostnames to ip addresses - no directory/file names, no port numbers.
You can use a permanent redirect, which is a webserver facility, used to tell web clients to contact a different webhost. In order to use that, you need a webserver which responds to requests on port 80, and knows that requests concerning your zone must be redirected to your actual webserver. Very similar to the iframe solution you've been already using, but a permanent redirect instead of iframe.
If your reason for dropping the current iframe approach isn't that you, for example, want to get rid of decorative framing, ads, "branding" etc  (with those, a permanent redirect would help), but want to cease using an intermediate webserver, adding another level of indirection to the queries, there's little you can do:
your firewall may be able to do port redirection, meaning that the incoming requests will hit your gateway/firewall on port 80, where the request is sent on to port 8080 where the webserver is actually listening. Another possibility could be, but requiring again another webserver, listening to port 80, to set up proxying: incoming requests to that webserver will be served from a cache on that server, which is populated and occasionally refreshed as result of that webserver querying your webserver on port 8080.
Even though with the latter suggestion an additional webserver will be existing, there'd be no visible indirection, as it would be transparent to clients: The web files are produced by the first server which is hit, even if they are once every so often taken from another server.


How to perform F-test in R for checking equality-of-variance (homoscedasticity/heteroscedasticity) if raw data is not given?

Question: In a typical two-sample problem scenario, I possess the sample mean, variance, and size, but not the raw data for samples drawn from two populations. I wish to perform the F-test to check equality of variance (homoscedasticity). In R, the built-in function var.test allows me to perform the F-test if I have the sample data in vector format, however, I don't have the raw data.

I found this library (BSDA) to perform the pooled t-test if raw data was not given.
How should I perform the F-test? Is there a library similar to BSDA for performing the F-test?
Answer: With data. First, it is important to know how the var.test in R works, if you do have the (normal) data.
Consider data as follows:
set.seed(2021)
x1 = rnorm(20, 19, 5);  x2 = rnorm(30, 10, 8)

stripchart(list(x1,x2), pch="|", ylim=c(.5,2.5))

With respective sample variances $S_1^2, S_2^2.$
The test statistic for testing
$H_0: \sigma_1^2/\sigma_2^2 = 1$ against
$H_a: \sigma_1^2/\sigma_2^2 < 1$ is $F = S_1^2/S_2^2.$ Under $H_0,$ $F \sim\mathsf{R}(\nu_1=19, \nu_2=29).$
var.test(x1, x2, alt="less")

        F test to compare two variances

data:  x1 and x2
F = 0.37735, num df = 19, denom df = 29,
 p-value = 0.01503

alternative hypothesis:
 true ratio of variances is less than 1

95 percent confidence interval:
 0.0000000 0.7838272
sample estimates:
ratio of variances
         0.3773455

The F-statistic is $S_1^2/S_2^2 = 0.3773.$
var(x1)/var(x2)
[1] 0.3773455

The P-value is $P(F \le 0.3773) = 0.015.$
pf(0.3773, 19, 29)
[1] 0.01501539

In the figure below the P-value for this one-sided test is the area under the density curve to the
left of the vertical black line.

R code for figure:
curve(df(x, 19,29), 0, 4, lwd=2, col="blue",
     ylab="Density", xlab="f", main="PDF of F(19, 29)")
abline(v =  0.3773, lwd=2)
abline(v = 0, col="green2")
abline(h = 0, col="green2")

Note: For a two-sided test, the P-value is doubled:
var.test(x1,x2)$p.val
[1] 0.03005009

With sample variances and sample sizes: Then with this background, it is easy to use R to do
a one-sided F test for equal variances if you know only the two variances and sample sizes. Just
use the PDF of the distribution $\mathsf{F}(19,20)$ to find the P-value $0.0150:$
v1 = var(x1);  v2 = var(x2);  f = v1/v2
v1; v2; f
[1] 29.63551
[1] 78.53681
[1] 0.3773455
pf(f, 19, 29)
[1] 0.01502505

For a right-sided test the P-value is computed
in the right tail of the F distribution. Here
are examples with data and with sample variances:
set.seed(1126)
y1 = rnorm(25, 30, 10)
y2 = rnorm(20, 45, 5)
var.test(y1, y2, alt="gr")$p.val
[1] 7.786383e-05
1 - pf(var(y1)/var(y2), 24, 19)
[1] 7.786383e-05

Comment: Not necessary. That identity is necessary only if you're using printed tables of the F distribution that give only upper tail quantiles (to save space in print). Software programs such as R will give lower tail probabilities and quantiles directly. // You mentioned R in your question, so I assumed you're using R.
Comment: Thanks @BruceET for the answer. However, in cases when the F-statistic is smaller than 1, the p-value is computed to be $2*p[F_{n_2-1;n_1-1}> 1/F_{obs}]$ for the 2-sided test.


How to json decode in php

Question: How to json decode in php
{
    TestID": 1,
    UserID": 1,
    TotalAttempted": 1,
    TotalQuestion": 1,
    LeftQuestion": 1,
    CorrectQuestion": 1,
    IncorrectQuestion": 1,
    TimeTaken": 1,
    "msg": [
        {
            "QuestionID": 5,
            "IsTrue": 1,
            "GivenAnswer": 1
        },
    ]
}

Comment: use` json_decode` see the [manual](http://php.net/manual/en/function.json-decode.php)
Comment: Ok thanks for your co-operating
Answer: Reference:- http://php.net/manual/en/function.json-decode.php
<?php
   $array = json_decode($json_variable,true);
  echo "
";print_r($array);
?>

Note:- Your json data have some missed ".
Example with a valid json:-https://eval.in/743659

How to json decode in php


MCMC combined with numerical integration towards more efficient Bayesian inference

Question: I am quite new to Bayesian statistics so the question can be a bit naive.
My question is on how to deal with a model with individual coefficients. Simple versions of a task and a model I deal with is bellow.
Let there are customers that visit our company from time to time. We are interested in modeling the inter-visit time intervals.
The intervals follow the gamma distribution:
$$
t_{ij} \sim \mathtt{gamma}(k,\theta),
$$
where $i$ is the customer number and $j$ the time interval number for the customer $i$ with $k \sim N(0,10)$.
However we also assume that customers are heterogeneous, which means that every customer has its own individual parameter $\theta_i$ and, in fact, we have the following model:
$$
t_{ij} \sim \mathtt{gamma}(k,\theta_i),
$$
where $\theta_i$ comes from the inverse gamma distribution:
$$
\frac{1}{\theta_i} \sim \mathtt{gamma}(\nu,\sigma),
$$ with $\nu,\sigma \sim N(0,10)$. Thus, the model has 3 parameters: $k,\nu, \sigma$.
The question is how to encode this model (in particular in stan) for efficient inference? The number of observations is high, e.g. 10000+.
The first option is to encode it straightforward and allow MCMC sample a large space including $\theta_i$ for every customer. However, it is at least slow and looks like the number of iteration in MCMC should be high.
Would it be correct to remove $\theta_i$ from the sampling space and substitute it with numerical integration for computing the target log likelihood as follows:
$$
t_{ij} \sim \int \mathtt{gamma}(k,\theta)\mathtt{gamma}\left(\frac{1}{\theta} | \nu,\sigma\right)d{\theta},
$$
where the integral can be computed by taken for example just 1000 (instead of 10000+) points of $\theta^{(i)}$ (given $\nu$ and $\sigma$) that are not included into the MCMC sampling space.
PS: If "model with individual coefficients" is an incorrect term, I would be grateful to know the correct one, since the correct terms dramatically increase the search possibilities.
UPD: I describe the exact model I want to implement, since without it my question seems to be misguiding. The model is from Allenby G.M., Leone R.P., Jen L. A Dynamic Model of Purchase Timing with Application to Direct Marketing // J. Am. Stat. Assoc. 1999. Vol. 94, № 446. P. 365. For simplicity I provide no priors.
$$
t_{ij} \sim \Phi(\beta_i\cdot x_{ij})\cdot \mathtt{ggamma}(k_1,\theta^{(1)}_i,\gamma) + (1-\Phi(\beta_i\cdot x_{ij}))\cdot \mathtt{ggamma}(k_2,\theta^{(2)}_i,\gamma),
$$
$$
\frac{1}{\theta^{(1)}_i} \sim \mathtt{ggamma}(\nu_1,\psi_1,\gamma),
$$
$$
\frac{1}{\theta^{(2)}_i} \sim \mathtt{ggamma}(\nu_2,\psi_2,\gamma),
$$
$$
\beta \sim N(\mu,\sigma),
$$
where $\Phi(x)$ is normal CDF. So the parameters of the model are $\mu,\sigma,$ (vectors corresponding to the covariates $x_{ij}$) $\nu_{1,2},\psi_{1,2}, k_{1,2}$ (just 6 numbers). The value of $\gamma$ is considered as a constant and is not from the optimization space.
Comment: It is not correct to do that because the $t_{ij}$'s are no longer independent when $\theta_i$ is integrated out.
Comment: I can't really help you with this problem, but for details on coding the model in Stan it might be faster to ask on the Stan forums (https://discourse.mc-stan.org/).
Comment: Thank you, Maurits! I will duplicate my question also there
Comment: @guy, intuitively it is not correct, however, if I am not wrong, formally the result is the same. You just compute the probability the get all several values together that is basically the same as get them independently. The dependence is only needed to determine the $\theta_i$.
Comment: @guy, see alse the answer by **Xi'an**
Comment: @Aleskey Xi'an's answer takes account of the dependence through reduction to the sufficient statistic. The result is not a product over the $t_{ij}$'s that your OP implies it is.
Comment: @guy, thank you, I was wrong. It basically means that I should compute sum of log probabilities for every customer given a $\theta$ and the **log_sum_exp** on base of $\theta$ samples?
Answer: A first reduction of complexity is to use sufficiency: if
$$t_{ij} \sim \mathtt{gamma}(k,\theta_i),$$
then
$$t_{i\cdot} = \sum_{j=1}^J t_{ij} \sim \mathtt{gamma}(J\times k,\theta_i),$$
is sufficient. And integrating out the $\theta_i$'s is also feasible by conjugacy
$$\int_0^\infty \theta_i^{-Jk-\nu-1}\exp\{-\theta_i^{-1} [t_{i\cdot}+\sigma]\}\,\text{d}\theta_i = \Gamma(Jk+\nu)[t_{i\cdot}+\sigma]^{Jk+\nu} $$
So there is no need for a call to simulation methods.
Comment: Thank you for  this answer. However, it seems, that this is only valid if we consider gamma distribution. In the actual model there is a mixture of two generalized gamma distribution with individual $\theta$ as well as with individual probability for the mixture that depends on some covariates. You also cannot do the first step unfortunately since the weights in the mixture depend on the interval. Here I have simplified the task, probably two much. My main concern was on what can we do the individual coefficients.
Comment: If you ask a question about one model and want an answer about another model, what is the point of asking the question?
Comment: Sorry for this, my point is not to be too specific. I want to deal with individual coefficients, and the model is given as an example. If I would have asked about my model, it is unlikely that it would be useful for a large number of people, is not it? I am new to the community, so if it is better to provide the most specific description of the model, even if it is useful for only a few people, I will do that.
Answer: What you have in the OP is not exactly true, but there is a correct way to do this sort of thing. Suppose that I have parameters $\theta_1, \ldots, \theta_N \sim g(\theta \mid\eta)$ given $\eta$, and I use a prior $\eta \sim F$. Then the joint distribution of the $\theta$'s after integrating out $\eta$ is
$$
m(\pmb \theta) = \int \left(\prod_{i = 1}^N g(\theta_i \mid \eta) \right) \, F(d\eta). \tag{$\dagger$}
$$
A "folk-theorem" in MCMC is that chains based on $(\dagger)$ leads to better mixing, i.e., it is better to marginalize things out if you can. It is not strictly true, as there are some situations where parameter-expansion ideas lead to better mixing, and it also matters what exactly you do with $m(\pmb \theta)$ to sample it, but it is a useful rule of thumb.
So, for example, it would be valid, in STAN to do
target += log_m(theta)

assuming you can write a function log_mthat computes the log of $(\dagger)$. That's the tricky part, of course, since log_m may not be easy to evaluate to a given accuracy.
Actually, this is how the makers of STAN recommend that one incorporates discrete parameters, because HMC cannot deal with discrete parameters directly. They recommend summing out the discrete parameter, which is equivalent to $(\dagger)$ when $\eta$ is discrete (e.g., it might be a mixture component indicator).
Comment: @Aleksey there are enough pitfalls in doing this type of thing numerically that I'm not sure I would recommend it to a novice. Monte Carlo integration will induce bias, and correcting this bias is non-trivial and probably cannot be done using STAN. And numerical integration is also not so easy in that, if $N$ is large, the mass is likely to be concentrated in a very tiny area (it is also quite expensive potentially).
Comment: Thank you! So it means that I can try to numerically integrate it. The most "fast-and-dirty" approach is a random sampling, i.e., Monte-Carlo method. Is it possible to randomly sample from a distribution in the model (I guess I should not put it in the parameters, since I do not want to optimize w.r.t. these sampling)? As far as I know *_rng functions are not available in the model part.


Comunicação com CLP Siemens

Question: Em breve estarei desenvolvendo uma interface com CLP da Siemens, modelo ET-200A.
Esse é um assunto novo para mim e aí estou com algumas dúvidas.
Alguém já lidou com esse tipo de comunicação?
A comunicação é a mesma para qualquer tipo de CLP da Siemens?
O CLP guarda como a informação dentro dele? Tem um banco de dados?
A ideia é desenvolver em C#, coletar a informação do CLP e persistí-la em um banco de dados SQL. A parte da persistência é bem tranquila para mim.
Não encontrei nada a respeito desse modelo na Web-esfera.
Comment: Olá Daniel,  te aconselho a fazer um [tour](http://pt.stackoverflow.com/tour) para conhecer melhor o site.
Answer: Olá, trabalhei bastante tempo com automação industrial e posso te dar um norte.
A comunicação com CLPs pode ser feita utilizando vários meios, um deles é com protocolo OPC ( OLE for Process Control ), a maioria dos CLPs ( Siemens, Rockwell etc) possuem este protocolo, mas existem outras interfaces como RS232. O OPC é um protocolo que facilita a captura de dados, geralmente o fabricante disponibiliza um "server controller' que faz a interface entre sua aplicação e o hardware. Nos CLPs da Rockwell da família Contrologix, quem faz essa interface é o RSLinx, para CLPs siemens existe o STEP 7. Neste "server controller" você mapeia todos os endereços dos CLPs da sua rede a adiciona quais o bits de cada CLP que deseja "compartilhar". Após essa configuração, você deve possuir um componente para a sua linguagem de programação, no meu caso utilizava Delphi com o componente pago Kassl OPC Client, mas existe também a versão para .NET. Nestes componentes você configura os endereços dos CLPs e os bits que deseja capturar.
O CLP pode armazenar algumas informações, mas são limitadas, por que o hardware possui pouca capacidade de armazenamento, e é programado para executar uma tarefa. Então ele fornece a você as informações em tempo real, basta você capturar essas informações e estruturar no seu banco de dados SQL e gerar histórico se for o caso.
Existe um projeto de software livre muito interessante, o ScadaBR. Este software possui todos os componentes necessários para você já começar a desenvolver o seu sistema de monitoramento com CLPs.
Não há muita informação sobre automação industrial mesmo na internet, é um mercado bastante restrito, mas foi pior no passado.
Comment: Obrigado pela ajuda, agora já tenho uma idéia por onde começar

Comunicação com CLP Siemens


Help starting with Integration by parts

Question: I am working on an assignment that deals with integration by parts and u-substitution and I have become frustratingly stuck on this question. I am unsure where to even start.
Question:
Let $f$ be a twice differentiable function such that $f(0)=5$, $f(3)=1$, and $f^{'}(3)=-2$. Determine the value of $$\int_0^3xf^{''}(x)dx$$
I would greatly appreciate if someone could explain to me at least how to start this.
Thanks.
Comment: HINT: Use IBP with $u=x$ and $dv=f''(x)dx$...
Answer: Let $u=x$ and $dv=f''(x)\,dx$. Then $du=dx$ and we can take $v=f'(x)$. So our integral is equal to
$$\left.xf'(x)\right|_0^3-\int_0^3 f'(x)\,dx.$$
Note that the remaining integral is $f(3)-f(0)$.
Comment: Thanks for the help. I was making this problem much harder than I should have.
Comment: You are welcome. This sort of problem can unfortunately confuse students who can integrate by parts perfectly well. So I avoid this kind of thing on exams. However, it is a suitable homework problem.
Answer: Let $v=f'(x)$ and $u=x$. Then $dv=f''(x)dx$ and $du=dx$. Integrating by parts yield
$$\int_0^3xf''(x)dx=\left.xf'(x)\right|_0^3-\int_0^3f'(x)dx=3(-2)-0-\left.f(x)\right|_0^3=-6-(1-5)=-2$$
Answer: Using Integration by Parts, we can do the following:
Let $u=x, \ dv = f^{\prime\prime}(x)dx \implies du = dx ,\ v=f^\prime(x)$.
Now \begin{align*}\int\limits_{0}^{3}xf^{\prime\prime}(x)dx &= [xf^{\prime}(x)]^3_0 - \int\limits_{0}^3 f^{\prime}(x)dx \\ &= 3(-2) - [f(x)]^3_0 \\&=-6 - (1 -5)  \\ &=-6+4\\ &=-2\end{align*}
Answer: When I was first learning Substitution by Parts, the following approach was very useful to me in trying to understand the method.
By the multiplication rule for derivatives.
$$f'(x)G(x)+f(x)G'(x)=[f(x)G(x)]'$$
$$f(x)G'(x)=[f(x)G(x)]'-f'(x)G(x)$$
Let $g(x) = G'(x)$, then
$$f(x)g(x)=[f(x)\bigg(\int g(x)dx\bigg)]'-f'(x)\bigg(\int g(x)dx\bigg)$$
$$\int f(x)g(x)dx=f(x)\bigg(\int g(x)dx\bigg)-\int f'(x)\bigg(\int g(x)dx\bigg)dx$$
This shows me that when integrating the product of two functions that one factor will be differentiated $(f)$ and the other will be integrated $(g)$. Technically this equation (as written) isn't correct because it assumes that both $\int g(x)dx$'s evaluate to the same function (e.g. the first $\int g(x)dx$ could evaluate to $h(x)$, and the other one to $h(x)+C$), but it provides a nice direct way of thinking about the method (i.e. it allows me to avoid asking convoluted questions like "$g$ is the derivative of what function?"). To make it technically correct, replace both $\int g(x)dx$'s with $G(x)$.
Applying this point of view to your problem we have
$$\begin{array}{lll}
\int^{3}_{0}xf''(x)dx&=&\bigg[x\bigg(\int f''(x)dx\bigg)-\int 1\cdot \bigg(\int f''(x)dx\bigg)dx \bigg]^3_0\\
&=&\bigg[xf'(x)-\int f'(x)dx\bigg]^3_0\\
&=&\bigg[xf'(x)-f(x)\bigg]^3_0\\
&=&3f'(3)-f(3) -[0f'(0)-f(0)]\\
&=&3(-2)-1 +5 = -2\\
\end{array}$$
As an example, try it with
$$\int \ln x dx = \int (\ln x)(1) dx=\dots$$

Help starting with Integration by parts


Shared component with specific click function

Question: I have created a shared component with below html:
<ion-row class="tableContainer">

            <ion-icon title={{b.styleClass}} name={{b.value}} (click)="clickTest()"></ion-icon>

</ion-row>

Then, I can use them in some pages like this:
<data-table [dataTitle]="invoicesDataTitle" [data]="invoicesData" [dataButtons]="invoicesDataButtons"></data-table>

My problem is that when I click the button, I want to call the method in the page that used data-table, instead of the method in data-table component. How can I do that?
Comment: I think this is covered in the docs: [Parent listens for child event](https://angular.io/guide/component-interaction#parent-listens-for-child-event).
Comment: Correct. Either use an EventEmitter or a shared service. Depends on complexity of your Application
Answer: The correct way to handle this is for your component to emit an event that the parent can listen to.
<data-table [dataTitle]="invoicesDataTitle" [data]="invoicesData" [dataButtons]="invoicesDataButtons" (dataClick)="currentPageHandler($event)"></data-table>

Inside your data-table.component.ts
@Output() dataClick = new EventEmitter<SomeEventType>();

clickTest() {
    this.dataClick.emit({data: someData} as SomeEventType);
}

Comment: By doing this, does each page now can have its own click method?
Comment: Yes, each parent component can implement its own click handler for what to do when the `ion-icon` element is clicked.


The effect of covariate measurement error on coefficients in regression with dummy variables

Question: I am trying to understand if I should be more concerned with covariate measurement error in linear models including dummy variables, than with all continuous predictors. Say I have a simple linear model with one independent variable (IV) and one covariate:
\begin{align}
Y_i = \beta_0 +\beta_1X_i+\beta_2Z_i+\epsilon_i
\end{align}
where $Y_i$ is the dependent variable, my error term $\epsilon_i \sim N(0,\sigma_{\epsilon}^2)$, $X_i$ is my independent variable, and $Z_i$ my covariate measured with a stochastic measurement error $\eta_i \sim N(0,\sigma_{\eta}^2)$. Does the measurement error affect the estimates of the effect of my IV: $\beta_1$ any worse for a dichotomous vs. continuous IV?
Bonus. How are the IV estimates affected by measurement errors when there is 1) a systematic measurement error of the covariate 2) more than one IV 3) more than one covariate with independent errors 4) more than one covariate but with correlated errors.
It seems to me there should not be a qualitative difference, but  a colleague told me that ANCOVA results are very unstable with respect to measurement errors in the covariates, as opposed to regression. This worries me because I often use dummy variables in a regression where the covariates have a sizable measurement error.

My attempt at a solution.
say $y$, $x_1...x_{n-1}$ and $z = z^*+u$ are particular realizations of the variables in the model, and u is the measurement error.
Using the standard formula for the estimates $$\hat\beta = (X^TX)^{-1}X^Ty$$ so $$\hat\beta_i= \frac{1}{2|\text{cov}(X,X)|}\sum_{j=1}^n \epsilon_{jpq}\epsilon_{ikl}\text{cov}_{pk}(X,X)\text{cov}_{ql}(X,X)\text{cov}_{j1}(X,y)$$
where the permutation symbol $$\epsilon_{ijk} = \left\{ \begin{array} \\ 1 & i,j,k = 1,2,3; 2,3,1 \text{or} 3,1,2 \\ -1 & i,j,k = 3,2,1; 2,1,3 \text{or} 1,3,2 \\ 0 & \text{else}\end{array} \right.$$
now measurement error will only affect the $\hat \beta_i$ where the covariance matrix element cov$_{jk}(X,\cdot)$ includes the covariate with the error terms. That doesn't seem to be affected by whether we use a dichotomous or continuous variable. So the only thing that could be affected is the determinant in the denominator, so we probably should be weary of collinearity that can arise with many dummy variables, other than that I don't see how using dichotomous variables can be any worse.
Answer: How does measurement error in a binary predictor affect bias?
Starting from the single variable case, we observe a binary variable $x$ which is the true predictor measured with error, $X = x + u$ (I drop the $i$ subscripts for convenience). For the sake of the illustration and because much of this work was done in that field, let's suppose $X$ is a disease and $x$ is a doctor's diagnosis. Let's define the following quantities:

$P$ is the proportion of people in the population who truly have the disease
$\tilde{P}$ is the proportion of people diagnosed with the disease according to our doctor, then $\tilde{Q} = (1-\tilde{P})$ is the proportion of those diagnosed as healthy
$\eta$ is the proportion of people who truly have the disease but are classified as not having the disease
$\nu$ is the proportion of people who are truly healthy but who are classified as having the disease

The errors-in-variables framework is then
$$P = (1-\nu)\tilde{P} + \eta \tilde{Q}$$
in order to allow misclassification into both directions. From the set-up the marginal distributions of $X$ and $x$ are Bernoulli with parameter $P$ and $\tilde{P}$, respectively.
Savoca (2000) derives the quantities needed for evaluating the bias of OLS,
$$
\begin{align}
E(u) &= \nu - (\eta + \nu)P \\
Var(u) &= \nu + (\eta - \nu)P - \left[\nu - (\eta + \nu)P\right]^2 \\
Cov(x,u) &= -(\eta + \nu)P(1-P)
\end{align}
$$
So as compared to the classical measurement error in a continuous explanatory variable the error here does not have zero mean unless $E(X) = E(x) = P$ - but this would mean that there is no misclassification in our diagnosis.
The corresponding coefficient from the above regression with one binary regressor with error would be
$$\widehat{\beta} = \beta \left[ \frac{P(1-P)(1-\nu-\eta)}{\tilde{P}(1-\tilde{P})} \right] $$
The resulting bias, as in any other measurement error case, is towards zero. This has been shown as early as Aigner (1973).
Is measurement error worse for binary or continuous predictors?
In terms of whether measurement error in a binary variable is worse than that in a continuous variable it is not necessarily obvious which case has a larger bias. Consider the following simulation exercise (using Stata). First we try the errors-in-variables framework with a binary predictor:
<code>set seed 777
set obs 1000

* suppose the true P = 0.44
* generate our true X
gen X = rbinomial(1, 0.44)

* generate some error to be used in constructing the observed x
gen e = rnormal(0,1)
gen error = (e>2) | (e<-1.5)

* generate the observed x (with error)
gen x = X
replace x = 0 if X==1 & err==1
replace x = 1 if X==0 & err==1

* generate the dependent variable with true beta = 1.2
gen eps = rnormal(0,1)
gen y = 1 + 1.2*X + eps

* regression with measurement error
reg y x
</code>
The result is
<code>      Source |       SS       df       MS              Number of obs =    1000
-------------+------------------------------           F(  1,   998) =  180.45
       Model |  208.290565     1  208.290565           Prob > F      =  0.0000
    Residual |  1152.00081   998  1.15430943           R-squared     =  0.1531
-------------+------------------------------           Adj R-squared =  0.1523
       Total |  1360.29137   999  1.36165303           Root MSE      =  1.0744

------------------------------------------------------------------------------
           y |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
           x |   .9171922   .0682789    13.43   0.000     .7832055    1.051179
       _cons |   1.109043   .0458538    24.19   0.000     1.019062    1.199024
------------------------------------------------------------------------------
</code>
So that's pretty far off the true value. The correlation between $X$ and $x$ here is 0.8 and if we consider a similar correlation for their continuous versions,
<code>*specify a correlation matrix
matrix C = (1, 0.8, 0 \ 0.8, 1, 0 \ 0, 0, 1)

* simulate the data (fortunately here we can use a Stata function rather than doing all by hand)
corr2data X x e, n(10000) means(0.5 0.5 0) sds(0.5 0.5 1) corr(C)
gen y = 1 + 1.2*X + e
</code>
the result is
<code>. reg y x

      Source |       SS       df       MS              Number of obs =   10000
-------------+------------------------------           F(  1,  9998) = 2039.25
       Model |  2303.76962     1  2303.76962           Prob > F      =  0.0000
    Residual |  11294.8704  9998  1.12971298           R-squared     =  0.1694
-------------+------------------------------           Adj R-squared =  0.1693
       Total |    13598.64  9999        1.36           Root MSE      =  1.0629

------------------------------------------------------------------------------
           y |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
           x |        .96   .0212587    45.16   0.000     .9183288    1.001671
       _cons |       1.12   .0150318    74.51   0.000     1.090535    1.149465
------------------------------------------------------------------------------
</code>
which is only marginally closer to the true value than what we had in the binary case. However, what will happen in reality is going to depend on several factors. In the binary case you can already see how many parameters affect the resulting bias, i.e. the true prevalence and the observed prevalence of the disease, and our error rates among the classes.
In this sense you can probably come up with settings of $P$, $\tilde{P}$, $\nu$, and $\eta$ that are much closer to the true value (or much further off) than the coefficient of a continuous variable with measurement error. For the latter only the signal to noise ratio matters regarding the size of the bias, i.e. how large is our measurement error.
What happens if the measurement error in the binary variable is systematic?
If you want to investigate the case of non-standard measurement error in the binary case (which is actually already non-standard), then simply set $\nu = 0$ or $\eta = 0$ in order to create a scenario where we make a systematic classification error in either direction. I'm not aware though of a paper which looks exactly at such a setting.
What happens to other explanatory variables?
In the binary case with measurement error it can be shown that this bias affects all other explanatory variables unless they are uncorrelated with the mismeasured binary predictor. The relevant reference for this would again be Savoca (2000).
Regarding the final questions "3) more than one covariate with independent errors 4) more than one covariate but with correlated errors", I'm not sure if this means two (or more) covariates and all of them are measured with error. Or one of the covariates is measured with error and the error is correlated with the regression error. In the latter case we go back to the non-standard errors-in-variables framework. For multiple covariates that are measured with error the bias will depend on each variables measurement error and the correlation between the covariates. If all covariates are uncorrelated then we can assess the measurement errors separately if they are continuous. If they are not continuous then we are again in the Savoca framework.
As concerns question 4) I am not aware of a paper that derives the exact bias of such a case. Correlation between errors and with several covariates with measurement error is presumably a very complex case for which it will be difficult to find a closed form solution to the bias unless one is willing to make strong assumptions on the relationship between the errors and they distributions.
Caveat: despite it's length I am sure that this answer does not answer all your questions to the extent to which it would have helped you the most. It is not possible to consider all scenarios in equal detail so I tried to focus on certain aspects that I thought would be the most important and tried to highlight relevant literature for the other parts.
Comment: Thank you, this detailed answer helped me understand how to handle the errors in variables and pinpoints how measurement error affects the $\hat{\beta}$. The only part of the question that I feel this answer did not address in detail is: if I have two correlated predictors, one of them is binary (without measurement error) and the other is continuos (measured with measurement error), does the error in the continuous predictor, have any affect on the beta for the dichotomous predictor other than biasing it towards zero?
Comment: The coefficient of the mismeasured continuous variable is biased towards zero. Whether the binary predictor's coefficient is biased up or down depends on its correlation with the mismeasured continuous predictor, so it's not necessarily biased towards zero. See for example these lecture notes: https://www.google.co.uk/url?q=http://www.nuff.ox.ac.uk/teaching/economics/bond/endogeneity1.pdf&sa=U&ei=vPIjVZzmJ9fmapGcgOAJ&ved=0CBAQFjAA&usg=AFQjCNEhU7S9Yqp_VQFP3eY-o279HcPrXA


Carregar "php.ini" especifico para um sub-domínio

Question: Para carregar um php.ini personalizado para um sub-domínio, apliquei no .htaccess na raiz do sub-domínio em questão o seguinte código:
AddHandler php5-fastcgi .php
Action php5-fastcgi /cgi-bin/php.fcgi

O ficheiro só tem estas duas linhas.
O mesmo carrega as definições em condições e de forma independente do domínio principal, que consigo ver através do phpinfo().
Problema
Com a linha em cima presente no .htaccess, deixo de conseguir aceder ao sub-domínio, só conseguindo aceder ao mesmo através do domínio principal seguido da pasta onde se encontra o sub-domínio:
Acesso pretendido:
http://sub.dominio.com/

Acesso que funciona com as directivas em cima:
http://www.dominio.com/sub/

Nota:
No htaccess na raiz do domínio principal existem diversas directivas para uso do mod_rewrite.c, mod_deflate.c, Options, IndexIgnore, Header, as quais se relevantes para o problema poderei adicionar aqui.

Pergunta
O que falta ou estou a fazer de errado para perder o acesso directo via sub-domínio quando tenho as duas linhas no .htaccess do mesmo?
Answer: Use a diretiva PHPINIDir na configuração de virtual host do site para o qual você quer especificar um php.ini personalizado.
<VirtualHost 220.127.116.11:80>
    PHPINIDir /var/www/web1
</VirtualHost>


How exactly do the odds multiply when "evidence" adds up?

Question: I was reading an answer explaining the justification for using the sigmoid function in logistic regression. The reason given was essentially "when evidence adds up, the odds multiply". This is the exact excerpt:

For example, there are two Boolean features of an animal: x1 says whether it has a long tail, x2 says whether it is small sized. The two features are used to predict y: whether it is a rat. When either of the features is activated (true), the likelihood ratio is 3. When both are activated, the probability that it is a rat is 9 times of the probability it isn't.
You may notice that independence between different feature effects is assumed.

Now I'm struggling with how exactly, he got to that probability ratio of 9. Essentially, we are trying to compute:
$\frac{P(Y=1|x_1,x_2)}{P(Y=0|x_1,x_2)}$
How exactly can we transform that to this:
$\frac{P(Y=1|x_1) \cdot P(Y=1|x_2)}{P(Y=0|x_1) \cdot P(Y=0|x_2)}$
And how can we formulate the "independence between feature effects" mathematically?
My considerations so far
I tried to reduce the term $P(Y=1|x_1,x_2)$ to something containing $P(Y=1|x_1) \cdot P(Y=1|x_2)$ multiplied by a constant term that does not depend on $Y$. So essentially getting
$P(A|B,C) = P(A|B) \cdot P(A|C) \cdot T$ with $T$ not containing $A$.
But using the basic probability laws, I only got
$P(A|B,C) = P(A,B|C)\cdot \frac{1}{P(B|C)} = P(B|A,C) \cdot P(A|C) \cdot \frac{1}{P(B|C)}$
Now, I'd need to transform $P(B|A,C)$ to $P(A|B)$ times a term not containing $A$. And at that point I am stuck.
Answer: This example is confusing because

it suggests (though never states) that the input variables $x_1,x_2$ are discrete, and
they probabilities are not really conditional probabilities.

Logistic regression takes input from a continuous variable and maps that to a probability of belong to a discrete output (a binary classification of either 0 or 1). For some (previously unseen) value $X=x$, it returns a value $P(Y=1)$. Since there are only two classes, $P(Y=0)$ follows trivially:
$$P(Y=0) = 1-P(X=1).$$
These are not conditional probabilities in the sense that
$$P(Y=1 \, \cap \, X=x) \neq P(Y=1 |X=x)P(X=x),$$
so I'm going to go ahead and call this out as an abuse of notation. My proposal would be to replace the bar with a semicolon: $P(Y=1|x) \rightarrow P(Y=1;x)$.
The fact that the odds multiply is really just a feature of the logistic model; you won't be able to see it as a consequence of the laws of probability.
If you're concerned about $x_1$ and $x_2$ being correlated, I would plot them together and check the covariance matrix. Detecting and quantifying the effect of correlated independent variables is beyond the scope of this answer; see What is the effect of having correlated predictors in a multiple regression model?


Surface are of a curve $y=\sin \left(\frac{\pi x}{6} \right)$ rotated about the $x$ axis.

Question: I'm doing a problem involving finding the surface area of the curve for $y=\sin \left(\frac{\pi x}{6} \right)$, rotated about the $x$ axis, for $[0 < x < 6]$.
I got as far as $\frac{72}{\pi} \int^{\pi/6}_0 \sqrt{1+u^2} du$ with $u=\frac{\pi}{6}\cos(\frac{\pi x}{6})$. I'm not really sure how to precede from this point though.
Comment: Is that $S$ supposed to be an integral symbol?
Comment: See this: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: [Here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is a link for math formatting used here.
Comment: To complete the integral, substitute $u=\sinh \theta$
Comment: It's what's known as a [hyperbolic function](http://mathworld.wolfram.com/HyperbolicFunctions.html). If you're not familiar with them, you can use a trigonometric substitution of $u=\tan \theta$ instead.
Comment: Yea. It is. One thing I haven't figured out how to put correctly here yet...
Comment: what does the h at the end of sin mean? Not familiar with sinh.
Answer: Here's a plot of the surface of revolution:

The area of the surface is given by
$$2\pi\int_0^6\sin\frac{\pi x}{6}\sqrt{1+\left(\frac{\mathrm{d}}{\mathrm{d}x}\left[\sin\frac{\pi x}{6}\right]\right)^2}\,\mathrm{d}x=2\pi\int_0^6\sin\frac{\pi x}{6}\sqrt{1+\frac{\pi^2}{36}\cos^2\frac{\pi x}{6}}\,\mathrm{d}x$$
Substituting $u=\frac{\pi}{6}\cos\frac{\pi x}{6}$, so that $\mathrm{d}u=-\frac{\pi^2}{36}\sin\frac{\pi x}{6}\,\mathrm{d}x$, you get the integral you're currently stuck on:
$$-\frac{72}{\pi}\int_{\pi/6}^{-\pi/6}\sqrt{1+u^2}\,\mathrm{d}u=\frac{144}{\pi}\int_0^{\pi/6}\sqrt{1+u^2}\,\mathrm{d}u$$
(I believe you made a slight mistake with either the coefficient or the lower limit of the integral here.)
Now, substituting $u=\tan t$, you have that $\mathrm{d}u=\sec^2t\,\mathrm{d}t$, and so the integral is
$$\frac{144}{\pi}\int_0^{\tan^{-1}(\pi/6)}\sqrt{1+\tan^2t}\sec^2t\,\mathrm{d}t=\frac{144}{\pi}\int_0^{\tan^{-1}(\pi/6)}\sec^3t\,\mathrm{d}t$$
The latter integral can be computed in a variety of ways, and the process is described in detail here.
Comment: How do you get to the 144/pi and negative gone?
Comment: @windy401 The integrand is symmetric about $u=0$ (i.e. an even function), so $$\int_{-a}^af(u)\,\mathrm{d}u=2\int_0^af(u)\,\mathrm{d}u$$
Comment: Ohh ok thanks..


Given ring with identity $R$ and ideals $I, J$, with $I+J=R$ and $IJ=0$, prove $I\cap J=0$

Question: Give a ring with identity $R$ and its ideals $I, J$, with $I+J=R$ and $IJ=0$, I was required to prove $R\simeq R/I \times R/J$.
My understanding is $R/I\cap J \simeq R/I \times R/J$ so $I\cap J=0$ must hold if I'm able to do so.
Work done:
Since $1$ belongs to $R$, $1=u+(1-u)$ with $u$ in $I$ and $1-u$ in $J$, with $u(1-u)=0$.
For arbitary $v\in I\cap J$ we have $uv = 0$ and $v(1-u)=0$ i.e. $v=vu$.
If the ring is commutative or just $JI=0$ (we have $vu=0$ and $v=uv$) will force $v=0$. Neither commutativity nor $JI=0$ is given. I am aware of this conterexample but this example uses left ideals $(x)=Rx$, while the ideals defined in my book is always $(x)=Rx+xR+RxR$.
Edit: It seems $R=\mathbb{Z}\langle x,y|2x+2y-1=xy=0\rangle,I=(x),J=(y)$ have $I+J=R$, $IJ=0$ and $I\cap J=JI=(yx)$ (note x and y does not commute). Is this a counterexample or something is wrong?
Comment: Yeah, so you probably should work out the example given in that answer and see if it is also a counterexample for your problem.
Comment: You might want to check out this: https://math.stackexchange.com/questions/1222474/a-noncommutative-counterexample-to-the-following-property-if-i-j-are-comaxima?rq=1. The answer showed that $IJ+JI = I \cap J$, so I am not sure what is happening in your case.
Comment: So $IJ=0$ means $I\cap J=JI$, but $JI=0$ is precisely what is NOT given...
Answer: Here's maybe an easier counterexample. Take $R$ to be the ring of lower triangular 2x2 matrices over a field, with basis $e,f,x$ such that $e,f$ are orthogonal idempotents and $x=fxe$. Set $I=ReR$ having basis $e,x$, and $J=RfR$ having basis $f,x$. Then $I+J=R$ and $IJ=0$ but $JI$ has basis $x$.


Questions on Kolmogorov Zero-One Law Proof in Rosenthal

Question: Here is the proof of the Kolmogorov Zero-One Law and the lemmas used to prove it in Rosenthal's Probability book:

Here are my questions:
Question 1: In the first red box, does the fact that Q and P agree on J hold because of the statement in the blue box?
Question 2: What is the relevance of "independence is defined in terms of finite subcollections only" ? I was thinking that we can infer the independence of $A, A_1, A_2, ...$ merely from the $\forall n \in \mathbb{N}$.
Here is what I think "independence is defined in terms of finite subcollections only" means:
Given events $(A_n)_{n \geq 1}$, they are defined to be independent if for any indices $i_1, i_2, ..., i_n$,
$P(\bigcap_{k = i_1}^{i_n} A_{k}) = \prod_{k = i_1}^{i_n} P(A_{k})$.
Thus, the "finite subcollections" refers to the $A_{i_1}, A_{i_2}, ..., A_{i_n}$
Assuming I understood that right, how that is relevant?
Comment: For Question 1, the answer is "Yes". As for Question 2, what you say is OK; and it is relevant because any finite subcollection of $A, A_1, A_2,\dots$ is contained in $A,A_1, \dots ,A_{n-1}$ for some $n$.
Comment: Yes, this is it.
Comment: You're welcome!
Comment: @Etienne If so, how exactly can we conclude such? I sort of get it intuitively, I think but am unable to express it precisely. My guess: If $A, A_1, A_2, ..., A_{n-1}$ are independent, then any finite subcollection of that is independent. If this indeed holds $\forall n \in \mathbb{N}$, then finite subcollections of $A, A_1, A_2, ...$ are also independent. Hence, $A, A_1, A_2, ...$ is independent ?
Comment: @Etienne Thanks!
Comment: @Etienne Thanks. I think I get it now. Please correct me if I am wrong: if $\forall n \in \mathbb{N}, A, A_1, A_2, ... A_{n-1}$ are have a certain property, I think it does not follow that $A, A_1, A_2, ...$ have that same property similar to just because $\sum_{k \geq n \geq 1} a_n < \infty \forall k \in \mathbb{N}$ does not mean $\sum_{n \geq 1} a_n < \infty$. However, if that property is independence, then from the definition of independence, which includes your statement "any finite subcollection of A,A1,A2,… is contained in A,A1,…,An−1 for some n.", we can conclude such?
Answer: For Question 1, the answer is "Yes". As for Question 2, what you say is OK; and it is relevant because any finite subcollection of A,A1,A2,… is contained in A,A1,…,An−1 for some n. –  Etienne May 24 at 17:01
@Etienne Thanks. I think I get it now. Please correct me if I am wrong: if ∀n∈N,A,A1,A2,...An−1 are have a certain property, I think it does not follow that A,A1,A2,... have that same property similar to just because ∑k≥n≥1an<∞∀k∈N does not mean ∑n≥1an<∞. However, if that property is independence, then from the definition of independence, which includes your statement "any finite subcollection of A,A1,A2,… is contained in A,A1,…,An−1 for some n.", we can conclude such? –  BCLC May 24 at 18:05
@Etienne If so, how exactly can we conclude such? I sort of get it intuitively, I think but am unable to express it precisely. My guess: If A,A1,A2,...,An−1 are independent, then any finite subcollection of that is independent. If this indeed holds ∀n∈N, then finite subcollections of A,A1,A2,... are also independent. Hence, A,A1,A2,... is independent ? –  BCLC May 24 at 18:13
Yes, this is it. –  Etienne May 24 at 21:05
@Etienne Thanks! –  BCLC just now   edit


CSS: Overflow:Hidden - Issues with hiding specific elements and showing others

Question: Good Evening StackOverflowers!
I am running into what seems to be a catch 22 with my code.
I am using the new CSS3 Ribbon Navigation with an image logo.
Here is my problem:
The Ribbon Navigation has overflow:hidden; in the css to hide the bottom parts of the ribbon. However, to get my logo in the middle of the navigation, I need to include it in the DIV. With overflow:hidden; on, it crops my logo (because it's overflow), and my navigation looks like this:
https://i.stack.imgur.com/JoXyJ.png
Not wanting to cut off my logo, I remove the overflow:hidden; but then I run into the problem of the ribbon tags showing under the nav, like so:
https://i.stack.imgur.com/bZE26.png
It seems there is no simple solution to this. As a new developer, I find I am starting to pull my hair out a little. Is there a workaround that will make the ribbon tails disappear, and allow my logo to show?
This is my HTML code:

        Home
    Portfolio

    About
    Contact

and my CSS code:
/*************************
* Left Ribbon Navigation *
**************************/
.ribbon {
    margin-top:6em;
}

.ribbon:after, .ribbon:before {
margin-top:0.5em;
content: "";
float:left;
border:1.5em solid #fff;
}

.ribbon:after {
border-right-color:transparent;
}

.ribbon:before {
border-left-color:transparent;
}

.ribbon span {
background:#fff;
display:inline-block;
line-height:3em;
padding:0 1em;
margin-top:0.5em;
position:relative;

-webkit-transition: background-color 0.2s, margin-top 0.2s;  /* Saf3.2+, Chrome */
-moz-transition: background-color 0.2s, margin-top 0.2s;  /* FF4+ */
-ms-transition: background-color 0.2s, margin-top 0.2s;  /* IE10 */
-o-transition: background-color 0.2s, margin-top 0.2s;  /* Opera 10.5+ */
transition: background-color 0.2s, margin-top 0.2s;
}

.ribbon a:hover span {
background:#D55E96;
margin-top:0;
}

.ribbon span:before {
content: "";
position:absolute;
top:3em;
left:0;
border-right:0.5em solid #9B8651;
border-bottom:0.5em solid #fff;
}

.ribbon span:after {
content: "";
position:absolute;
top:3em;
right:0;
border-left:0.5em solid #9B8651;
border-bottom:0.5em solid #fff;
}

.ribbon a:link, .ribbon a:visited {
color:#000;
text-decoration:none;
float:left;
height:3.5em;
}

/*********************
* Logo In Navigation *
**********************/
#logo {
margin-top:-5em;
z-index:3;
border:0;
}

Honestly, any advice or guidance would be truly appreciated. I have read many threads that have been posted on this, and they don't seem to be on the same wave. Thank you Overflowers for putting up with newbie's like me, and not ripping your hair out.
Best,
Laura
Comment: I have the site running live here: http://www.lmabee.com/Humber/Semester3/PHP/Portfolio/index.php
Answer: What I would do is set the anchors in the ribbon to overflow hidden except the one that holds the logo
.ribbon a:not(#logo-anchor){
    overflow:hidden;
}

Fiddle
If you target browser doesn't support :not then give all the anchors except the one with the logo a class.
.ribbon a.overflow-hidden{
    overflow:hidden;
}

Fiddle
Comment: Musa, you're amazing. **THANK YOU SO MUCH**.
After spending 4 hours playing with this, you made it work in a minute. I **truly** appreciate your help and patience. You've made my night.


Wireless Connection for Vortex and MicroFreak

Question: I'm looking for a simple way to connect a keytar (Alesis Vortex) to a synth (Arturia MicroFreak) through wireless midi.

My first hope is that since the Vortex comes with a USB-A dongle I can use a USB-AF to USB-BM adapter to plug directly into the MicroFreak.

This is the adapter shown below.

I don't know whether or not this would actually work because I'm not sure whether the MicroFreak will recognize information from the Dongle or not. It seems that some midi, especially wireless so far as I can tell, requires some sort of driver/setup to be installed on the receiving device. Should the synth already function with it?
If not, are there other wireless options buying a set of transmitters that would work with these two?
Answer: I'm going to take a swing at this without concrete evidence, just 'prior knowledge'.
I doubt it.
I don't know any of those devices, but apart from your 'frankenstein' adaptor [which I can't really fathom the purpose of], all your USB ports/plugs are client-side devices.
USB-A requires a client at one end & a host at the other. The way the plug spec is designed, if a client plugs straight into a host it has the 'flat' plug; if it needs a connecting cable, the cable has the 'flat' plug at the host end & a 'house' shape at the client end. This is so you just can't connect things up the wrong way.
USB-C, now is capable of this duality, which is why the plugs are the same at both ends. The connectivity of client/host is negotiated by the hardware as it's connected. USB-A cannot do that.
So, even your dongle needs to be connected to a host - a computer in other words. There's potential this will then work using the computer itself to enable the midi transmission - but for that I'd need to know more about each system. Presumably the Vortex is designed to be able to use that dongle to wirelessly connect to a computer - which then needs to be configured to pass wired MIDI through to your Arturia.


View for Entity Reference reverse, backwards forwards

Question: The need is to present in a landing page a view of all pages that do reference to this landing page. So, this view will search in other content type, to find in a reference field that contain same id.
Landing page content type have several nodes children.
Page content type have a Entity reference field_back_parent for a node parent
Content types
Landing page (1) parent,
  Page (2) child,
  Page (3) child,
I would like to this using UI in admin. So, no entityQuery in this opportunity.
Comment: You can also use a module instead of (or instead of only) core views: https://www.drupal.org/project/reverse_entity_reference > Reverse Entity Reference adds a computed reverse reference field to all referenced entities.
Comment: Nice comprehensive answer below  from Carlos (I haven't tried it myself yet though). What I have tried and found to work is: https://drupal.stackexchange.com/a/298084/1082 (albeit a programmatic solution, but if one is already doing coding for their project, then this other answer is simple solution that I have tried).
Answer:
No additional module need to be installed.
No coding needed. Just site building for Drupal 8.
First we need to check if our content types are ready.

Landing page content type, don't need any change.
Page content type need a field of type Entity reference.

Add field -> Add a new field = Reference Content

Then in Edit tab chose your kind of content type (parent)

After Save you will get...

Now go to admin/structure/views and + Add view

In this case we are going to check the option to create a block

In ADVANCED

Add Relationship for our field_back_parent in Page content type. This important to connect the two content types.

You need to tick Require this relationship.

In ADVANCED

Then Add Contextual filter for our current content type Landing Page. In this way, we will get our actual node id to be used in the view. So, now we can find only the pages that have same node id in field_back_parent.
So find by ID (Content)

Select the relationship name.
Check Provide default value -> Content ID from URL

Then you will get something like this:

In Relationship you must to have the word Content in the rightside
This is the result of our settings

If you click in Update preview you will corroborate that it doesn't display anything.
You must to add the node id from parent. In our case is the node 2 from Landing page.

Other way for reference https://mushtaqtahir.com/blog/4/drupal-8-reverse-entity-reference-in-view
I hope that this info help you.