问:
Java Socket read from socket in real time
I'm writing a java applet to simulate a ssh connection to ubuntu machine, I set up the connection, excute the command, and get back response, everything looks fine.
However, I had a small issue here, I want to receive server socket response in real time, so I can simulate on Applet in real time, but it seems I receive the response while the command excution is finished.
 For example, I have a test tcl file, I let the excution sleep 5 seconds between each statement, I should whoe the response on applet in every 5 seconds, instead of I get all of the response in the end.
Any thoughts?

```<code>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ssh_applet.java
 *
 * Created on 9-Dec-2010, 11:10:06 AM
 */

/**
 *
 * @author xzhang
 */
//import javax.swing.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import javax.swing.*;

public class ssh_applet extends javax.swing.JApplet{
    private String host_name = null;
    private String user_name = null;
    private String pass_word = null;
    private Connection app_conn;
    private Session app_session;
    /** Initializes the applet ssh_applet */
    public void init() {
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        ssh_input = new javax.swing.JPanel();
        connect = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        hostname = new javax.swing.JTextField();
        username = new javax.swing.JTextField();
        password = new javax.swing.JPasswordField();
        ssh_command = new javax.swing.JTextField();
        ssh_output_pannel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ssh_output = new javax.swing.JTextArea();
        clear_text = new javax.swing.JButton();

        connect.setText("Connect");
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        jLabel1.setText("Host Name");

        jLabel2.setText("User Name");

        jLabel3.setText("Password");

        hostname.setText("10.4.0.135");

        username.setText("xzhang");

        password.setText("Samboapple0827!");

        ssh_command.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ssh_commandActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_inputLayout = new javax.swing.GroupLayout(ssh_input);
        ssh_input.setLayout(ssh_inputLayout);
        ssh_inputLayout.setHorizontalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(username, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(password)
                            .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(connect))
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(60, Short.MAX_VALUE))
        );
        ssh_inputLayout.setVerticalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        ssh_output.setColumns(20);
        ssh_output.setEditable(false);
        ssh_output.setLineWrap(true);
        ssh_output.setRows(5);
        jScrollPane1.setViewportView(ssh_output);

        clear_text.setText("Clear");
        clear_text.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clear_textActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_output_pannelLayout = new javax.swing.GroupLayout(ssh_output_pannel);
        ssh_output_pannel.setLayout(ssh_output_pannelLayout);
        ssh_output_pannelLayout.setHorizontalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                    .addComponent(clear_text, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        ssh_output_pannelLayout.setVerticalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(clear_text)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ssh_input, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(ssh_output_pannel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(ssh_input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ssh_output_pannel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>

    private void connectActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
                        /*get host_name*/
                    host_name=hostname.getText();
                    user_name=username.getText();
                    pass_word=password.getText();
            /* Create a connection instance */
                      app_conn=new Connection(host_name);
                      try
            {
                              app_conn.connect();
            /* Authenticate.
             * If you get an IOException saying something like
             * "Authentication method password not supported by the server at this stage."
             * then please check the FAQ.
             */
            boolean isAuthenticated = app_conn.authenticateWithPassword(user_name, pass_word);

            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");

                         JOptionPane.showMessageDialog(null, "You are connected to host "+host_name, "Connection",
                                        JOptionPane.INFORMATION_MESSAGE);
            /* Create a session */
                        }
                        catch(IOException e)
                        {}

    }

    private void ssh_commandActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        String command=ssh_command.getText();
         try
        {

        app_session=app_conn.openSession();
        app_session.execCommand( command );
            InputStream stdout = new StreamGobbler( app_session.getStdout() );
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            String line ;
            while( (line= br.readLine()) != null )
            {
                ssh_output.append( line + "\n" );
                //line = br.readLine();
            }
            // DEBUG: dump the exit code
            System.out.println( "ExitCode: " + app_session.getExitStatus() );

            // Close the session
            app_session.close();
        }
         catch(Exception e)
         {}
    }

    private void clear_textActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        ssh_output.setText("");
    }

    // Variables declaration - do not modify
    private javax.swing.JButton clear_text;
    private javax.swing.JButton connect;
    private javax.swing.JTextField hostname;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField password;
    private javax.swing.JTextField ssh_command;
    private javax.swing.JPanel ssh_input;
    private javax.swing.JTextArea ssh_output;
    private javax.swing.JPanel ssh_output_pannel;
    private javax.swing.JTextField username;
    // End of variables declaration

}
</code>```

Here is my code,I'm using ganymed-ssh2 library, can't get where to flush

答: Without any code to look at, it'll be hard to help much.  But, it sounds like a buffer needs flushing.    </p>

Body:
I'm writing a java applet to simulate a ssh connection to ubuntu machine, I set up the connection, excute the command, and get back response, everything looks fine.
However, I had a small issue here, I want to receive server socket response in real time, so I can simulate on Applet in real time, but it seems I receive the response while the command excution is finished.
 For example, I have a test tcl file, I let the excution sleep 5 seconds between each statement, I should whoe the response on applet in every 5 seconds, instead of I get all of the response in the end.
Any thoughts?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ssh_applet.java
 *
 * Created on 9-Dec-2010, 11:10:06 AM
 */

/**
 *
 * @author xzhang
 */
//import javax.swing.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import javax.swing.*;

public class ssh_applet extends javax.swing.JApplet{
    private String host_name = null;
    private String user_name = null;
    private String pass_word = null;
    private Connection app_conn;
    private Session app_session;
    /** Initializes the applet ssh_applet */
    public void init() {
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        ssh_input = new javax.swing.JPanel();
        connect = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        hostname = new javax.swing.JTextField();
        username = new javax.swing.JTextField();
        password = new javax.swing.JPasswordField();
        ssh_command = new javax.swing.JTextField();
        ssh_output_pannel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ssh_output = new javax.swing.JTextArea();
        clear_text = new javax.swing.JButton();

        connect.setText("Connect");
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        jLabel1.setText("Host Name");

        jLabel2.setText("User Name");

        jLabel3.setText("Password");

        hostname.setText("10.4.0.135");

        username.setText("xzhang");

        password.setText("Samboapple0827!");

        ssh_command.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ssh_commandActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_inputLayout = new javax.swing.GroupLayout(ssh_input);
        ssh_input.setLayout(ssh_inputLayout);
        ssh_inputLayout.setHorizontalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(username, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(password)
                            .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(connect))
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(60, Short.MAX_VALUE))
        );
        ssh_inputLayout.setVerticalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        ssh_output.setColumns(20);
        ssh_output.setEditable(false);
        ssh_output.setLineWrap(true);
        ssh_output.setRows(5);
        jScrollPane1.setViewportView(ssh_output);

        clear_text.setText("Clear");
        clear_text.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clear_textActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_output_pannelLayout = new javax.swing.GroupLayout(ssh_output_pannel);
        ssh_output_pannel.setLayout(ssh_output_pannelLayout);
        ssh_output_pannelLayout.setHorizontalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                    .addComponent(clear_text, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        ssh_output_pannelLayout.setVerticalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(clear_text)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ssh_input, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(ssh_output_pannel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(ssh_input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ssh_output_pannel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>

    private void connectActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
                        /*get host_name*/
                    host_name=hostname.getText();
                    user_name=username.getText();
                    pass_word=password.getText();
            /* Create a connection instance */
                      app_conn=new Connection(host_name);
                      try
            {
                              app_conn.connect();
            /* Authenticate.
             * If you get an IOException saying something like
             * "Authentication method password not supported by the server at this stage."
             * then please check the FAQ.
             */
            boolean isAuthenticated = app_conn.authenticateWithPassword(user_name, pass_word);

            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");

                         JOptionPane.showMessageDialog(null, "You are connected to host "+host_name, "Connection",
                                        JOptionPane.INFORMATION_MESSAGE);
            /* Create a session */
                        }
                        catch(IOException e)
                        {}

    }

    private void ssh_commandActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        String command=ssh_command.getText();
         try
        {

        app_session=app_conn.openSession();
        app_session.execCommand( command );
            InputStream stdout = new StreamGobbler( app_session.getStdout() );
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            String line ;
            while( (line= br.readLine()) != null )
            {
                ssh_output.append( line + "\n" );
                //line = br.readLine();
            }
            // DEBUG: dump the exit code
            System.out.println( "ExitCode: " + app_session.getExitStatus() );

            // Close the session
            app_session.close();
        }
         catch(Exception e)
         {}
    }

    private void clear_textActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        ssh_output.setText("");
    }

    // Variables declaration - do not modify
    private javax.swing.JButton clear_text;
    private javax.swing.JButton connect;
    private javax.swing.JTextField hostname;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField password;
    private javax.swing.JTextField ssh_command;
    private javax.swing.JPanel ssh_input;
    private javax.swing.JTextArea ssh_output;
    private javax.swing.JPanel ssh_output_pannel;
    private javax.swing.JTextField username;
    // End of variables declaration

}

Here is my code,I'm using ganymed-ssh2 library, can't get where to flush


来源: stackexchange

问:
Issue with Image View and onClickListener
Im new to android programming and I am trying to build an app with imageviews that open up a new activity for each image view clicked with an image view of their own. so far i have made my main activity and put 4 image views on it all below each other with constraints. all works fine in the sense of when i open the app, the image views are laid out how they should be and i can click on imageview1, then 2, then 3, then 4 and then any of them. but if i open the app and try to click on imageview 2 first or imageview 3 for example, or imageview 4 then it doesn't work. I have to start at 1 and then go on to 2 and then 3 and 4 and then finally i can navigate freely. How can I fix this? I have posted my main activity java file below before. Any help would be appreciated. </p>

```<code>package com.ntq.ntqapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

public class MainActivity1 extends AppCompatActivity {
private ImageView ts;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main1);

    ts  = (ImageView)findViewById(R.id.ts1);
    ts.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent myIntent = new Intent(MainActivity1.this, imageView1.class);
            startActivity(myIntent);

     ts = (ImageView)findViewById(R.id.ts2);
     ts.setOnClickListener(new View.OnClickListener(){
         public void onClick(View view) {
             Intent myIntent = new Intent(MainActivity1.this, imageView2.class);
             startActivity(myIntent);

     ts = (ImageView)findViewById(R.id.ts3);
     ts.setOnClickListener(new View.OnClickListener(){
           public void onClick(View view) {
           Intent myIntent = new Intent(MainActivity1.this, imageView3.class);
           startActivity(myIntent);

     ts = (ImageView) findViewById(R.id.ts4);
     ts.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) {
              Intent myIntent = new Intent(view.getContext(), imageView4.class);
           startActivity(myIntent);

         }

         }
         );
        }}
         );
        }});}});}}
</code>```

答:
You have two problems.  First problem is your end brackets are in the wrong location.  The second problem is you are using the same variable.  Here is the code corrected:</p>

```<code>package com.ntq.ntqapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

public class MainActivity1 extends AppCompatActivity {
private ImageView ts1;
    private ImageView ts2;
    private ImageView ts3;
    private ImageView ts4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

        ts1 = (ImageView) findViewById(R.id.ts1);
        ts1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(MainActivity1.this,
                                             imageView1.class);
                startActivity(myIntent);
            }
        });

        ts2 = (ImageView) findViewById(R.id.ts2);
        ts2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(MainActivity1.this,
                                             imageView2.class);
                startActivity(myIntent);
            }
        });
        ts3 = (ImageView) findViewById(R.id.ts3);
        ts3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(MainActivity1.this,
                                             imageView3.class);
                startActivity(myIntent);
            }
        });
        ts4 = (ImageView) findViewById(R.id.ts4);
        ts4.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(),
                                             imageView4.class);
                startActivity(myIntent);
            }
        });
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im new to android programming and I am trying to build an app with imageviews that open up a new activity for each image view clicked with an image view of their own. so far i have made my main activity and put 4 image views on it all below each other with constraints. all works fine in the sense of when i open the app, the image views are laid out how they should be and i can click on imageview1, then 2, then 3, then 4 and then any of them. but if i open the app and try to click on imageview 2 first or imageview 3 for example, or imageview 4 then it doesn't work. I have to start at 1 and then go on to 2 and then 3 and 4 and then finally i can navigate freely. How can I fix this? I have posted my main activity java file below before. Any help would be appreciated.

package com.ntq.ntqapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

public class MainActivity1 extends AppCompatActivity {
private ImageView ts;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main1);

    ts  = (ImageView)findViewById(R.id.ts1);
    ts.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent myIntent = new Intent(MainActivity1.this, imageView1.class);
            startActivity(myIntent);

     ts = (ImageView)findViewById(R.id.ts2);
     ts.setOnClickListener(new View.OnClickListener(){
         public void onClick(View view) {
             Intent myIntent = new Intent(MainActivity1.this, imageView2.class);
             startActivity(myIntent);

     ts = (ImageView)findViewById(R.id.ts3);
     ts.setOnClickListener(new View.OnClickListener(){
           public void onClick(View view) {
           Intent myIntent = new Intent(MainActivity1.this, imageView3.class);
           startActivity(myIntent);

     ts = (ImageView) findViewById(R.id.ts4);
     ts.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) {
              Intent myIntent = new Intent(view.getContext(), imageView4.class);
           startActivity(myIntent);

         }

         }
         );
        }}
         );
        }});}});}}

Body:
You have two problems.  First problem is your end brackets are in the wrong location.  The second problem is you are using the same variable.  Here is the code corrected:

package com.ntq.ntqapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

public class MainActivity1 extends AppCompatActivity {
private ImageView ts1;
    private ImageView ts2;
    private ImageView ts3;
    private ImageView ts4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

        ts1 = (ImageView) findViewById(R.id.ts1);
        ts1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(MainActivity1.this,
                                             imageView1.class);
                startActivity(myIntent);
            }
        });

        ts2 = (ImageView) findViewById(R.id.ts2);
        ts2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(MainActivity1.this,
                                             imageView2.class);
                startActivity(myIntent);
            }
        });
        ts3 = (ImageView) findViewById(R.id.ts3);
        ts3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(MainActivity1.this,
                                             imageView3.class);
                startActivity(myIntent);
            }
        });
        ts4 = (ImageView) findViewById(R.id.ts4);
        ts4.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(),
                                             imageView4.class);
                startActivity(myIntent);
            }
        });
    }


问:
Changing the target of multiple shortcuts with PowerShell
I am writing a PowerShell script to search the C:\Users directory and change all lnk files that contain \server1 to \server2 but keep the rest of the link.

What I have so far will keep changing the LNK's target path to "Computer" and then disable you from being able to edit the LNK. Can anyone explain why this is doing this?

Code:

```<code>#Folder to search
$favourites_path = "C:\Users\"

#Backup C:\Users DISABLED by Default "
# Copy-Item $favourites_path "$favourites_path`1" -Recurse

$favourites = Get-ChildItem $favourites_path -Recurse -Filter *.lnk
foreach ($favourite in $favourites) {
  $shortcut = (New-Object -ComObject
  'WScript.Shell').CreateShortCut($favourite.FullName)
  $newpath=switch -Wildcard ($shortcut.TargetPath)
  {
    '"\\server1*"'           { $_ -replace '"\\server1"', '"\\server2"'}
  }
  $shortcut.TargetPath=$newpath
  $shortcut.Save()
}
</code>```

答:
Even though Explorer may show the Target: field of a shortcut (*.lnk file) enclosed in "...", accessing the equivalent field programmatically usually does not contain these enclosing double quotes.

-replace's 1st RHS operand is a regex (regular expression), in which \ is the escape character. Therefore, to replace a literal \, you must double it.

As written (leaving the double-quoting issue aside), your code would replace \\server1 with \\\server2.

Since you're recreating the shortcut file unconditionally, there is no need for a switch statement, given that -replace amounts to a no-op if the regex doesn't match anything.

Your switch statement has only 1 branch and no default branch, so that any target that doesn't start with \\server1 (leaving the double-quoting aside) is set to $null.

The following code addresses these issues:

```<code>#Folder to search
$favourites_path = "C:\Users"

Get-ChildItem $favourites_path -Recurse -Filter *.lnk | ForEach-Object {
   $shortcut = (New-Object -ComObject 'WScript.Shell').CreateShortCut($favourite.FullName)
   $shortcut.Target = $shortcut.Target -replace '^\\\\server1\\', '\\server2\'
   $shortcut.Save()
}
</code>```

Note how the regex is anchored with ^ to the start of the string, ensuring that literal \\server1\ only matches there.

An alternative to manually doubling the \ instances is to use [regex]::Escape(), which escapes any regex metacharacters in the input string to ensure its treatment as a literal:

```<code>$shortcut.Target = $shortcut.Target -replace ('^' + [regex]::Escape('\\server1\')), '\\server2\'
</code>```

In the replacement string (2nd RHS operand), \ instances do not need escaping; there, only $ instances would need escaping, because $-prefixed tokens refer to parts of what the regex matched (see this answer of mine for more).

Body:
I am writing a PowerShell script to search the C:\Users directory and change all lnk files that contain \server1 to \server2 but keep the rest of the link.

What I have so far will keep changing the LNK's target path to "Computer" and then disable you from being able to edit the LNK. Can anyone explain why this is doing this?

Code:

#Folder to search
$favourites_path = "C:\Users\"

#Backup C:\Users DISABLED by Default "
# Copy-Item $favourites_path "$favourites_path`1" -Recurse

$favourites = Get-ChildItem $favourites_path -Recurse -Filter *.lnk
foreach ($favourite in $favourites) {
  $shortcut = (New-Object -ComObject
  'WScript.Shell').CreateShortCut($favourite.FullName)
  $newpath=switch -Wildcard ($shortcut.TargetPath)
  {
    '"\\server1*"'           { $_ -replace '"\\server1"', '"\\server2"'}
  }
  $shortcut.TargetPath=$newpath
  $shortcut.Save()
}

Body:
Even though Explorer may show the Target: field of a shortcut (*.lnk file) enclosed in "...", accessing the equivalent field programmatically usually does not contain these enclosing double quotes.

-replace's 1st RHS operand is a regex (regular expression), in which \ is the escape character. Therefore, to replace a literal \, you must double it.

As written (leaving the double-quoting issue aside), your code would replace \\server1 with \\\server2.

Since you're recreating the shortcut file unconditionally, there is no need for a switch statement, given that -replace amounts to a no-op if the regex doesn't match anything.

Your switch statement has only 1 branch and no default branch, so that any target that doesn't start with \\server1 (leaving the double-quoting aside) is set to $null.

The following code addresses these issues:

#Folder to search
$favourites_path = "C:\Users"

Get-ChildItem $favourites_path -Recurse -Filter *.lnk | ForEach-Object {
   $shortcut = (New-Object -ComObject 'WScript.Shell').CreateShortCut($favourite.FullName)
   $shortcut.Target = $shortcut.Target -replace '^\\\\server1\\', '\\server2\'
   $shortcut.Save()
}

Note how the regex is anchored with ^ to the start of the string, ensuring that literal \\server1\ only matches there.

An alternative to manually doubling the \ instances is to use [regex]::Escape(), which escapes any regex metacharacters in the input string to ensure its treatment as a literal:

$shortcut.Target = $shortcut.Target -replace ('^' + [regex]::Escape('\\server1\')), '\\server2\'

In the replacement string (2nd RHS operand), \ instances do not need escaping; there, only $ instances would need escaping, because $-prefixed tokens refer to parts of what the regex matched (see this answer of mine for more).


问:
how can i block the user from downloading paid programs with out paying
I want to build e-commerce website with php and I will use omnipay library for paying. The problem is if the file in the url www.mywebsite.com/programs/paint.exe the user can write in his browser that url and the paid program will download..... I searched how to block user from downloading file like RewriteEngine but how can I let the file download if the user paid in this case?

答:
In addition to using hashed filenames as Peter mentioned, you can use php to serve the file after authentication.

Create an htaccess rewrite to send any requests for the file directly to a php script. In the php script, perform some authentication (I.E. have the user login, or have them use a secured link which sets session variables, etc.). Then, if the user authenticated successfully, use php to return the file using http headers.

```<code>header('Content-Type: application/x-msdownload'); // Set this to a .exe
header('Content-Disposition: attachment; filename="paint.exe"'); // Set the filename to download.
$downloadFile = file_get_contents('programs/hashedpaintexename.exe');
echo $downloadFile;
</code>```

NOTE: You will want to make sure that should you use hashed filenames you'll want your htaccess handle these hashed files as well.

Another option, if you've got the control over the server to do so, is you can have PHP load the file from outside of the website's directory instead of using a htaccess rewrite. For example, if your website directory is /var/www/mywebsite, have php load the executable from /whatever/path/you/want provided php has read-access to the directory.

Body:
In addition to using hashed filenames as Peter mentioned, you can use php to serve the file after authentication.

Create an htaccess rewrite to send any requests for the file directly to a php script. In the php script, perform some authentication (I.E. have the user login, or have them use a secured link which sets session variables, etc.). Then, if the user authenticated successfully, use php to return the file using http headers.

header('Content-Type: application/x-msdownload'); // Set this to a .exe
header('Content-Disposition: attachment; filename="paint.exe"'); // Set the filename to download.
$downloadFile = file_get_contents('programs/hashedpaintexename.exe');
echo $downloadFile;

NOTE: You will want to make sure that should you use hashed filenames you'll want your htaccess handle these hashed files as well.

Another option, if you've got the control over the server to do so, is you can have PHP load the file from outside of the website's directory instead of using a htaccess rewrite. For example, if your website directory is /var/www/mywebsite, have php load the executable from /whatever/path/you/want provided php has read-access to the directory.


问:
ASP.NET Core MVC runtime exception: "PrecompiledViews" not found
I've created a new empty ASP.NET Core web app (target framework is .NETCoreApp 1.1) in Visual Studio 2017. After adding the Microsoft.AspNetCore.Mvc 1.1.3 package I've got a runtime exception

```<code>{System.IO.FileNotFoundException: Could not load the specified file.
File name: '%my-project-name%.PrecompiledViews'
  at System.Runtime.Loader.AssemblyLoadContext.ResolveUsingEvent(AssemblyName assemblyName)}
</code>```

I've tried to create a new ASP.NET Core web app with demo controller/views but got the same issue. Downgrading to previous versions of Microsoft.AspNetCore.MVC package (1.1.1, 1.1.2) doesn't help too.

Does anyone encountered a similar problem? If so can you tell a solution?

Update: I've just enabled the "Enable Just My Code" option in VS Options => Debugging and this runtime exception is gone. But I'm still going for seeing variants of a solvation. Because of my solvation is looking like a workaround.

Update: Clearing of NuGet cache gives nothing too.

答: Seems that it is an only answer. "I've just enabled the "Enable Just My Code" option in VS Options => Debugging and this runtime exception is gone. But I'm still going for seeing variants of a solvation. Because of my solvation is looking like a workaround."</p>

Body:
I've created a new empty ASP.NET Core web app (target framework is .NETCoreApp 1.1) in Visual Studio 2017. After adding the Microsoft.AspNetCore.Mvc 1.1.3 package I've got a runtime exception

{System.IO.FileNotFoundException: Could not load the specified file.
File name: '%my-project-name%.PrecompiledViews'
  at System.Runtime.Loader.AssemblyLoadContext.ResolveUsingEvent(AssemblyName assemblyName)}

I've tried to create a new ASP.NET Core web app with demo controller/views but got the same issue. Downgrading to previous versions of Microsoft.AspNetCore.MVC package (1.1.1, 1.1.2) doesn't help too.

Does anyone encountered a similar problem? If so can you tell a solution?

Update: I've just enabled the "Enable Just My Code" option in VS Options => Debugging and this runtime exception is gone. But I'm still going for seeing variants of a solvation. Because of my solvation is looking like a workaround.

Update: Clearing of NuGet cache gives nothing too.


问:
Wordpress - Replace main image with thumbnail when clicked
I'm trying to accomplish the following task: I have a page that has several images, 1 is large and is the main image and then several images below which are sized smaller. What I want to do is that when a user clicks one of the smaller images, that image is loaded and replaces the main product image.

An example of one of my pages is: http://footybootsdb.com/adidas-x16-1/

I would like this to occur on multiple different pages so any code that can be implemented on several pages would be appreciated.

The page is configured using the 'Page Builder' plugin for Wordpress.

答: Install a light box plugin, when user clicks on the image, it will open the bigger version.</p>


问:
CSS cascading term
The cascading term in CSS is related to the fact
that having more style sources combine them together
or only to the fact to the conflict order resolution?

Thanks

答: Yes, the cascade defines the order conflicting styles will resolve.</p>

ContentLicense: CC BY-SA 2.5

Title: CSS cascading term


问:
Get all possible binary trees using Prolog?
I'm aware there are lots of questions about defining a binary tree to check whether something is a binary tree or not,but i could not find a thread that tackled this question in the "opposite direction".

Why does your definition of binary tree not return all possible binary trees when called as "es_arbol(X)"? Explain in detail and try to implement a different definition that does return all possible binary tree structures.

Ok,so basically i'm stuck in this part of an assignment.After defining my binary-tree-validating function i noticed that when called with no arguments it just returns trees that "grow" through their right nodes,or at least that's how i interpret the output of swi-prolog.What i am not getting is,assuming my definition is correct,Prolog should be able to construct them in both ways.If not,i would like if someone could point me in the right direction to work out a more general definition of a binary tree,or maybe explain why is it that my definition is not sufficient.

This is my definition:

```<code>es_arbol(nil).
es_arbol(arbol(_,I,D)) :- es_arbol(I), es_arbol(D).
</code>```

答:
The reason that your predicate generates an infinite number of trees along one branch is because you have more than one recursion, and like any language, Prolog will continue making the first recursive call it finds until it returns, which in this case, never will. So you always recurse on one leg of the tree. In other words, you have at least two variables in each tree (the left and right subtrees) that have an infinite number of possibilities.

Binary trees have an infinite number of recursive possibilities along two dimensions. You need a way to order the trees using a single-dimensional metric. One such metric could be the count of nodes in the tree. If you order your trees by node count, starting with node count 0, then for each node count, there are a finite number of trees to enumerate. Here is the general way this would work:

Nodes is a valid number of nodes

nil is a valid binary tree with 0 nodes

arbol(_, TL, TR) is a valid binary tree with N nodes if NL and NR2 add up to N-1 and TL is a valid binary tree of NL nodes, and TR is a valid binary tree of NR nodes. Since Prolog will find all solutions from a given point before backtracking prior to that point, it will search for all of the trees with the given number of nodes first before backtracking to a new valid number of nodes.

In Prolog, it looks like this.

```<code>:- use_module(library(clpfd)).

es_arbol(Tree) :-
    length(_, Nodes),
    es_arbol(Tree, Nodes).
</code>```

I'm using length/2 to "generate" Nodes values of 0, 1, 2, etc. es_arbol(Tree) will succeed with binary trees with successive node counts starting at 0. For a given node count, Nodes, it will find all the solutions to es_arbol(Tree, Nodes) before it finally fails and backtracks to length(_, Nodes) again which will succeed on the next value of Node.

```<code>es_arbol(nil, 0).
es_arbol(arbol(_,TreeL,TreeR), N) :-
    N #> 0,
    NL + NR #= N - 1,
    NL #>= 0, NR #>= 0,
    es_arbol(TreeL, NL),
    es_arbol(TreeR, NR).
</code>```

The base case is trivial. nil is the tree with 0 nodes. The recursive case says that arbol(_,L,R) is a binary tree with N nodes if N > 0, NL and NR are non-negative integers that add up to N, and TL and TR are binary trees with length NL and NR, respectively.

The results of running the above code are:

```<code>?- es_arbol(Tree).
Tree = nil ;
Tree = arbol(_G258, nil, nil) ;
Tree = arbol(_G17, nil, arbol(_G157, nil, nil)) ;
Tree = arbol(_G17, arbol(_G200, nil, nil), nil) ;
Tree = arbol(_G14, nil, arbol(_G154, nil, arbol(_G593, nil, nil))) ;
Tree = arbol(_G14, nil, arbol(_G154, arbol(_G603, nil, nil), nil)) ;
Tree = arbol(_G14, arbol(_G130, nil, nil), arbol(_G191, nil, nil)) ;
Tree = arbol(_G14, arbol(_G53, nil, arbol(_G193, nil, nil)), nil) ;
Tree = arbol(_G14, arbol(_G53, arbol(_G236, nil, nil), nil), nil) ;
Tree = arbol(_G14, nil, arbol(_G100, nil, arbol(_G214, nil, arbol(_G354, nil, nil)))) ;
Tree = arbol(_G14, nil, arbol(_G100, nil, arbol(_G214, arbol(_G397, nil, nil), nil))) ;
Tree = arbol(_G14, nil, arbol(_G100, arbol(_G216, nil, nil), arbol(_G277, nil, nil))) ;
Tree = arbol(_G14, nil, arbol(_G100, arbol(_G139, nil, arbol(_G279, nil, nil)), nil)) ;
Tree = arbol(_G14, nil, arbol(_G100, arbol(_G139, arbol(_G322, nil, nil), nil), nil)) ;
Tree = arbol(_G14, arbol(_G130, nil, nil), arbol(_G191, nil, arbol(_G664, nil, nil))) ;
Tree = arbol(_G14, arbol(_G130, nil, nil), arbol(_G191, arbol(_G674, nil, nil), nil)) ;
Tree = arbol(_G14, arbol(_G132, nil, arbol(_G272, nil, nil)), arbol(_G676, nil, nil)) .
...
</code>```

As @false has pointed out in the comments, the use of CLP(FD) is not the most efficient way in this case of applying a enumerative constraint. An alternative, more efficient means would be to use between/3:

```<code>es_arbol(nil, 0).
es_arbol(arbol(_,TreeL,TreeR), N) :-
    N > 0,
    N1 is N - 1,
    between(0, N1, NL),
    NR is N1 - NL,
    es_arbol(TreeL, NL),
    es_arbol(TreeR, NR).
</code>```

Body:
I'm aware there are lots of questions about defining a binary tree to check whether something is a binary tree or not,but i could not find a thread that tackled this question in the "opposite direction".

Why does your definition of binary tree not return all possible binary trees when called as "es_arbol(X)"? Explain in detail and try to implement a different definition that does return all possible binary tree structures.

Ok,so basically i'm stuck in this part of an assignment.After defining my binary-tree-validating function i noticed that when called with no arguments it just returns trees that "grow" through their right nodes,or at least that's how i interpret the output of swi-prolog.What i am not getting is,assuming my definition is correct,Prolog should be able to construct them in both ways.If not,i would like if someone could point me in the right direction to work out a more general definition of a binary tree,or maybe explain why is it that my definition is not sufficient.

This is my definition:

es_arbol(nil).
es_arbol(arbol(_,I,D)) :- es_arbol(I), es_arbol(D).

Body:
The reason that your predicate generates an infinite number of trees along one branch is because you have more than one recursion, and like any language, Prolog will continue making the first recursive call it finds until it returns, which in this case, never will. So you always recurse on one leg of the tree. In other words, you have at least two variables in each tree (the left and right subtrees) that have an infinite number of possibilities.

Binary trees have an infinite number of recursive possibilities along two dimensions. You need a way to order the trees using a single-dimensional metric. One such metric could be the count of nodes in the tree. If you order your trees by node count, starting with node count 0, then for each node count, there are a finite number of trees to enumerate. Here is the general way this would work:

Nodes is a valid number of nodes

nil is a valid binary tree with 0 nodes

arbol(_, TL, TR) is a valid binary tree with N nodes if NL and NR2 add up to N-1 and TL is a valid binary tree of NL nodes, and TR is a valid binary tree of NR nodes. Since Prolog will find all solutions from a given point before backtracking prior to that point, it will search for all of the trees with the given number of nodes first before backtracking to a new valid number of nodes.

In Prolog, it looks like this.

:- use_module(library(clpfd)).

es_arbol(Tree) :-
    length(_, Nodes),
    es_arbol(Tree, Nodes).

I'm using length/2 to "generate" Nodes values of 0, 1, 2, etc. es_arbol(Tree) will succeed with binary trees with successive node counts starting at 0. For a given node count, Nodes, it will find all the solutions to es_arbol(Tree, Nodes) before it finally fails and backtracks to length(_, Nodes) again which will succeed on the next value of Node.

es_arbol(nil, 0).
es_arbol(arbol(_,TreeL,TreeR), N) :-
    N #> 0,
    NL + NR #= N - 1,
    NL #>= 0, NR #>= 0,
    es_arbol(TreeL, NL),
    es_arbol(TreeR, NR).

The base case is trivial. nil is the tree with 0 nodes. The recursive case says that arbol(_,L,R) is a binary tree with N nodes if N > 0, NL and NR are non-negative integers that add up to N, and TL and TR are binary trees with length NL and NR, respectively.

The results of running the above code are:

?- es_arbol(Tree).
Tree = nil ;
Tree = arbol(_G258, nil, nil) ;
Tree = arbol(_G17, nil, arbol(_G157, nil, nil)) ;
Tree = arbol(_G17, arbol(_G200, nil, nil), nil) ;
Tree = arbol(_G14, nil, arbol(_G154, nil, arbol(_G593, nil, nil))) ;
Tree = arbol(_G14, nil, arbol(_G154, arbol(_G603, nil, nil), nil)) ;
Tree = arbol(_G14, arbol(_G130, nil, nil), arbol(_G191, nil, nil)) ;
Tree = arbol(_G14, arbol(_G53, nil, arbol(_G193, nil, nil)), nil) ;
Tree = arbol(_G14, arbol(_G53, arbol(_G236, nil, nil), nil), nil) ;
Tree = arbol(_G14, nil, arbol(_G100, nil, arbol(_G214, nil, arbol(_G354, nil, nil)))) ;
Tree = arbol(_G14, nil, arbol(_G100, nil, arbol(_G214, arbol(_G397, nil, nil), nil))) ;
Tree = arbol(_G14, nil, arbol(_G100, arbol(_G216, nil, nil), arbol(_G277, nil, nil))) ;
Tree = arbol(_G14, nil, arbol(_G100, arbol(_G139, nil, arbol(_G279, nil, nil)), nil)) ;
Tree = arbol(_G14, nil, arbol(_G100, arbol(_G139, arbol(_G322, nil, nil), nil), nil)) ;
Tree = arbol(_G14, arbol(_G130, nil, nil), arbol(_G191, nil, arbol(_G664, nil, nil))) ;
Tree = arbol(_G14, arbol(_G130, nil, nil), arbol(_G191, arbol(_G674, nil, nil), nil)) ;
Tree = arbol(_G14, arbol(_G132, nil, arbol(_G272, nil, nil)), arbol(_G676, nil, nil)) .
...

As @false has pointed out in the comments, the use of CLP(FD) is not the most efficient way in this case of applying a enumerative constraint. An alternative, more efficient means would be to use between/3:

es_arbol(nil, 0).
es_arbol(arbol(_,TreeL,TreeR), N) :-
    N > 0,
    N1 is N - 1,
    between(0, N1, NL),
    NR is N1 - NL,
    es_arbol(TreeL, NL),
    es_arbol(TreeR, NR).


问:
Having an issue with alignment of image/text
Trying to align the image vertically, and the text centered according to image. The whole card is about 300px * 200px. I want the image to be on the left hand side with text on the right.

```<code><div class="card center-block">
<div class="container">
    <div class="row">
        <div class="col-sm-6">
            <div class="photo">
                <img class="rounded" src="../im/3.jpg" width="130" height="130" style="min-height:50px;" />
                }
            </div>
        </div>
        <div class="col-sm-6" style="height: 250px; align-items:center">
            <div class="content">
                <h5 class="left-align"><strong>John Doe</strong></h5>
                <p class="left-align">Software Developer</p>
            </div>
        </div>
    </div>
</div>
</code>```

CSS:

```<code>.card {
min-width: 350px;
max-width: 350px;
min-height: 200px;
max-height: 200px;
}

.photo {
padding-top: 35px;
margin-right: 10px;
display:inline-block;
height: 100%;
float: left;
}

.content{
height: 100%;
}
</code>```

答:
You can add a class to the row and use flexbox positioning. align-items: center on the row that holds the 2 columns, then also use flex on the .content element and create a flex column with justify-content: center

.card {
min-width: 350px;
max-width: 350px;
min-height: 200px;
max-height: 200px;
}

.photo {
margin-right: 10px;
display:inline-block;
height: 100%;
float: left;
}

.special-row {
  display: flex;
  align-items: center;
}
.special-row .content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="card center-block">
<div class="container"><div class="row special-row">
  <div class="col-sm-6">
    <div class="photo">
      <img class="rounded" src="http://androidandme.com/wp-content/uploads/2015/12/Google-Now-on-Tap.jpg"width="130" height="130" style="min-height:50px;" />

            </div>
        </div>
        <div class="col-sm-6 details" style="height: 250px; align-items:center">
            <div class="content">
                <h5 class="left-align"><strong>John Doe</strong></h5>
                <p class="left-align">Software Developer</p>
            </div>
        </div>
    </div>
</div></code>```

Body:
Trying to align the image vertically, and the text centered according to image. The whole card is about 300px * 200px. I want the image to be on the left hand side with text on the right.

                }

John Doe

Software Developer

CSS:

.card {
min-width: 350px;
max-width: 350px;
min-height: 200px;
max-height: 200px;
}

.photo {
padding-top: 35px;
margin-right: 10px;
display:inline-block;
height: 100%;
float: left;
}

.content{
height: 100%;
}

Body:
You can add a class to the row and use flexbox positioning. align-items: center on the row that holds the 2 columns, then also use flex on the .content element and create a flex column with justify-content: center

.card {
min-width: 350px;
max-width: 350px;
min-height: 200px;
max-height: 200px;
}

.photo {
margin-right: 10px;
display:inline-block;
height: 100%;
float: left;
}

.special-row {
  display: flex;
  align-items: center;
}
.special-row .content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100%;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="card center-block">
<div class="container"><div class="row special-row">
  <div class="col-sm-6">
    <div class="photo">
      <img class="rounded" src="http://androidandme.com/wp-content/uploads/2015/12/Google-Now-on-Tap.jpg"width="130" height="130" style="min-height:50px;" />

            </div>
        </div>
        <div class="col-sm-6 details" style="height: 250px; align-items:center">
            <div class="content">
                <h5 class="left-align"><strong>John Doe</strong></h5>
                <p class="left-align">Software Developer</p>
            </div>
        </div>
    </div>
</div>


问:
Windows 10 UWP - stop background task if foreground app is running
How I can prevent background task from running if there are foreground app being executed? Using Universal Windows Platform for my app.

My background task is checking for new items on some site and sends a toast when there are new things available, but I wan't to prevent toast sending if user is running application right now.

I have tried to unregister task on my application launch and register it again when app is terminated, through, this is not fine solution for me -- when device shuts down for some reason (for example, battery was removed) my task will be not registered until app launched again.

Thanks.

答:
This is similar to this question: How to stop the background task if the app is starting?

The easiest way would be to convert your tasks to in-proc background tasks: https://learn.microsoft.com/en-us/windows/uwp/launch-resume/convert-out-of-process-background-task

With an in-proc task you can check whether the app is in the foreground or not directly from the background activity.

If you need to keep your background tasks as separate processes from your main app, then you can do one of the following:

Create a Mutex via a file.

Create an in-proc app service and attempt to communicate to it from your background task. Then you can return a value whether the app is in the foreground.

Use the App Local Settings Dictionary to hold a flag about whether the foreground app is running. This is the most fragile, as an app crash could cause the flag to not be reset correctly.


问:
Gunicorn can't find staticfiles after dockerization
I am using docker 17.05.0-cs edge on Ubuntu 17.04 Zesty. I have a gunicorn/Django app that I built here. It runs fine before being dockerized, but gunicorn can't see the staticfiles after docker build. Here is the Dockerfile:

```<code># Dockerfile

# FROM base image to build upon
FROM phusion/baseimage

# RUN install python and pip
RUN apt-get update
RUN apt-get install -y python python-pip python-dev

# ENV set environment directory tree
ENV PROJECT=mysite
ENV CONTAINER_HOME=/opt
ENV CONTAINER_PROJECT=$CONTAINER_HOME/$PROJECT

# move to project WORKDIR
WORKDIR $CONTAINER_PROJECT

# COPY project to container directory
COPY . $CONTAINER_PROJECT

# RUN pip and install requirements
RUN pip install -r requirements.txt

# COPY start.sh into known container location
COPY start.sh /start.sh

# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000

# CMD execute start.sh to start the server running.
CMD ["/start.sh"]
# done!
</code>```

The app runs and displays the page, funny, it even applies the css templates while saying it can't find bootstrap.css or bootstrap.js. It does not execute the script to toggle the menu though. The current templates are just an artifact of my initial build, the new ones won't even use bootstrap.js I'm pretty sure. It runs but the toggle doesn't work which I know is a feature of bootstrap.js. This is the out from sudo docker run -it -p 8000:8000 dockerized_site:

```<code>Starting Gunicorn.
[2017-06-07 00:38:56 +0000] [1] [INFO] Starting gunicorn 19.6.0
[2017-06-07 00:38:56 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2017-06-07 00:38:56 +0000] [1] [INFO] Using worker: sync
[2017-06-07 00:38:56 +0000] [9] [INFO] Booting worker with pid: 9
[2017-06-07 00:38:56 +0000] [10] [INFO] Booting worker with pid: 10
[2017-06-07 00:38:56 +0000] [11] [INFO] Booting worker with pid: 11
Not Found: /js/bootstrap.min.js
Not Found: /js/jquery.js
Not Found: /js/bootstrap.min.js
Not Found: /favicon.ico
</code>```

I appended the static file url pattern to urls.py, I am pretty sure this has to do with the container build, or perhaps settings.py. Perhaps I need to add an environment directory for the static files? Any help is, of course, appreciated.

答:
See https://docs.djangoproject.com/en/1.11/howto/static-files/deployment/
for static files deployment.

But you may want to serve your static files using a web server like Nginx or Apache. You should not use Gunicorn to serve static files particularly in production. Gunicorn is a WSGI server made for dynamic content.

Body:
I am using docker 17.05.0-cs edge on Ubuntu 17.04 Zesty. I have a gunicorn/Django app that I built here. It runs fine before being dockerized, but gunicorn can't see the staticfiles after docker build. Here is the Dockerfile:

# Dockerfile

# FROM base image to build upon
FROM phusion/baseimage

# RUN install python and pip
RUN apt-get update
RUN apt-get install -y python python-pip python-dev

# ENV set environment directory tree
ENV PROJECT=mysite
ENV CONTAINER_HOME=/opt
ENV CONTAINER_PROJECT=$CONTAINER_HOME/$PROJECT

# move to project WORKDIR
WORKDIR $CONTAINER_PROJECT

# COPY project to container directory
COPY . $CONTAINER_PROJECT

# RUN pip and install requirements
RUN pip install -r requirements.txt

# COPY start.sh into known container location
COPY start.sh /start.sh

# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000

# CMD execute start.sh to start the server running.
CMD ["/start.sh"]
# done!

The app runs and displays the page, funny, it even applies the css templates while saying it can't find bootstrap.css or bootstrap.js. It does not execute the script to toggle the menu though. The current templates are just an artifact of my initial build, the new ones won't even use bootstrap.js I'm pretty sure. It runs but the toggle doesn't work which I know is a feature of bootstrap.js. This is the out from sudo docker run -it -p 8000:8000 dockerized_site:

Starting Gunicorn.
[2017-06-07 00:38:56 +0000] [1] [INFO] Starting gunicorn 19.6.0
[2017-06-07 00:38:56 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2017-06-07 00:38:56 +0000] [1] [INFO] Using worker: sync
[2017-06-07 00:38:56 +0000] [9] [INFO] Booting worker with pid: 9
[2017-06-07 00:38:56 +0000] [10] [INFO] Booting worker with pid: 10
[2017-06-07 00:38:56 +0000] [11] [INFO] Booting worker with pid: 11
Not Found: /js/bootstrap.min.js
Not Found: /js/jquery.js
Not Found: /js/bootstrap.min.js
Not Found: /favicon.ico

I appended the static file url pattern to urls.py, I am pretty sure this has to do with the container build, or perhaps settings.py. Perhaps I need to add an environment directory for the static files? Any help is, of course, appreciated.


问:
Dynamic Dropdown, JQuery, Not Submitting form with Value
I have the following code, which creates a dynamic dropdown (Text Color) based on the selection of another dropdown (Background Color)

It works as expected, and populates the Text Color dropdown perfectly.

However, when I submit my form, the value for textC is blank everytime. If I create a simple select for Text Color, my form submits fine, and all variables are available on the next page via POST.

Any thoughts to why the the textC value is always blank with this code?

var black = [
{display: "Gray", value: "gray" },
{display: "Warm Red", value: "red" },
{display: "White", value: "white" }];

var white = [
{display: "Black", value: "black" },
{display: "Gray", value: "gray" },
{display: "Warm Red", value: "red" }];

var gray = [
{display: "Black", value: "black" },
{display: "Warm Red", value: "red" },
{display: "White", value: "white" }];

$("#parent_selection").change(function() {
    var parent = $(this).val(); //get option value from parent

    switch(parent){ //using switch compare selected option and populate child
          case 'black':
            list(black);
            break;
          case 'white':
            list(white);
            break;
          case 'gray':
            list(gray);
            break;
          default: //default child option is blank
            $("#textC").html('');
            break;
       }
});

//function to populate child select box
function list(array_list)
    {
    $("#textC").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options
        $("#textC").append("<option value=''+array_list[i].value+''>"+array_list[i].display+"</option>");
    });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><b>Background Color ?</b><br>
<select name="theme" id="parent_selection">
    <option value="">-- Please Select --</option>
    <option value="black">Black</option>
    <option value="white">White</option>
    <option value="gray">Gray</option>
</select>

<p><b>Text Color?</b><br>
<select name="textC" id="textC">
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script></code>```

答:
you can have other option by using select2 https://select2.github.io/

//set each item to id=value, text=display
var black = [
{text:"", id:""},
{text: "Gray", id: "gray" },
{text: "Warm Red", id: "red" },
{text: "White", id: "white" }];

//initialized select2 control.
$("#textC").select2({
    data: black,
    escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 1,
    placeholder: "choose item",
    selectOnClose: true,
    closeOnSelect: true
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select id="textC" name="textC" style="width:100%"></select></code>```

Body:
I have the following code, which creates a dynamic dropdown (Text Color) based on the selection of another dropdown (Background Color)

It works as expected, and populates the Text Color dropdown perfectly.

However, when I submit my form, the value for textC is blank everytime. If I create a simple select for Text Color, my form submits fine, and all variables are available on the next page via POST.

Any thoughts to why the the textC value is always blank with this code?

var black = [
{display: "Gray", value: "gray" },
{display: "Warm Red", value: "red" },
{display: "White", value: "white" }];

var white = [
{display: "Black", value: "black" },
{display: "Gray", value: "gray" },
{display: "Warm Red", value: "red" }];

var gray = [
{display: "Black", value: "black" },
{display: "Warm Red", value: "red" },
{display: "White", value: "white" }];

$("#parent_selection").change(function() {
    var parent = $(this).val(); //get option value from parent

    switch(parent){ //using switch compare selected option and populate child
          case 'black':
            list(black);
            break;
          case 'white':
            list(white);
            break;
          case 'gray':
            list(gray);
            break;
          default: //default child option is blank
            $("#textC").html('');
            break;
       }
});

//function to populate child select box
function list(array_list)
    {
    $("#textC").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options
        $("#textC").append("<option value=''+array_list[i].value+''>"+array_list[i].display+"</option>");
    });
}

Background Color ?

<select name="theme" id="parent_selection">
    <option value="">-- Please Select --</option>
    <option value="black">Black</option>
    <option value="white">White</option>
    <option value="gray">Gray</option>
</select>

Text Color?

<select name="textC" id="textC">
</select>

Body:
you can have other option by using select2 https://select2.github.io/

//set each item to id=value, text=display
var black = [
{text:"", id:""},
{text: "Gray", id: "gray" },
{text: "Warm Red", id: "red" },
{text: "White", id: "white" }];

//initialized select2 control.
$("#textC").select2({
    data: black,
    escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 1,
    placeholder: "choose item",
    selectOnClose: true,
    closeOnSelect: true
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select id="textC" name="textC" style="width:100%"></select>


问:
why do I need to poll message hub?
I am looking at the node-js express example for message-hub on blue mix and am puzzled for why I need to poll message hub from my server. I thought that the whole idea behind a pub-sub model is that I don't have to (over) load my server polling the message service to find out if new messages exist for me to consume. In the example provided, lines 211-213 in the app.js file contain the following: </p>

```<code>  // Set up an interval which will poll Message Hub for
  // new messages on the 'livechat' topic.
  produceInterval = setInterval(function() { ...},250);
</code>```

<p>This now has my server polling message hub every 250 mSec when what I want is to completely avoid a polling model and be notified by message hub when a message exists for me to consume. </p>

答:
in brief:
Kafka achieves its scalability by using a consumer-pull model, not a server-push.

in detail:
It's worth going through the Kafka documentation first.
In particular, your question is answered here
http://kafka.apache.org/documentation/#design_pull

HTH,
Edo

Title: why do I need to poll message hub?

Body:
I am looking at the node-js express example for message-hub on blue mix and am puzzled for why I need to poll message hub from my server. I thought that the whole idea behind a pub-sub model is that I don't have to (over) load my server polling the message service to find out if new messages exist for me to consume. In the example provided, lines 211-213 in the app.js file contain the following:

  // Set up an interval which will poll Message Hub for
  // new messages on the 'livechat' topic.
  produceInterval = setInterval(function() { ...},250);

This now has my server polling message hub every 250 mSec when what I want is to completely avoid a polling model and be notified by message hub when a message exists for me to consume.


问:
In terms of memory usage, what is the difference between these two arrays in javascript?
Here i have an array with elements whose indexes are separated by increments of 1.

```<code>let noGap = [];
noGap[0] = 0;
noGap[1] = 1;
</code>```

Here I have a different array whose indexes are separated by indexes of much greater than 1.

```<code>let gap = [];
gap[0] = 0;
gap[1000] = 1;
</code>```

What is the difference between how much memory each variable (noGap vs gap) uses? I can see from a Chrome console log that gap has wider length, because it logs  (1001) [0, undefined × 999, 1].

But if the gap variable indeed uses more space, I'm interested to know if it's proportionate to the number of undefined that exist in the array or if it's constant.

Pardon me if this is repeated question. This is the closest answer I found but I couldn't fully understand the answer.

答:
In V8, there is a big difference, the long and sparse array takes more memory. However, this is partially because 1000 is near the boundary after which V8 changes its internal representation of sparse arrays.  An even longer sparse array will likely take a similar amount of memory.

I only did a little evidence gathering with the Chrome dev tools (check out the memory tab), but here it is. Each row in this table is an array with an entry at index 0, and another at the end to define its length.

```<code>| sparse array length | retained size |
|---------------------|---------------|
| 1                   | 56            |
| 10                  | 304           |
| 1000                | 12,184        |
| 2000                | 184           |
| 3000                | 184           |
| 3000, less sparse   | 472           |
</code>```

Notice that memory scales with length up to 1000, but at 2000 it's much less, and it scales with number of set indices instead.

I'm assuming this is because V8 is switching from a complete representation of all the values from indices 0 to length (in the case of length 1000) to a hash map which only has entries for the indices which have been set.

I have no formal knowledge of how this actually works, FYI.

Body:
Here i have an array with elements whose indexes are separated by increments of 1.

let noGap = [];
noGap[0] = 0;
noGap[1] = 1;

Here I have a different array whose indexes are separated by indexes of much greater than 1.

let gap = [];
gap[0] = 0;
gap[1000] = 1;

What is the difference between how much memory each variable (noGap vs gap) uses? I can see from a Chrome console log that gap has wider length, because it logs  (1001) [0, undefined × 999, 1].

But if the gap variable indeed uses more space, I'm interested to know if it's proportionate to the number of undefined that exist in the array or if it's constant.

Pardon me if this is repeated question. This is the closest answer I found but I couldn't fully understand the answer.

Body:
In V8, there is a big difference, the long and sparse array takes more memory. However, this is partially because 1000 is near the boundary after which V8 changes its internal representation of sparse arrays.  An even longer sparse array will likely take a similar amount of memory.

I only did a little evidence gathering with the Chrome dev tools (check out the memory tab), but here it is. Each row in this table is an array with an entry at index 0, and another at the end to define its length.

| sparse array length | retained size |
|---------------------|---------------|
| 1                   | 56            |
| 10                  | 304           |
| 1000                | 12,184        |
| 2000                | 184           |
| 3000                | 184           |
| 3000, less sparse   | 472           |

Notice that memory scales with length up to 1000, but at 2000 it's much less, and it scales with number of set indices instead.

I'm assuming this is because V8 is switching from a complete representation of all the values from indices 0 to length (in the case of length 1000) to a hash map which only has entries for the indices which have been set.

I have no formal knowledge of how this actually works, FYI.


问:
Restlet DigestAuthenticator hashed local secret
I am trying to use a DigestAuthenticator to secure some parts of an API I am creating using Restlet. In all of the examples, the DigestAuthenticator expects to wrap a LocalVerifier that will return the local secret in plain text. Obviously, I do not want to store all of my users' passwords in plain text. How can I use HTTP Digest with Restlet while not providing the local secret in plain text?

I have written a LocalVerifier that uses the identifer to query a db and retrieve a sha1'd password, but it doesn't work unless my Verifier returns the password in plain text.

Any ideas?

答: So basically I hashed all the passwords on the server side in the database, and I hashed the password on the client side before it was hashed by http digest. Seems like a more secure solution to me anyway.</p>


问:
Reading/Writing files in Python and using Dictionary for WordCount list
i'm doing a python exercise that has to open and read the text file of Alice In Wonderland, populate a dictionary by making a wordcount, and then writing out that file. For the love of me, it won't work. Any tips??</p>

```<code>f = open('/Users/yongcho822/Desktop/alice.txt', 'r')

count = {}

for line in f:
    for word in line.split():

        # remove punctuation
        word = word.replace('_', '').replace('"', '').replace(',', '').replace('.', '')
        word = word.replace('-', '').replace('?', '').replace('!', '').replace("'", "")
        word = word.replace('(', '').replace(')', '').replace(':', '').replace('[', '')
        word = word.replace(']', '').replace(';', '')

        # ignore case
        word = word.lower()

        # ignore numbers
        if word.isalpha():
            if word in count:
                count[word] = count[word] + 1
            else:
                count[word] = 1

keys = list(count.keys())
keys.sort()

# save the word count analysis to a file
out = open('/Users/yongcho822/Desktop/alice.txt', 'w')

for word in keys:
    out.write(word + " " + str(count[word]))
    out.write('\n')

print("The word 'alice' appears " + str(count['alice']) + " times in the book.")
</code>```

答:
An easier way to have gotten rid of the punctuation would have been to do as follows,</p>

```<code>word=word.translate(None, string.punctuation)
</code>```

Body:
i'm doing a python exercise that has to open and read the text file of Alice In Wonderland, populate a dictionary by making a wordcount, and then writing out that file. For the love of me, it won't work. Any tips??

f = open('/Users/yongcho822/Desktop/alice.txt', 'r')

count = {}

for line in f:
    for word in line.split():

        # remove punctuation
        word = word.replace('_', '').replace('"', '').replace(',', '').replace('.', '')
        word = word.replace('-', '').replace('?', '').replace('!', '').replace("'", "")
        word = word.replace('(', '').replace(')', '').replace(':', '').replace('[', '')
        word = word.replace(']', '').replace(';', '')

        # ignore case
        word = word.lower()

        # ignore numbers
        if word.isalpha():
            if word in count:
                count[word] = count[word] + 1
            else:
                count[word] = 1

keys = list(count.keys())
keys.sort()

# save the word count analysis to a file
out = open('/Users/yongcho822/Desktop/alice.txt', 'w')

for word in keys:
    out.write(word + " " + str(count[word]))
    out.write('\n')

print("The word 'alice' appears " + str(count['alice']) + " times in the book.")

Body:
An easier way to have gotten rid of the punctuation would have been to do as follows,

word=word.translate(None, string.punctuation)


问:
C# Getting Runtime error : The process cannot access the file because it is being used by another process
Here is my code:
enter image description here

```<code>using System.IO;

namespace Randoms
{
    public class Program
    {
        public static void Main()
        {
            byte[] buffer = new byte[10240]; // buffer size
            string path = @"C:\Users\RAHUL\Desktop\file.txt";
            using (FileStream source = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                long fileLength = source.Length;
                using (FileStream dest = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    long totalBytes = 0;
                    int currentBlockSize = 0;

                    while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        totalBytes += currentBlockSize;
                        double percentage = (double)totalBytes * 100.0 / fileLength;
                        dest.Write(buffer, 0, currentBlockSize);
                    }
                }
            }
        }
    }
}
</code>```

Please check the image which shows the error which I am getting.I have tried to change the FileAccess multiple times but not getting any luck.

答:
This post explains how to both read and write to a file using a single stream:

How to both read and write a file in C#

Consider you may have the file still open from a previous erroneous run. Use a tool like Sysinternals Process Monitor or Unlocker to verify it isn't open by another instance.

How to use Process Monitor:

http://www.manuelmeyer.net/2013/09/tooltips-unlocking-files-with-sysinternals-process-monitor/

Body:
Here is my code:
enter image description here

using System.IO;

namespace Randoms
{
    public class Program
    {
        public static void Main()
        {
            byte[] buffer = new byte[10240]; // buffer size
            string path = @"C:\Users\RAHUL\Desktop\file.txt";
            using (FileStream source = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                long fileLength = source.Length;
                using (FileStream dest = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    long totalBytes = 0;
                    int currentBlockSize = 0;

                    while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        totalBytes += currentBlockSize;
                        double percentage = (double)totalBytes * 100.0 / fileLength;
                        dest.Write(buffer, 0, currentBlockSize);
                    }
                }
            }
        }
    }
}

Please check the image which shows the error which I am getting.I have tried to change the FileAccess multiple times but not getting any luck.


问:
Warning when trying to install angular2 dropdown multiselect library
I am trying to install angular 2 drop down multi select library by running the following command

npm install angular-2-dropdown-multiselect --save-dev

But I get this warning message "angular-2-dropdown-multiselect@1.3.2 requires a peer of tslib@^1.6.1 but none was installed."

I have no clue what this means. Any idea what am I missing here?

答:
You can read about tslib here:

https://github.com/Microsoft/tslib

In the README.md, you will find  npm install tslib@1.6.1. See if that resolves your issue.


问:
Simple search on Firebase database with swift 3
I'm new with Firebase and for the past two days, I've been trying to figure out how to perform a simple search on my db without any success.

And I want to perform search on all the channels children. For example I want to search if there is a channel named Klx0N4pxsBHGVkhYuY0. I try the

```<code>queryEqual(toValue: "Klx0N4pxsBHGVkhYuY0")
</code>```

but no luck.

Thank you so much in advance for your time and help.

答:
All you have to do is observe that path and if there is no data, the snapshot.value will be nil.

```<code>let ref = FIRDatabase.database().reference().child("channels").child("Klx0N4pxsBHGVkhYuY0")

ref.observeSingleEvent(of: .value, with: { (snapshot) in

    if let value = snapshot.value as? Dictionary<String,Any> {

        // There is data, so it exists

        print(value)

    } else {

        // There is no data, so it doesn't exist
    }
})
</code>```

Body:
I'm new with Firebase and for the past two days, I've been trying to figure out how to perform a simple search on my db without any success.

And I want to perform search on all the channels children. For example I want to search if there is a channel named Klx0N4pxsBHGVkhYuY0. I try the

queryEqual(toValue: "Klx0N4pxsBHGVkhYuY0")

but no luck.

Thank you so much in advance for your time and help.

Body:
All you have to do is observe that path and if there is no data, the snapshot.value will be nil.

let ref = FIRDatabase.database().reference().child("channels").child("Klx0N4pxsBHGVkhYuY0")

ref.observeSingleEvent(of: .value, with: { (snapshot) in

    if let value = snapshot.value as? Dictionary<String,Any> {

        // There is data, so it exists

        print(value)

    } else {

        // There is no data, so it doesn't exist
    }
})