问:
how to pass data from servlet to android application
```<code>I have a form in android upon submit im inserting it into database using servlet i have to show to user that form was inserted successfully. this is my application

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author trainee
 */
public class form extends HttpServlet {

String name;
String password;
Connection con = null;
Statement stmt = null;
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */

        /* TODO output your page here
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet form</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet form at " + request.getContextPath () + "</h1>");
        out.println("</body>");
        out.println("</html>");
        */

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

   try
  {

  }

  catch(Exception ex)
  {

  }
}

/**
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  try
  {
     Class.forName("com.mysql.jdbc.Driver");
     con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/Login","root", "");
     String nn=request.getParameter("name");
     String pass=request.getParameter("pass");
     String email=request.getParameter("email");
     stmt=con.createStatement();
     String query="insert into users values('"+nn+"','"+pass+"','"+email+"');";
     int v=stmt.executeUpdate(query);
     ArrayList<String> arr=new ArrayList<String>();
     arr.add("inserted");

System.out.println("sent response back...");

  }
  catch(Exception ex)
  {

  }

}

/**
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}
</code>```

this is my android application

```<code>package org.me.loginandroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.methods.HttpGet;

public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn1 = (Button) findViewById(R.id.submit);
        btn1.setOnClickListener(listener_login);
    }
    private OnClickListener listener_login = new OnClickListener() {

        boolean check = false;

        public void onClick(View v) {
            EditText emailText = (EditText) findViewById(R.id.email);
            EditText passText = (EditText) findViewById(R.id.password);
            EditText nameText = (EditText) findViewById(R.id.uname);

            String name = nameText.getText().toString();
            String email = (emailText.getText().toString());
            String pass = (passText.getText().toString());

            String result = "";
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("name", name));
            nameValuePairs.add(new BasicNameValuePair("pass", pass));
            nameValuePairs.add(new BasicNameValuePair("email", email));

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2:8084/Login/form");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                TextView lbl = (TextView) findViewById(R.id.lbl);
                lbl.setText(result);
            } catch (Exception e) {
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText("Error parsing data " + e.toString());
                System.out.println("Error parsing data " + e.toString());
            }
            //parse json data
            try {
                boolean check=false;
               ArrayList<String> arrays=new ArrayList<String>();
               for(int i=0;i<arrays.size();i++)
               {
                   if(arrays.get(i).equals("Inserted"))
                   {
                        check=true;
                   }
                   else
                   {
                   }
               }
               if(check)
               {
                   Intent myintent = new Intent(MainActivity.this, welcome.class);
                   startActivity(myintent);
               }
               else
               {
                    TextView tv = (TextView) findViewById(R.id.err);
                    tv.setText("Data was not inserted properly");
               }

            } catch (Exception e) {
                //setContentView(R.layout.notify);
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText(e.toString());
                System.out.println("log_tag" + "Error parsing data ");

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

答: You need to make a URLConnection to your servlet page and do it. Example for it: How to download file/image from url to your device</p>

Body:
I have a form in android upon submit im inserting it into database using servlet i have to show to user that form was inserted successfully. this is my application

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author trainee
 */
public class form extends HttpServlet {

String name;
String password;
Connection con = null;
Statement stmt = null;
/**
 * Processes requests for both HTTP GET and POST methods.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */

        /* TODO output your page here
        out.println("");
        out.println("");
        out.println("<title>Servlet form</title>");
        out.println("");
        out.println("");
        out.println("
Servlet form at " + request.getContextPath () + "
");
        out.println("");
        out.println("");
        */

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

   try
  {

  }

  catch(Exception ex)
  {

  }
}

/**
 * Handles the HTTP POST method.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
  try
  {
     Class.forName("com.mysql.jdbc.Driver");
     con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/Login","root", "");
     String nn=request.getParameter("name");
     String pass=request.getParameter("pass");
     String email=request.getParameter("email");
     stmt=con.createStatement();
     String query="insert into users values('"+nn+"','"+pass+"','"+email+"');";
     int v=stmt.executeUpdate(query);
     ArrayList<String> arr=new ArrayList<String>();
     arr.add("inserted");

System.out.println("sent response back...");

  }
  catch(Exception ex)
  {

  }

}

/**
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

this is my android application

package org.me.loginandroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.apache.http.client.methods.HttpGet;

public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn1 = (Button) findViewById(R.id.submit);
        btn1.setOnClickListener(listener_login);
    }
    private OnClickListener listener_login = new OnClickListener() {

        boolean check = false;

        public void onClick(View v) {
            EditText emailText = (EditText) findViewById(R.id.email);
            EditText passText = (EditText) findViewById(R.id.password);
            EditText nameText = (EditText) findViewById(R.id.uname);

            String name = nameText.getText().toString();
            String email = (emailText.getText().toString());
            String pass = (passText.getText().toString());

            String result = "";
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("name", name));
            nameValuePairs.add(new BasicNameValuePair("pass", pass));
            nameValuePairs.add(new BasicNameValuePair("email", email));

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2:8084/Login/form");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                TextView lbl = (TextView) findViewById(R.id.lbl);
                lbl.setText(result);
            } catch (Exception e) {
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText("Error parsing data " + e.toString());
                System.out.println("Error parsing data " + e.toString());
            }
            //parse json data
            try {
                boolean check=false;
               ArrayList<String> arrays=new ArrayList<String>();
               for(int i=0;i<arrays.size();i++)
               {
                   if(arrays.get(i).equals("Inserted"))
                   {
                        check=true;
                   }
                   else
                   {
                   }
               }
               if(check)
               {
                   Intent myintent = new Intent(MainActivity.this, welcome.class);
                   startActivity(myintent);
               }
               else
               {
                    TextView tv = (TextView) findViewById(R.id.err);
                    tv.setText("Data was not inserted properly");
               }

            } catch (Exception e) {
                //setContentView(R.layout.notify);
                TextView tv = (TextView) findViewById(R.id.err);
                tv.setText(e.toString());
                System.out.println("log_tag" + "Error parsing data ");

            }
        }
    };
}


来源: stackexchange

问:
Menu loop in 2 different methods Java program
I am working on a menu program and I want to be able to enter as many selections as I want without the menu looping as well after the input, currently it either infinite-loops, or the program ends after one input, being unable to perform a different selection after the first. Also I want to have a case where I exit the menu if I press 0.</p>

```<code>public void showMenu() {

    System.out.println("Welcome!");
    System.out.println("Select an option:\n" +
            "1. Adunare\n" +
            "2. Scadere\n" +
            "3. Inmultire\n" +
            "4. Impartire\n" +
            "5. Comparare numere\n" +
            "6. List To Hundred\n" +
            "7. Nr to list\n" +
            "8. Contains\n" +
            "9. Even numbers\n" +
            "10. List of Strings\n" +
            "11. Second largest number\n" +
            "12. Second lowest number\n" +
            "13. Number \n" +
            "14. Number 2 \n" +
            "15. Number 3\n" +
            "16. String\n" +
            "17. String 2\n" +
            "18. Amount of snow\n" +
            "19. Eligible to vote test\n" +
            "20. Odd or even\n" +
            "21. Dog\n" +
            "22. Cat\n" +
            "23. Elev");

}

public void runProgram() {
    showMenu();
    int numberFromUser = citire.readNumbers();

    do {
        switch (numberFromUser) {
            case 1:
                addition();
                break;
            case 2:
                subtraction();
                break;
            case 3:
                multiply();
                break;
            case 4:
                divide();
                break;
            case 5:
                comparareNumere();
                break;
            case 6:
                listhundred();
                break;
            case 7:
                setnumbertolist();
                break;
            case 8:
                contain();
                break;
            case 9:
                limit();
                break;
            case 10:
                list();
                break;
            case 11:
                secmax();
                break;
            case 12:
                secmin();
                break;
            case 13:
                nr();
                break;
            case 14:
                nr2();
                break;
            case 15:
                nr3();
                break;
            case 16:
                string();
                break;
            case 17:
                string2();
                break;
            case 18:
                weather();
                break;
            case 19:
                eligible();
                break;
            case 20:
                oddoreven();
                break;
            case 21:
                dog();
                break;
            case 22:
                cat();
                break;
            case 23:
                elev();
                break;
            default:
                break;

        }
    } while (numberFromUser != 0);
}
</code>```

答:
Add

numberFromUser = citire.readNumbers();

into the loop to take numbers in the loop.

```<code>public void runProgram() {
   showMenu();
   int numberFromUser;

   do {
       numberFromUser = citire.readNumbers();
       switch (numberFromUser) {
        case 1:
            addition();
            break;
        case 2:
            subtraction();
            break;
        case 3:
            multiply();
            break;
        case 4:
            divide();
            break;
        case 5:
            comparareNumere();
            break;
        case 6:
            listhundred();
            break;
        case 7:
            setnumbertolist();
            break;
        case 8:
            contain();
            break;
        case 9:
            limit();
            break;
        case 10:
            list();
            break;
        case 11:
            secmax();
            break;
        case 12:
            secmin();
            break;
        case 13:
            nr();
            break;
        case 14:
            nr2();
            break;
        case 15:
            nr3();
            break;
        case 16:
            string();
            break;
        case 17:
            string2();
            break;
        case 18:
            weather();
            break;
        case 19:
            eligible();
            break;
        case 20:
            oddoreven();
            break;
        case 21:
            dog();
            break;
        case 22:
            cat();
            break;
        case 23:
            elev();
            break;
        default:
            break;

       }
   } while (numberFromUser != 0);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on a menu program and I want to be able to enter as many selections as I want without the menu looping as well after the input, currently it either infinite-loops, or the program ends after one input, being unable to perform a different selection after the first. Also I want to have a case where I exit the menu if I press 0.

public void showMenu() {

    System.out.println("Welcome!");
    System.out.println("Select an option:\n" +
            "1. Adunare\n" +
            "2. Scadere\n" +
            "3. Inmultire\n" +
            "4. Impartire\n" +
            "5. Comparare numere\n" +
            "6. List To Hundred\n" +
            "7. Nr to list\n" +
            "8. Contains\n" +
            "9. Even numbers\n" +
            "10. List of Strings\n" +
            "11. Second largest number\n" +
            "12. Second lowest number\n" +
            "13. Number \n" +
            "14. Number 2 \n" +
            "15. Number 3\n" +
            "16. String\n" +
            "17. String 2\n" +
            "18. Amount of snow\n" +
            "19. Eligible to vote test\n" +
            "20. Odd or even\n" +
            "21. Dog\n" +
            "22. Cat\n" +
            "23. Elev");

}

public void runProgram() {
    showMenu();
    int numberFromUser = citire.readNumbers();

    do {
        switch (numberFromUser) {
            case 1:
                addition();
                break;
            case 2:
                subtraction();
                break;
            case 3:
                multiply();
                break;
            case 4:
                divide();
                break;
            case 5:
                comparareNumere();
                break;
            case 6:
                listhundred();
                break;
            case 7:
                setnumbertolist();
                break;
            case 8:
                contain();
                break;
            case 9:
                limit();
                break;
            case 10:
                list();
                break;
            case 11:
                secmax();
                break;
            case 12:
                secmin();
                break;
            case 13:
                nr();
                break;
            case 14:
                nr2();
                break;
            case 15:
                nr3();
                break;
            case 16:
                string();
                break;
            case 17:
                string2();
                break;
            case 18:
                weather();
                break;
            case 19:
                eligible();
                break;
            case 20:
                oddoreven();
                break;
            case 21:
                dog();
                break;
            case 22:
                cat();
                break;
            case 23:
                elev();
                break;
            default:
                break;

        }
    } while (numberFromUser != 0);
}

Body:
Add

numberFromUser = citire.readNumbers();

into the loop to take numbers in the loop.

public void runProgram() {
   showMenu();
   int numberFromUser;

   do {
       numberFromUser = citire.readNumbers();
       switch (numberFromUser) {
        case 1:
            addition();
            break;
        case 2:
            subtraction();
            break;
        case 3:
            multiply();
            break;
        case 4:
            divide();
            break;
        case 5:
            comparareNumere();
            break;
        case 6:
            listhundred();
            break;
        case 7:
            setnumbertolist();
            break;
        case 8:
            contain();
            break;
        case 9:
            limit();
            break;
        case 10:
            list();
            break;
        case 11:
            secmax();
            break;
        case 12:
            secmin();
            break;
        case 13:
            nr();
            break;
        case 14:
            nr2();
            break;
        case 15:
            nr3();
            break;
        case 16:
            string();
            break;
        case 17:
            string2();
            break;
        case 18:
            weather();
            break;
        case 19:
            eligible();
            break;
        case 20:
            oddoreven();
            break;
        case 21:
            dog();
            break;
        case 22:
            cat();
            break;
        case 23:
            elev();
            break;
        default:
            break;

       }
   } while (numberFromUser != 0);
}


问:
JavaScript to detect what checkboxes and checked and perform action
I have a jsp page with a checkbox declared like so

```<code><form:checkbox path="affProgramSessionList[${status.index}].programSessionDetailId" id="checkbox_${session.id}" data-id="${session.id}" value="${session.id}" />
</code>```

it is contained within a for loop and basically a checkbox is displayed for each session.  That all works fine and I have no issues.

currently when a check box is checked this function is ran

```<code>$("input[id*='checkbox_']").each(function () {
    $(this).click(function(){
        var dataid = $(this).attr("data-id");
        var divId = "fullAttendence_" + dataid;
        var divIdAttendee = "attendeeType_" + dataid;

        $('#' + divId).toggle(this.checked);
        $('#' + divIdAttendee).toggle(this.checked);
    });

});
</code>```

This then results in some other checkboxes being checked and some divs that were hidden being shown.

I am now adding in functionality for if someone had checked some check boxes and saved and comes back to the page then those check boxes will be checked.

I have that part working but I can't get the function to run properly.

I have the following

```<code>if ($("input[id*='checkbox_']").is(':checked')) {

    var dataid = $(this).attr("data-id");
    var divId = "fullAttendence_" + dataid;
    var divIdAttendee = "attendeeType_" + dataid;

    $('#' + divId).toggle(this.checked);
    $('#' + divIdAttendee).toggle(this.checked);
}
</code>```

This function DOES get called as I tested it with a console.log.

the issue is that

```<code>var dataid = $(this).attr("data-id");
</code>```

comes back as

```<code>undefined
</code>```

Now my assumption right now is just that my new function to check for checked boxes and the other function that gets call are not working quite the same and my function doesn't know which check box was checked just that at least one was?

any help is really appreciated.

答:
```<code>if ($("input[id*='checkbox_']").is(':checked')) {
</code>```

<p>... will filter out the first checked input and operate on that. If you want to iterate on all checkboxes, use this construct:</p>

```<code>$("input[id*='checkbox_']").each(function() {
    if ($(this).is(':checked')) {
        // do something
    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a jsp page with a checkbox declared like so

<form:checkbox path="affProgramSessionList[${status.index}].programSessionDetailId" id="checkbox_${session.id}" data-id="${session.id}" value="${session.id}" />

it is contained within a for loop and basically a checkbox is displayed for each session.  That all works fine and I have no issues.

currently when a check box is checked this function is ran

$("input[id*='checkbox_']").each(function () {
    $(this).click(function(){
        var dataid = $(this).attr("data-id");
        var divId = "fullAttendence_" + dataid;
        var divIdAttendee = "attendeeType_" + dataid;

        $('#' + divId).toggle(this.checked);
        $('#' + divIdAttendee).toggle(this.checked);
    });

});

This then results in some other checkboxes being checked and some divs that were hidden being shown.

I am now adding in functionality for if someone had checked some check boxes and saved and comes back to the page then those check boxes will be checked.

I have that part working but I can't get the function to run properly.

I have the following

if ($("input[id*='checkbox_']").is(':checked')) {

    var dataid = $(this).attr("data-id");
    var divId = "fullAttendence_" + dataid;
    var divIdAttendee = "attendeeType_" + dataid;

    $('#' + divId).toggle(this.checked);
    $('#' + divIdAttendee).toggle(this.checked);
}

This function DOES get called as I tested it with a console.log.

the issue is that

var dataid = $(this).attr("data-id");

comes back as

undefined

Now my assumption right now is just that my new function to check for checked boxes and the other function that gets call are not working quite the same and my function doesn't know which check box was checked just that at least one was?

any help is really appreciated.

Body:
if ($("input[id*='checkbox_']").is(':checked')) {

... will filter out the first checked input and operate on that. If you want to iterate on all checkboxes, use this construct:

$("input[id*='checkbox_']").each(function() {
    if ($(this).is(':checked')) {
        // do something
    }
});


问:
Encoding error when installing Keras on Windows 10
I am trying to install Keras on Windows 10. I installed Visual Studio 2015 Community Edition, CUDA 8.0, its second patch, cuDNN 6.0, PyCharm, Anaconda, Python 3.6.3 in this specific order.
I installed tensorflow-gpu.
I added \path-to\Python\Python36\bin to the PATH environment variable, and for the NVIDIA folders. Tensorflow works from the shell but not from the Anaconda prompt.
When I try to install Keras by using pip install keras from PowerShell I get the following error.

```<code>    PS C:\Users\myusr> pip install keras
    Collecting keras
      Downloading Keras-2.1.1-py2.py3-none-any.whl (302kB)
        100% |████████████████████████████████| 307kB 553kB/s
    Collecting pyyaml (from keras)
      Downloading PyYAML-3.12.tar.gz (253kB)
        100% |████████████████████████████████| 256kB 553kB/s
    Collecting scipy>=0.14 (from keras)
      Downloading scipy-1.0.0-cp36-none-win_amd64.whl (30.8MB)
        100% |████████████████████████████████| 30.8MB 41kB/s
    Requirement already satisfied: six>=1.9.0 in c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages (from keras)
    Requirement already satisfied: numpy>=1.9.1 in c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages (from keras)
    Building wheels for collected packages: pyyaml
      Running setup.py bdist_wheel for pyyaml ... error
      Failed building wheel for pyyaml
      Running setup.py clean for pyyaml
    Failed to build pyyaml
    Installing collected packages: pyyaml, scipy, keras
      Running setup.py install for pyyaml ... error
    Exception:
    Traceback (most recent call last):
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str
        return s.decode(sys.__stdout__.encoding)
            UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8a in position 76: invalid start byte

            During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main
        status = self.run(options, args)
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 342, in run
        prefix=options.prefix_path,
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 784, in install
        **kwargs
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 878, in install
        spinner=spinner,
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess
        line = console_to_str(proc.stdout.readline())
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 75, in console_to_str
        return s.decode('utf_8')
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8a in position 76: invalid start byte
</code>```

What can I do?

答:
This is coming from pyyaml module. Based on the fact that from version 3.6 Python for Windows is using UTF-8 for it's console IO it leads to errors. In case of running a subprocess, it thinks that the output from subprocess will be also UTF-8... which is not the case.

There are 3 ways to fix this:

Use Python < 3.6 (e.g. 3.5.2)

Use locale.getpreferredencoding(False) for the encoding

Run a command from cmd/powershell: chcp . It will show the system default code, for example 936. Open Lib/site-package/pip/compat/init.py
and around line 76 change

```<code>return s.decode('utf_8')
</code>```

to

```<code>return s.decode('cp936')
</code>```

Body:
I am trying to install Keras on Windows 10. I installed Visual Studio 2015 Community Edition, CUDA 8.0, its second patch, cuDNN 6.0, PyCharm, Anaconda, Python 3.6.3 in this specific order.
I installed tensorflow-gpu.
I added \path-to\Python\Python36\bin to the PATH environment variable, and for the NVIDIA folders. Tensorflow works from the shell but not from the Anaconda prompt.
When I try to install Keras by using pip install keras from PowerShell I get the following error.

    PS C:\Users\myusr> pip install keras
    Collecting keras
      Downloading Keras-2.1.1-py2.py3-none-any.whl (302kB)
        100% |████████████████████████████████| 307kB 553kB/s
    Collecting pyyaml (from keras)
      Downloading PyYAML-3.12.tar.gz (253kB)
        100% |████████████████████████████████| 256kB 553kB/s
    Collecting scipy>=0.14 (from keras)
      Downloading scipy-1.0.0-cp36-none-win_amd64.whl (30.8MB)
        100% |████████████████████████████████| 30.8MB 41kB/s
    Requirement already satisfied: six>=1.9.0 in c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages (from keras)
    Requirement already satisfied: numpy>=1.9.1 in c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages (from keras)
    Building wheels for collected packages: pyyaml
      Running setup.py bdist_wheel for pyyaml ... error
      Failed building wheel for pyyaml
      Running setup.py clean for pyyaml
    Failed to build pyyaml
    Installing collected packages: pyyaml, scipy, keras
      Running setup.py install for pyyaml ... error
    Exception:
    Traceback (most recent call last):
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str
        return s.decode(sys.__stdout__.encoding)
            UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8a in position 76: invalid start byte

            During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\basecommand.py", line 215, in main
        status = self.run(options, args)
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\commands\install.py", line 342, in run
        prefix=options.prefix_path,
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_set.py", line 784, in install
        **kwargs
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\req\req_install.py", line 878, in install
        spinner=spinner,
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess
        line = console_to_str(proc.stdout.readline())
      File "c:\users\myusr\appdata\local\programs\python\python36\lib\site-packages\pip\compat\__init__.py", line 75, in console_to_str
        return s.decode('utf_8')
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8a in position 76: invalid start byte

What can I do?

Body:
This is coming from pyyaml module. Based on the fact that from version 3.6 Python for Windows is using UTF-8 for it's console IO it leads to errors. In case of running a subprocess, it thinks that the output from subprocess will be also UTF-8... which is not the case.

There are 3 ways to fix this:

Use Python < 3.6 (e.g. 3.5.2)

Use locale.getpreferredencoding(False) for the encoding

Run a command from cmd/powershell: chcp . It will show the system default code, for example 936. Open Lib/site-package/pip/compat/init.py
and around line 76 change

return s.decode('utf_8')

to

return s.decode('cp936')


问:
Creating summary statistic table from subsets of data in R
I have a table that looks something like this:

```<code>Time     Carbon       OD
 0       Sucrose      1.13
 0       Citric acid  1.54
24       Histidine    2.1
24       Glutamine    1.7
48       Maleic acid  2.1
48       Furm acid    3.1
72       Tryptophan   2.3
72       Serine       1.2
72       etc          etc
</code>```

It has four time points, and 9 different carbons that can be split into three groups (organic acids, sugars, amino acids).

EDIT - if its helpful, the OD was measured for each carbon at each time point 8 times. Previously I used this code to create summary statistics for the entire thing:

```<code>summary <- aggregate(dataset2$OD,
                   by = list(Time = dataset2$Time, Carbon = dataset2$Carbon),
                   FUN = function(x) c(mean = mean(x), sd = sd(x),
                                       n = length(x)))
summary <- do.call(data.frame, dataset2)
summary$se <- dataset2$x.sd / sqrt(dataset2$x.n)
</code>```

But now I would like to generate the same summary statistics for the means of each of the three groups, if possible, so I would get something like this:

```<code>Time    Group    OD    SD    n    SE
  0     Group 1
 24     Group 1
 48     Group 1
 72     Group 1
  0     Group 2
</code>```

I'm not quite sure how to specify this in my code?

答:
Using dplyr:

```<code>dataset2 %>%
  group_by(Time, Group)
  summarise(OD = mean(OD),
            SD = sd(OD),
            n = n())
</code>```

Body:
I have a table that looks something like this:

Time     Carbon       OD
 0       Sucrose      1.13
 0       Citric acid  1.54
24       Histidine    2.1
24       Glutamine    1.7
48       Maleic acid  2.1
48       Furm acid    3.1
72       Tryptophan   2.3
72       Serine       1.2
72       etc          etc

It has four time points, and 9 different carbons that can be split into three groups (organic acids, sugars, amino acids).

EDIT - if its helpful, the OD was measured for each carbon at each time point 8 times. Previously I used this code to create summary statistics for the entire thing:

summary <- aggregate(dataset2$OD,
                   by = list(Time = dataset2$Time, Carbon = dataset2$Carbon),
                   FUN = function(x) c(mean = mean(x), sd = sd(x),
                                       n = length(x)))
summary <- do.call(data.frame, dataset2)
summary$se <- dataset2$x.sd / sqrt(dataset2$x.n)

But now I would like to generate the same summary statistics for the means of each of the three groups, if possible, so I would get something like this:

Time    Group    OD    SD    n    SE
  0     Group 1
 24     Group 1
 48     Group 1
 72     Group 1
  0     Group 2

I'm not quite sure how to specify this in my code?

Body:
Using dplyr:

dataset2 %>%
  group_by(Time, Group)
  summarise(OD = mean(OD),
            SD = sd(OD),
            n = n())


问:
Initialize decimal with literal
I've got Decimal class which implements decimal floating point arithmetic. It can be initialized with an integral arithmetic type or a fractional digit stored as a string. Build-in floating point types are deliberately avoided because of their approximative nature. Such approach works well but fractional digits coded as strings look awkward. Is it possible to use somehow C++ literals to build strings (or binary representation) behind the scene?</p>

```<code>Decimal a{"1.254684987"}; // current initialization
Decimal b{1.254684987_dec}; // desired way
</code>```

答:
Given that you already have a c'tor taking a C-string, simply writr something like

```<code>Decimal operator "" _dec(const char* c){
    return Decimal{c}; // Assuming an explicit c'tor
}

auto whatever = 12.3_dec;
</code>```

Of course, you need a C++11 compiler for this to work.

Title: Initialize decimal with literal

Body:
I've got Decimal class which implements decimal floating point arithmetic. It can be initialized with an integral arithmetic type or a fractional digit stored as a string. Build-in floating point types are deliberately avoided because of their approximative nature. Such approach works well but fractional digits coded as strings look awkward. Is it possible to use somehow C++ literals to build strings (or binary representation) behind the scene?

Decimal a{"1.254684987"}; // current initialization
Decimal b{1.254684987_dec}; // desired way

Body:
Given that you already have a c'tor taking a C-string, simply writr something like

Decimal operator "" _dec(const char* c){
    return Decimal{c}; // Assuming an explicit c'tor
}

auto whatever = 12.3_dec;

Of course, you need a C++11 compiler for this to work.


答:
first of all,
if your doGet() and doPost() do the same thing, you can call one from the other, sending the request and response

Second, you can pass an ArrayList<E> to the android app.
Both the Servlet and Android APIs have it

edit:
You need to read from a InputStream, generated by a HttpURLConnection object.
http://developer.android.com/reference/java/io/InputStream.html

check out this book:
used book http://www.amazon.com/Professional-Android-Application-Development-Programmer/dp/0470565527)

String input = getString(R.string.input);

try {

    URL url = new URL(input);

    URLConnection connection = url.openConnection();

    HttpURLConnection http = (HttpURLConnection)connection;

    int response = http.getResponseCode();

    if (response == HttpURLConnection.HTTP_OK) {

        InputStream is = http.getInputStream();

        //do whatever you want with the stream

    }

}

catch (MalformedURLException exception) { }

catch (IOException exception) { }

ContentLicense: CC BY-SA 2.5

Title: how to pass data from servlet to android application


问:
SparkSQL "CASE WHEN THEN" with two table columns in pyspark
I have two temporary tables table_a and table_b and trying to get this query and all of its conditions to work properly.

SELECT DISTINCT CASE WHEN a.id IS NULL THEN b.id ELSE a.id END id,
    CASE WHEN a.num IS NULL THEN b.num ELSE a.num END num,
    CASE WHEN a.testdate IS NULL THEN b.testdate ELSE a.testdate END testdate
FROM table_a a
    FULL OUTER JOIN table_b b
    ON (a.id=b.id AND a.num=b.num AND a.testdate=b.testdate)
WHERE
    (CASE WHEN a.t_amt IS NULL THEN 0 ELSE a.t_amt END)
    <>
    (CASE WHEN b.t_amt IS NULL THEN 0 ELSE b.t_amt END) OR
    (CASE WHEN a.qty IS NULL THEN 0 ELSE a.qty END)
    <>
    (CASE WHEN b.qty IS NULL THEN 0 ELSE b.qty END)
ORDER BY
    CASE WHEN a.id IS NULL THEN b.id ELSE a.id END,
    CASE WHEN a.num IS NULL THEN b.num ELSE a.num END,
    CASE WHEN a.testdate IS NULL THEN b.testdate ELSE a.testdate END
```

<p>Executing the above query on these two tables using <code>SparkSQL</code> produces the following error</p>

```sqlq = <the sql from above>

df = sqlContext.sql(sqlq)
```

"AnalysisException: u"cannot resolve 'a.id' given input columns: [id, num, testdate];"

答:
It seems your error is in the ORDER BY clause, as it has no concept of tables a and b, but only the names and aliases in the SELECT clause.

This makes quite good sense since you should really only order your results based on columns actually in the result set.

SELECT DISTINCT (CASE WHEN a.id IS NULL THEN b.id ELSE a.id END) AS id,
    (CASE WHEN a.num IS NULL THEN b.num ELSE a.num END) AS num,
    (CASE WHEN a.testdate IS NULL THEN b.testdate ELSE a.testdate END) AS testdate
FROM table_a AS a
    FULL OUTER JOIN table_b AS b
    ON (a.id=b.id AND a.num=b.num AND a.testdate=b.testdate)
WHERE
    (CASE WHEN a.t_amt IS NULL THEN 0 ELSE a.t_amt END) <> (CASE WHEN b.t_amt IS NULL THEN 0 ELSE b.t_amt END)
    OR
    (CASE WHEN a.qty IS NULL THEN 0 ELSE a.qty END) <> (CASE WHEN b.qty IS NULL THEN 0 ELSE b.qty END)
ORDER BY id, num, testdate
```

Body:
I have two temporary tables table_a and table_b and trying to get this query and all of its conditions to work properly.

SELECT DISTINCT CASE WHEN a.id IS NULL THEN b.id ELSE a.id END id,
    CASE WHEN a.num IS NULL THEN b.num ELSE a.num END num,
    CASE WHEN a.testdate IS NULL THEN b.testdate ELSE a.testdate END testdate
FROM table_a a
    FULL OUTER JOIN table_b b
    ON (a.id=b.id AND a.num=b.num AND a.testdate=b.testdate)
WHERE
    (CASE WHEN a.t_amt IS NULL THEN 0 ELSE a.t_amt END)
    <>
    (CASE WHEN b.t_amt IS NULL THEN 0 ELSE b.t_amt END) OR
    (CASE WHEN a.qty IS NULL THEN 0 ELSE a.qty END)
    <>
    (CASE WHEN b.qty IS NULL THEN 0 ELSE b.qty END)
ORDER BY
    CASE WHEN a.id IS NULL THEN b.id ELSE a.id END,
    CASE WHEN a.num IS NULL THEN b.num ELSE a.num END,
    CASE WHEN a.testdate IS NULL THEN b.testdate ELSE a.testdate END

Executing the above query on these two tables using SparkSQL produces the following error

sqlq = <the sql from above>

df = sqlContext.sql(sqlq)

"AnalysisException: u"cannot resolve 'a.id' given input columns: [id, num, testdate];"


问:
How does the non-static method of a class is getting called statically from another different class' method without creating the object of former?
I'm using PHP 7.1.11

Consider below code :

```<code><?php
  class A {
    function foo() {
      if (isset($this)) {
        echo '$this is defined (';
        echo get_class($this);
        echo ")\n";
      } else {
        echo "\$this is not defined.\n";
      }
    }
  }

  class B {
    function bar() {
      A::foo();
    }
  }

  $a = new A();
  $a->foo();

  A::foo();
  $b = new B();
  $b->bar();

  B::bar();
?>
</code>```

Output of above code :

```<code>$this is defined (A)
$this is not defined.
$this is not defined.
$this is not defined.
</code>```

Except the first line in the output the next three lines of output have been generated by calling the non-static method foo() which is present in class A statically(i.e. without creating an object of class A).

Someone please explain me how is this happening?

How does the non-static method from another class is getting called statically from the class/ object of class under consideration(i.e. class B here)?

Thank You.

答:
Note: PHP is very loose with static vs. non-static methods

But: Methods which are not static should NOT be called statically (even if PHP is tolerant). Why?

If a method is not static, this usually means that it is depending on the state of an instance, because otherwise it could be made static.

Sometimes a non-static method is not dependent on an instance and therefore a program still works, because this method could be static. But you never should do this.

Furthermore - if you turn on error reporting, PHP will also tell you this:

$this is defined (A)
 Deprecated:  Non-static method
  A::foo() should not be called statically in [...][...] on line
  25
 $this is not defined.
 Deprecated:
  Non-static method A::foo() should not be called statically in
  [...][...] on line 18
 $this is not defined.

  Deprecated:  Non-static method B::bar() should not be called
  statically in [...][...] on line 29

  Deprecated:  Non-static method A::foo() should not be called
  statically in [...][...] on line 18
 $this is not
  defined.

The Deprecated also means: Just because PHP still allows this, it will most probably be removed in future PHP updates.

Body:
I'm using PHP 7.1.11

Consider below code :

<?php
  class A {
    function foo() {
      if (isset($this)) {
        echo '$this is defined (';
        echo get_class($this);
        echo ")\n";
      } else {
        echo "\$this is not defined.\n";
      }
    }
  }

  class B {
    function bar() {
      A::foo();
    }
  }

  $a = new A();
  $a->foo();

  A::foo();
  $b = new B();
  $b->bar();

  B::bar();
?>

Output of above code :

$this is defined (A)
$this is not defined.
$this is not defined.
$this is not defined.

Except the first line in the output the next three lines of output have been generated by calling the non-static method foo() which is present in class A statically(i.e. without creating an object of class A).

Someone please explain me how is this happening?

How does the non-static method from another class is getting called statically from the class/ object of class under consideration(i.e. class B here)?

Thank You.


问:
James Montenegro : extension "Plugin For Xamarin Templates" for UWP
I want to create a plugin for Xamarin Forms. I tried that with extension "Plugin For Xamarin Templates" but when I create the project it throws this error :

And the "Solution Explorer" only shows Android , IOS and PLC projects.

答:
This template is determined for Visual Studio 2015. If you want to use it in VS2017 install Visual Studio 2015. Then create project template in VS2015 and remove Windows Phone projects. After that you can open in Visual Studio 2017.

In case that you don't want to install VS2015 you can do everything manually. Follow my answer here.


问:
Any Extension in VS code to integrate with Adobe CRX/CQ content
Is there any plugin through which I can integrate Visual Studio Code with Adobe Experience Manager without time-consuming builds, deploys, or lunching heavy CRXDE.

There is plugin in Submime Text 2 , VLT (https://packagecontrol.io/packages/Vlt) , but is it possible in vs code.

答:
No, there isn't. (As of Oct 2017)

If escaping time consuming builds is your goal than you can use gulp  to deploy files to AEM on change. For some time I used a package named gulp-slang. You should try that.


问:
how to serialize class to database instead of file system c#
we can easily serialize class to flat file but if i want to serialize class to database then how could i do it and if it is possible then how can i deserialize data from db to class.
please give a sample code in c#.

thanks

答:
You can serialize a class (out of the box) to binary form or to XML.

In the first case you get a byte[], and in the second you get a simple string.

If you want to persist that in the database, just treat it as any other byte array or string (or XML, if your database natively supports that) that need to be sent to the database.


问:
Full width of col-md-10 when using col-md-2 for sidebar bootstrap 4
I am trying to add background color for nav-header, and since it is within col-md-10, it won't take full width when sidebar (col-md-2) is closed.
I tried to wrap it inside another div, but it doesn't work, I can't override col-md-10 rules. Is there any way to do this?</p>

```<code><div class="container-fluid">
    <div class="row d-flex d-md-block flex-nowrap wrapper">
        <div class="col-md-2 float-left col-1 pl-0 pr-0 collapse width hidden" id="sidebar">
            <div class="list-group border-0 card text-center text-md-left">

                <a href="#" class="list-group-item d-inline-block collapsed" data-parent="#sidebar"><i class="fa fa-film"></i> <span class="d-none d-md-inline">Item 2</span></a>
                <a href="#menu3" class="list-group-item d-inline-block collapsed" data-toggle="collapse" data-parent="#sidebar" aria-expanded="false"><i class="fa fa-book"></i> <span class="d-none d-md-inline">Item 3 </span></a><a href="#" class="list-group-item d-inline-block collapsed" data-parent="#sidebar"><i class="fa fa-heart"></i> <span class="d-none d-md-inline">Item 4</span></a>
                <a href="#" class="list-group-item d-inline-block collapsed" data-parent="#sidebar"><i class="fa fa-list"></i> <span class="d-none d-md-inline">Item 5</span></a>

            </div>
        </div>
        <main class="col-md-10 float-left">
            <div class="nav-header">
                <a href="#" data-target="#sidebar" data-toggle="collapse"><i class="fa fa-navicon fa-2x py-2 p-1"></i></a>
                <a href="/" class="navbar-brand"><img src="img/logo.png" height="45" alt=""></a>
            </div>
            <div class="page-header">
                <h2>Bootstrap 4 Sidebar Menu</h2>
            </div>

            <hr>

        </main>
    </div>
</div>
</code>```

答:
Perhaps a positioned pseudo-element to imitate a background.

```<code>.col-md-10 .nav-header{
  position: relative;

}

.col-md-10 .nav-header::after {
  content:"";
  position: absolute;
  top:0;
  left:0;
  height:100%;
  background: red;
  width:calc(100vw - 30px);
}
</code>```

.col-md-10 .nav-header {
  position: relative;
}

.col-md-10 .nav-header::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: red;
  width: calc(100vw - 30px);
  z-index: -1
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
  <div class="row d-flex d-md-block flex-nowrap wrapper">
    <div class="col-md-2 float-left col-1 pl-0 pr-0 collapse width hidden" id="sidebar">
      <div class="list-group border-0 card text-center text-md-left">

        <i class="fa fa-film"></i> <span class="d-none d-md-inline">Item 2</span>
        <i class="fa fa-book"></i> <span class="d-none d-md-inline">Item 3 </span><i class="fa fa-heart"></i> <span class="d-none d-md-inline">Item 4</span>
        <i class="fa fa-list"></i> <span class="d-none d-md-inline">Item 5</span>

      </div>
    </div>
    <main class="col-md-10 float-left">
      <div class="nav-header">
        Nav header content
        <i class="fa fa-navicon fa-2x py-2 p-1"></i>
        <img src="img/logo.png" height="45" alt="">
      </div>
      <div class="page-header">
        <h2>Bootstrap 4 Sidebar Menu</h2>
      </div>

      <hr>

    </main>
  </div></code>```

Body:
I am trying to add background color for nav-header, and since it is within col-md-10, it won't take full width when sidebar (col-md-2) is closed.
I tried to wrap it inside another div, but it doesn't work, I can't override col-md-10 rules. Is there any way to do this?

                 Item 2
                 Item 3  Item 4
                 Item 5

Bootstrap 4 Sidebar Menu

Body:
Perhaps a positioned pseudo-element to imitate a background.

.col-md-10 .nav-header{
  position: relative;

}

.col-md-10 .nav-header::after {
  content:"";
  position: absolute;
  top:0;
  left:0;
  height:100%;
  background: red;
  width:calc(100vw - 30px);
}

.col-md-10 .nav-header {
  position: relative;
}

.col-md-10 .nav-header::after {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: red;
  width: calc(100vw - 30px);
  z-index: -1
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="container-fluid">
  <div class="row d-flex d-md-block flex-nowrap wrapper">
    <div class="col-md-2 float-left col-1 pl-0 pr-0 collapse width hidden" id="sidebar">
      <div class="list-group border-0 card text-center text-md-left">

        <a href="#" class="list-group-item d-inline-block collapsed" data-parent="#sidebar"><i class="fa fa-film"></i> <span class="d-none d-md-inline">Item 2</span></a>
        <a href="#menu3" class="list-group-item d-inline-block collapsed" data-toggle="collapse" data-parent="#sidebar" aria-expanded="false"><i class="fa fa-book"></i> <span class="d-none d-md-inline">Item 3 </span></a><a href="#" class="list-group-item d-inline-block collapsed"
          data-parent="#sidebar"><i class="fa fa-heart"></i> <span class="d-none d-md-inline">Item 4</span></a>
        <a href="#" class="list-group-item d-inline-block collapsed" data-parent="#sidebar"><i class="fa fa-list"></i> <span class="d-none d-md-inline">Item 5</span></a>

      </div>
    </div>
    <main class="col-md-10 float-left">
      <div class="nav-header">
        Nav header content
        <a href="#" data-target="#sidebar" data-toggle="collapse"><i class="fa fa-navicon fa-2x py-2 p-1"></i></a>
        <a href="/" class="navbar-brand"><img src="img/logo.png" height="45" alt=""></a>
      </div>
      <div class="page-header">
        <h2>Bootstrap 4 Sidebar Menu</h2>
      </div>

      <hr>

    </main>
  </div>


问:
akka-streams with akka-cluster
My akka-streams learn-o-thon continues. I'd like to integrate my akka-streams application with akka-cluster and DistributedPubSubMediator.

Adding support for Publish is fairly straight forward, but the Subscribe part I'm having trouble with.

For reference, a subscriber is given as follows in the Typesafe  sample:

```<code>class ChatClient(name: String) extends Actor {
  val mediator = DistributedPubSub(context.system).mediator
  mediator ! Subscribe("some topic", self)

  def receive = {
    case ChatClient.Message(from, text) =>
      ...process message...
  }
}
</code>```

My question is, how should I integrate this actor with my flow, and how should I ensure I'm getting publish messages in the absence of stream backpressure?

I'm trying to accomplish a pubsub model where one stream may publish a message and another stream would consume it (if subscribed).

答:
The other answers are outdated: they suggest using ActorPublisher, which has been deprecated since version 2.5.0.

For those interested in a current approach, Colin Breck wrote an excellent series in his blog about integrating Akka Streams and Akka actors. Over the course of the series, Breck fleshes out a system that begins with Akka Streams and plain actors, then incorporates Akka Cluster and Akka Persistence. The first post in the series is here (the distributed stream processing piece is in part 3).

Title: akka-streams with akka-cluster

Body:
My akka-streams learn-o-thon continues. I'd like to integrate my akka-streams application with akka-cluster and DistributedPubSubMediator.

Adding support for Publish is fairly straight forward, but the Subscribe part I'm having trouble with.

For reference, a subscriber is given as follows in the Typesafe  sample:

class ChatClient(name: String) extends Actor {
  val mediator = DistributedPubSub(context.system).mediator
  mediator ! Subscribe("some topic", self)

  def receive = {
    case ChatClient.Message(from, text) =>
      ...process message...
  }
}

My question is, how should I integrate this actor with my flow, and how should I ensure I'm getting publish messages in the absence of stream backpressure?

I'm trying to accomplish a pubsub model where one stream may publish a message and another stream would consume it (if subscribed).


答:
```<code>select tbl1.name, SUM(tbl1.total), SUM(COALESCE(tbl2.qty, 0))
from tbl1
left join tbl2 ON tbl1.id = tbl2.id
GROUP by tbl1.name
</code>```

Title: SQL - How can I JOIN two tables and SUM a column based on IDs between them?

Body:
I have two tables. One table is with master data

Table tbl1:

+-------------+------------+------------+
| ID          | Name       | Total      |
+-------------+------------+------------+
| 1           | a          | 10         |
| 2           | b          | 5          |
| 3           | c          | 4          |
| 4           | a          | 4          |
+-------------+------------+------------+

Second table tbl2 contains child data. The key between tables is ID

Table tbl2:

+-------------+------------+
|id           | qty        |
+-------------+------------+
| 1           | 4          |
| 1           | 3          |
| 1           | 1          |
| 3           | 1          |
| 3           | 3          |
+-------------+------------+

I need to get output like this:

Output:

+-------------+------------+------------+
| name        | sum_tot    | sum_qty    |
+-------------+------------+------------+
| a           | 14         | 8          |
| b           | 5          | 0          |
| c           | 4          | 4          |
+-------------+------------+------------+

I had tried with this:

select tbl1.name, SUM(tbl1.total), SUM(tbl2.qty)
from tbl1
left join tbl2 ON tbl1.id = tbl2.id
GROUP by tbl1.name

The output that I get is:

Output:

+-------------+------------+------------+
| name        | sum_tot    | sum_qty    |
+-------------+------------+------------+
| a           | 34         | 8          |
| b           | 5          |null        |
| c           | 8          | 4          |
+-------------+------------+------------+

Which is not correct.

Here is the sql fiddle:

The summary from first table is not in relation with second table. It seems that somehow query runs three times.


问:
Web Service checking that DB is available
I need to create an ASP.NET web service that simply returns an information telling if a database is available or down when it's consumed.

So I would like to know if I can set a task that is executed inside the web service method on a regular basis to check the connection to the database and return the result via a URL.

答:
As you tagged c# and asp so you are using Sql server database,
this query gives you databases that exists on your sql server instance:

```<code>  select * from master.dbo.sysdatabases
</code>```

result contains name and some extra information, name gives you database names, mode column have a int value indicates that database is in creating mode or created mode, status column that contains a int value(power of 2)

If you would like to see if database is offline or not, you can see status value if it is 512 your database is offline, for 1024 it is in read only mode

for your service you can use web api, web method or wcf, it is depend on you

If you use hangfire, quartz or any other scheduler you can set a background job on your server to check your database status

"return the result via a URL" I can not understand this, but if you want to notify users about database you can use push notification on your background job

Body:
As you tagged c# and asp so you are using Sql server database,
this query gives you databases that exists on your sql server instance:

  select * from master.dbo.sysdatabases

result contains name and some extra information, name gives you database names, mode column have a int value indicates that database is in creating mode or created mode, status column that contains a int value(power of 2)

If you would like to see if database is offline or not, you can see status value if it is 512 your database is offline, for 1024 it is in read only mode

for your service you can use web api, web method or wcf, it is depend on you

If you use hangfire, quartz or any other scheduler you can set a background job on your server to check your database status

"return the result via a URL" I can not understand this, but if you want to notify users about database you can use push notification on your background job


问:
How to show hide a class?
On ajax success I have to hide a class and show the different class.
Suppose I have "foo" and "bar" two classes. Now it has "foo" class when my ajax returns success then I want to show the "bar" class.

```<code>$.ajax({
        type:'POST',
        url:"/test/",
        data:{"test_data": my_data},
        success:function(data) {

        },
        dataType:"json"
        // here I want to hide the "foo" class and show the "bar" class.
    });
</code>```

Actually "foo" and "bar" is a class of button. when i click button having "foo" class it should hide and button having "bar" class should be shown. and vice versa

Title: How to show hide a class?

Body:
On ajax success I have to hide a class and show the different class.
Suppose I have "foo" and "bar" two classes. Now it has "foo" class when my ajax returns success then I want to show the "bar" class.

$.ajax({
        type:'POST',
        url:"/test/",
        data:{"test_data": my_data},
        success:function(data) {

        },
        dataType:"json"
        // here I want to hide the "foo" class and show the "bar" class.
    });

Actually "foo" and "bar" is a class of button. when i click button having "foo" class it should hide and button having "bar" class should be shown. and vice versa

Body:
$(".foo").hide();
$(".bar").show();


问:
How to get local computer name after New-PSSession -Computername?
I am getting the below error, please advise how to fix this error for null-valued expression

```<code>You cannnot call a method on a null-valued expression
+CategoryInfo : InvalidOoperation: (:)[], RuntimeException
+FullyQualifiedErrorId: InvokeMethodonNull
+PSComputerName: DC1
</code>```

Code below

```<code>function myfunction (){
$remoteserver = 'DC1'
$Session = New-PSSession -Computername $remoteserver -Credential $Cred
Import-Module ActiveDirectory
$local= $env:COMPUTERNAME

Invoke-Command -ComputerName $remoteserver -Credential $cred -ScriptBlock
{$using:local
if($local.substring(5,3) -imatch "Sys") {
Get-ADComputer $local | Move-ADObject -Targetpath "ou=PRD,ou=Servers,dc=com,dc=Companycorp,dc=net"}
}
} #end function
Invoke-Command -ComputerName $remoteserver -ScriptBlock ${Function:myFunction}
</code>```

答:
What I think you're asking is 'how do I open a session on a remote pc, but then still run commands on my local PC'.  If that's so, then let's walk through it.

First, we can open a remote connection to another computer in PowerShell by creating a new PSSession, as you're doing here:

```<code>$session = New-PSSession -Computername DC01 -Credential $cred
</code>```

You can then either step into the remote computer wholly using Enter-PSSession, or just send individual commands to the remote computer using:

```<code>Invoke-Command -ScriptBlock {#Commands to run on the remote PC}`
 -Session $session
</code>```

Once you enter the remote PC, you can return to your own PC using the Exit-PSSession command.

```<code>#Enter Remote PC
Enter-PSSession $session

DC01> hostname

*DC01*

#Step out of Remote PC
Exit-PSSession

PS> hostname

*YOURPCNAME*
</code>```

If this isn't what you want to do, let me know and we'll get you sorted.

Body:
I am getting the below error, please advise how to fix this error for null-valued expression

You cannnot call a method on a null-valued expression
+CategoryInfo : InvalidOoperation: (:)[], RuntimeException
+FullyQualifiedErrorId: InvokeMethodonNull
+PSComputerName: DC1

Code below

function myfunction (){
$remoteserver = 'DC1'
$Session = New-PSSession -Computername $remoteserver -Credential $Cred
Import-Module ActiveDirectory
$local= $env:COMPUTERNAME

Invoke-Command -ComputerName $remoteserver -Credential $cred -ScriptBlock
{$using:local
if($local.substring(5,3) -imatch "Sys") {
Get-ADComputer $local | Move-ADObject -Targetpath "ou=PRD,ou=Servers,dc=com,dc=Companycorp,dc=net"}
}
} #end function
Invoke-Command -ComputerName $remoteserver -ScriptBlock ${Function:myFunction}

Body:
What I think you're asking is 'how do I open a session on a remote pc, but then still run commands on my local PC'.  If that's so, then let's walk through it.

First, we can open a remote connection to another computer in PowerShell by creating a new PSSession, as you're doing here:

$session = New-PSSession -Computername DC01 -Credential $cred

You can then either step into the remote computer wholly using Enter-PSSession, or just send individual commands to the remote computer using:

Invoke-Command -ScriptBlock {#Commands to run on the remote PC}`
 -Session $session

Once you enter the remote PC, you can return to your own PC using the Exit-PSSession command.

#Enter Remote PC
Enter-PSSession $session

DC01> hostname

*DC01*

#Step out of Remote PC
Exit-PSSession

PS> hostname

*YOURPCNAME*

If this isn't what you want to do, let me know and we'll get you sorted.


问:
Firebase last 10 data retrieving from database in Cloud Function
The below Cloud Function only returns the first data instead of 10:

```<code>exports.viewdata = functions.https.onRequest((req, res) => {
    const userId = req.query.user;
    return admin.database().ref('users/' + userId)
    .orderByKey()
    .limitToLast(10)
    .on('child_added', function(snapshot) {
        snapshot.forEach(function(data) {
        res.status(200).send(data.val());
        });
     });
});
</code>```

Please help me to fix this.

答:
Using send(), end() or redirect() will terminate a HTTP Cloud Function:

Always end an HTTP function with send(), redirect(), or end(). Otherwise, your function might to continue to run and be forcibly terminated by the system.

In your example, you are calling res.status(200).send(data.val()); inside your forEach iteration of each child snapshot, therefore it will only get a chance to send the one response.

Likewise, because you have used a child_added event listener, it is triggered once for every child at the specified path.

If you need to respond with all the query data at once, you'll be better off with a value event listener instead, which will retrieve all data from your query in a single response:

```<code>exports.viewdata = functions.https.onRequest((req, res) => {
    const userId = req.query.user;
    admin.database().ref('users/' + userId)
    .orderByKey()
    .limitToLast(10)
    .on('value', function(snapshot) {
        res.status(200).send(snapshot.val());
    });
});
</code>```

However, if your intention is to build a response with each child separately, you could use res.write() to write data to the response, and then eventually send this with end():

```<code>exports.viewdata = functions.https.onRequest((req, res) => {
    const userId = req.query.user;
    admin.database().ref('users/' + userId)
    .orderByKey()
    .limitToLast(10)
    .on('value', function(snapshot) {
        snapshot.forEach(function(data) {
            res.write(data.val());
        });
        res.status(200).end();
    });
});
</code>```

Or, you could add them to a list before sending them all back as a response. The method you take here all depends on your end-goal though.

Unrelated to your initial question, but for completeness, please see the below observations and side notes, from comments:

The return statement for admin.database().ref() is not required for HTTPS triggers as they have a different lifecycle than other triggers and do not need to return promises.

If you have no need to listen for further changes after you've retrieved the necessary data, you should consider using once() (to read data once) instead of on() or removing the on() listener with off().

Body:
The below Cloud Function only returns the first data instead of 10:

exports.viewdata = functions.https.onRequest((req, res) => {
    const userId = req.query.user;
    return admin.database().ref('users/' + userId)
    .orderByKey()
    .limitToLast(10)
    .on('child_added', function(snapshot) {
        snapshot.forEach(function(data) {
        res.status(200).send(data.val());
        });
     });
});

Please help me to fix this.

Body:
Using send(), end() or redirect() will terminate a HTTP Cloud Function:

Always end an HTTP function with send(), redirect(), or end(). Otherwise, your function might to continue to run and be forcibly terminated by the system.

In your example, you are calling res.status(200).send(data.val()); inside your forEach iteration of each child snapshot, therefore it will only get a chance to send the one response.

Likewise, because you have used a child_added event listener, it is triggered once for every child at the specified path.

If you need to respond with all the query data at once, you'll be better off with a value event listener instead, which will retrieve all data from your query in a single response:

exports.viewdata = functions.https.onRequest((req, res) => {
    const userId = req.query.user;
    admin.database().ref('users/' + userId)
    .orderByKey()
    .limitToLast(10)
    .on('value', function(snapshot) {
        res.status(200).send(snapshot.val());
    });
});

However, if your intention is to build a response with each child separately, you could use res.write() to write data to the response, and then eventually send this with end():

exports.viewdata = functions.https.onRequest((req, res) => {
    const userId = req.query.user;
    admin.database().ref('users/' + userId)
    .orderByKey()
    .limitToLast(10)
    .on('value', function(snapshot) {
        snapshot.forEach(function(data) {
            res.write(data.val());
        });
        res.status(200).end();
    });
});

Or, you could add them to a list before sending them all back as a response. The method you take here all depends on your end-goal though.

Unrelated to your initial question, but for completeness, please see the below observations and side notes, from comments:

The return statement for admin.database().ref() is not required for HTTPS triggers as they have a different lifecycle than other triggers and do not need to return promises.

If you have no need to listen for further changes after you've retrieved the necessary data, you should consider using once() (to read data once) instead of on() or removing the on() listener with off().


Title: Python Partition By

Body:
I have the below dataframe df:

| Staff_ID | Join_Date | Time_Stamp |
|----------|-----------|------------|
| 1        | 3/29/2016 | 4/23/2016  |
| 1        | 3/29/2016 | 3/29/2016  |
| 1        | 3/29/2016 | 6/21/2016  |
| 2        | 5/15/2016 | 4/1/2016   |
| 2        | 5/15/2016 | 5/25/2016  |
| 3        | 7/24/2016 | 6/21/2016  |
| 3        | 7/24/2016 | 6/10/2016  |
| 3        | 7/24/2016 | 4/21/2016  |

I want to get the Min and Max "Time_Stamp Date" partition by "Staff_ID" such that the resultant dataframe is as follows:

| Staff_ID | Join_Date | Time_Stamp | Min_Time_Stamp | Max_Time_Stamp |
|----------|-----------|------------|----------------|----------------|
| 1        | 3/29/2016 | 4/23/2016  | 3/29/2016      | 6/21/2016      |
| 1        | 3/29/2016 | 3/29/2016  | 3/29/2016      | 6/21/2016      |
| 1        | 3/29/2016 | 6/21/2016  | 3/29/2016      | 6/21/2016      |
| 2        | 5/15/2016 | 4/1/2016   | 4/1/2016       | 5/25/2016      |
| 2        | 5/15/2016 | 5/25/2016  | 4/1/2016       | 5/25/2016      |
| 3        | 7/24/2016 | 6/21/2016  | 4/21/2016      | 6/21/2016      |
| 3        | 7/24/2016 | 6/10/2016  | 4/21/2016      | 6/21/2016      |
| 3        | 7/24/2016 | 4/21/2016  | 4/21/2016      | 6/21/2016      |

How can I do this in Python ?

Body:
Let's use groupby with transform and assign:

g = df.groupby('Staff_ID')['Time_Stamp']
df.assign(Min_Time_Stamp = g.transform(min), Max_Time_Stamp = g.transform(max))

Output:

     Staff_ID    Join_Date    Time_Stamp Max_Time_Stamp Min_Time_Stamp
1   1           3/29/2016    4/23/2016      6/21/2016      3/29/2016
2   1           3/29/2016    3/29/2016      6/21/2016      3/29/2016
3   1           3/29/2016    6/21/2016      6/21/2016      3/29/2016
4   2           5/15/2016    4/1/2016       5/25/2016      4/1/2016
5   2           5/15/2016    5/25/2016      5/25/2016      4/1/2016
6   3           7/24/2016    6/21/2016      6/21/2016      4/21/2016
7   3           7/24/2016    6/10/2016      6/21/2016      4/21/2016
8   3           7/24/2016    4/21/2016      6/21/2016      4/21/2016

Timings:

@CarlesMitjans method:

10 loops, best of 3: 33.3 ms per loop

@ScottBoston method:

100 loops, best of 3: 5.52 ms per loop


问:
Angular 4+ best practice HTTP service
Hello I have a quick question about using HTTP service :

I would like to know if this is the right way to do.

Task

```<code>export interface Task {
    Title: string;
    AssignedTo: User;
    TaskStatus: string;
}
</code>```

TaskService

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
import { Task } from '../interfaces/task'

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http.get(serviceUrl)
            .map((res: Task) => {
                return res;
            });
    }
}
</code>```

TaskComponent

```<code>export class TaskComponent implements OnInit {
    task: Task;
    constructor(
        private taskService: TaskService
    ) { }
    ngOnInit() {
        this.route.params.subscribe(params => {
            this.getTask(<number>params.id);
        });
    }
    getTask(id: number) {
        this.taskService.getTask(id).subscribe(
          res => { this.task = res;    console.log(this.task) },
          err => { console.log(err); }
        )
    }
}
</code>```

template

```<code><input type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">
</code>```

I'm not sure if that's the way to go now... I still have errors like: "ERROR TypeError: Cannot read property 'Title' of undefined", Except when I replace in my component "Task: Task" in "task: {}" ... Do I have to use an interface?

答:
I would instance the object this way:

```<code>task = <Task>{};
</code>```

This way it will be or empty or filled, but not undefined.

Title: Angular 4+ best practice HTTP service

Body:
Hello I have a quick question about using HTTP service :

I would like to know if this is the right way to do.

Task

export interface Task {
    Title: string;
    AssignedTo: User;
    TaskStatus: string;
}

TaskService

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';
import { Task } from '../interfaces/task'

@Injectable()
export class TaskService {

    constructor(private http: HttpClient) { }

    getTask(id: number): Observable<Task> {
        const serviceUrl: string = environment.apiUrl + 'Tasks/' + id;
        return this.http.get(serviceUrl)
            .map((res: Task) => {
                return res;
            });
    }
}

TaskComponent

export class TaskComponent implements OnInit {
    task: Task;
    constructor(
        private taskService: TaskService
    ) { }
    ngOnInit() {
        this.route.params.subscribe(params => {
            this.getTask(<number>params.id);
        });
    }
    getTask(id: number) {
        this.taskService.getTask(id).subscribe(
          res => { this.task = res;    console.log(this.task) },
          err => { console.log(err); }
        )
    }
}

template

<input type="text" class="form-control" id="title" placeholder="Title"[(ngModel)]="task.Title" name="title">

I'm not sure if that's the way to go now... I still have errors like: "ERROR TypeError: Cannot read property 'Title' of undefined", Except when I replace in my component "Task: Task" in "task: {}" ... Do I have to use an interface?

Body:
I would instance the object this way:

task = <Task>{};

This way it will be or empty or filled, but not undefined.


问:
printf format based on data type
I have a templated buffer class with a simple printing function.

```<code>template <typename valueType, typename sumType, int N>
class IM_buffer
{
public:
    IM_buffer()
        : bufferValues(), numValues(-1), currentSum() { }

    void record(valueType sample)
    {
        // Set buffer index to be recorded
        numValues++;

        // Get memory location for oldest element in buffer
        valueType& oldest = bufferValues[modIdx(numValues)];

        // Add the input value to the current sum and take away the value being replaced
        currentSum += sample - oldest;

        // And now do the actual replacement in the same memory location
        oldest = sample;
    }

    valueType   getCurrent()            { return bufferValues[modIdx(numValues)];           }
    valueType   getNthPrev(int Nprev)   { return bufferValues[modIdx(numValues-Nprev)];     }
    sumType     getCurrentSum()         { return currentSum;                                }
    double      getAvg()                { return (double) currentSum / MIN(numValues+1, N); }
    int         getNumValues()          { return numValues+1;                               }
    int         getBufferSize()         { return N;                                         }

    void printBuff()
    {
        for (int ii=0; ii<N; ii++)
        {
            // if it's an integer type I need:
            printf("bufferValues[%2d]=%4d\n",ii,bufferValues[ii]);
            // but if it's a floating point type I need:
            printf("bufferValues[%2d]=%8g\n",ii,bufferValues[ii]);
        }
    }

    void clear()
    {
        for (int ii=0; ii<N; ii++)
            bufferValues[ii] = (valueType) 0.0;
        numValues = 0;
        currentSum = (sumType) 0.0;
    }

private:
    valueType bufferValues[N];
    int numValues;
    sumType currentSum;

    int modIdx(int a) { return (a % N + N) % N; }
};
</code>```

However, the format string of the printf should depend on what the data type is (e.g. int, vs. float, vs double). I've seen discussions like this but I don't really want to print out the data type, I just need to change the printf format string based on the data type. Can anyone point me in the right direction for how to implement some condition logic to select the right printf?

答:
If you don't want to use the C++ overloaded insertion operators, you can write your own overloaded function:

```<code>void print(int i) {
    printf("%4d",i);
}

void print(double d) {
    printf("%8g",d);
}
</code>```

etc.

Now you can call print from your printBuff function when needed:

```<code>printf("bufferValues["%2d] =",ii);
print(bufferValues[ii]);
printf("\n");
</code>```

Title: printf format based on data type

Body:
I have a templated buffer class with a simple printing function.

template <typename valueType, typename sumType, int N>
class IM_buffer
{
public:
    IM_buffer()
        : bufferValues(), numValues(-1), currentSum() { }

    void record(valueType sample)
    {
        // Set buffer index to be recorded
        numValues++;

        // Get memory location for oldest element in buffer
        valueType& oldest = bufferValues[modIdx(numValues)];

        // Add the input value to the current sum and take away the value being replaced
        currentSum += sample - oldest;

        // And now do the actual replacement in the same memory location
        oldest = sample;
    }

    valueType   getCurrent()            { return bufferValues[modIdx(numValues)];           }
    valueType   getNthPrev(int Nprev)   { return bufferValues[modIdx(numValues-Nprev)];     }
    sumType     getCurrentSum()         { return currentSum;                                }
    double      getAvg()                { return (double) currentSum / MIN(numValues+1, N); }
    int         getNumValues()          { return numValues+1;                               }
    int         getBufferSize()         { return N;                                         }

    void printBuff()
    {
        for (int ii=0; ii<N; ii++)
        {
            // if it's an integer type I need:
            printf("bufferValues[%2d]=%4d\n",ii,bufferValues[ii]);
            // but if it's a floating point type I need:
            printf("bufferValues[%2d]=%8g\n",ii,bufferValues[ii]);
        }
    }

    void clear()
    {
        for (int ii=0; ii<N; ii++)
            bufferValues[ii] = (valueType) 0.0;
        numValues = 0;
        currentSum = (sumType) 0.0;
    }

private:
    valueType bufferValues[N];
    int numValues;
    sumType currentSum;

    int modIdx(int a) { return (a % N + N) % N; }
};

However, the format string of the printf should depend on what the data type is (e.g. int, vs. float, vs double). I've seen discussions like this but I don't really want to print out the data type, I just need to change the printf format string based on the data type. Can anyone point me in the right direction for how to implement some condition logic to select the right printf?

Body:
If you don't want to use the C++ overloaded insertion operators, you can write your own overloaded function:

void print(int i) {
    printf("%4d",i);
}

void print(double d) {
    printf("%8g",d);
}

etc.

Now you can call print from your printBuff function when needed:

printf("bufferValues["%2d] =",ii);
print(bufferValues[ii]);
printf("\n");


问:
how can i show an irrational number to 100 decimal places in python?
I am trying to find the square root of 2 to 100 decimal places, but it only shows to like 10 by default, how can I change this?</p>

答:
You can use the decimal module for arbitrary precision numbers:

```<code>import decimal

d2 = decimal.Decimal(2)

# Add a context with an arbitrary precision of 100
dot100 = decimal.Context(prec=100)

print d2.sqrt(dot100)
</code>```

If you need the same kind of ability coupled to speed, there are some other options: [gmpy], 2, cdecimal.

Body:
You can use the decimal module for arbitrary precision numbers:

import decimal

d2 = decimal.Decimal(2)

# Add a context with an arbitrary precision of 100
dot100 = decimal.Context(prec=100)

print d2.sqrt(dot100)

If you need the same kind of ability coupled to speed, there are some other options: [gmpy], 2, cdecimal.


问:
How to import with ECMAScript (vanilla javascript) with modules es6
I read this post and i want use D3.js (v4+) using only import statement like this:

```<code>import { selection } from '../node modules/d3/build/d3.js';
</code>```

But, because code output is UMD (or read this) and can't import because some globals is no defined, and ES6 can't resolve absolutive names in node_modules for example and vanilla don't suport import statement without extension like this:

```<code>import * as someFeature from './myAwesomeModule';
</code>```

And this is pattern to import modules and each day is growing up like you see here.

How i can use import statement without any plugin today?

答:
You can import d3 like this:

import * as d3 from 'd3';

See more here: https://github.com/d3/d3/blob/master/README.md#installing

Body:
I read this post and i want use D3.js (v4+) using only import statement like this:

import { selection } from '../node modules/d3/build/d3.js';

But, because code output is UMD (or read this) and can't import because some globals is no defined, and ES6 can't resolve absolutive names in node_modules for example and vanilla don't suport import statement without extension like this:

import * as someFeature from './myAwesomeModule';

And this is pattern to import modules and each day is growing up like you see here.

How i can use import statement without any plugin today?


问:
100% width w/o parent element
I'm a bit confused. I'm building an To-Do List app and I'm trying to set the header as 100% of the screen width. I have the correct meta tags, I believe, but setting the header at 100% width is stretching the element past the right side of the screen. Is there something I'm doing wrong?</p>

```<code><!DOCTYPE html>
<html>
 <head>

 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Todo List App</title>

 <link rel="stylesheet" text="text/css" href="style.css">

 </head>
 <body>
     <header>

         <input type="text" placeholder="Enter an activity...">

         <button></button>

     </header>
 </body>
</html>

@charset "UTF-8";

header {
width: 100%;
height: 80px;
position: fixed;
padding: 15px;
top: 0px;
left: 0px;
z-index: 5;
background: #25b99a;
box-shadow:0px 2px 4px rgba(44, 62, 80, 0.15);
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
}

header input {
width: 100%;
height: 50px;
float: left;
background: rgba(255,255,255,0.2);
border-top-left-radius: 5px;
border-bottom-left-radius: 5px;
border-top-right-radius: 25px;
border-bottom-right-radius: 25px;
border-radius: 5px;
border: 0px;
box-shadow: none;
outline: none;
}
</code>```

答:
You need to include the box-sizing property.

Info from MDN

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 0;
}

header {
  width: 100%;
  height: 80px;
  position: fixed;
  padding: 15px;
  top: 0px;
  left: 0px;
  z-index: 5;
  background: #25b99a;
  box-shadow: 0px 2px 4px rgba(44, 62, 80, 0.15);
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
}

header input {
  width: 100%;
  height: 50px;
  float: left;
  background: rgba(255, 255, 255, 0.2);
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  border-top-right-radius: 25px;
  border-bottom-right-radius: 25px;
  border-radius: 5px;
  border: 0px;
  box-shadow: none;
  outline: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <input type="text" placeholder="Enter an activity...">
  <button></button>
</header></code>```

Title: 100% width w/o parent element

Body:
I'm a bit confused. I'm building an To-Do List app and I'm trying to set the header as 100% of the screen width. I have the correct meta tags, I believe, but setting the header at 100% width is stretching the element past the right side of the screen. Is there something I'm doing wrong?

<!DOCTYPE html>

 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Todo List App</title>

 <link rel="stylesheet" text="text/css" href="style.css">

         <input type="text" placeholder="Enter an activity...">

         <button></button>

@charset "UTF-8";

header {
width: 100%;
height: 80px;
position: fixed;
padding: 15px;
top: 0px;
left: 0px;
z-index: 5;
background: #25b99a;
box-shadow:0px 2px 4px rgba(44, 62, 80, 0.15);
border-bottom-right-radius: 10px;
border-bottom-left-radius: 10px;
}

header input {
width: 100%;
height: 50px;
float: left;
background: rgba(255,255,255,0.2);
border-top-left-radius: 5px;
border-bottom-left-radius: 5px;
border-top-right-radius: 25px;
border-bottom-right-radius: 25px;
border-radius: 5px;
border: 0px;
box-shadow: none;
outline: none;
}

Body:
You need to include the box-sizing property.

Info from MDN

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 0;
}

header {
  width: 100%;
  height: 80px;
  position: fixed;
  padding: 15px;
  top: 0px;
  left: 0px;
  z-index: 5;
  background: #25b99a;
  box-shadow: 0px 2px 4px rgba(44, 62, 80, 0.15);
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
}

header input {
  width: 100%;
  height: 50px;
  float: left;
  background: rgba(255, 255, 255, 0.2);
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  border-top-right-radius: 25px;
  border-bottom-right-radius: 25px;
  border-radius: 5px;
  border: 0px;
  box-shadow: none;
  outline: none;
}

<header>
  <input type="text" placeholder="Enter an activity...">
  <button></button>
</header>


问:
Is it possible to horizontally align individual characters with letter-spacing in CSS?
Given a CSS rule of letter-spacing: 16px;, I notice that the characters are left-aligned within their "box", and make the cursor jump ahead to the far right, as if I added an extra space after the character.

Is it possible to use letter-spacing, but having the characters horizontally aligned within their new extended boundaries?

答:
As have been said, letter-spacing does not have a mean to position the character in the unit, more precisely really just adds "tracking".

From your comment it is apparent what you want to get, and it is kinda achievable, provided you can split your input to multiple one-character ones:

div {
  border: 1px solid black;
  overflow: hidden;
  float: left;
  clear: both;
}

input {
  border: none;
  display: block;
  float: left;
  width: 20px; /* mimics letter-spacing*/
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input name="pin1[]" maxlength=1 oninput="this.nextElementSibling.select()" value="m">
  <input name="pin1[]" maxlength=1 oninput="this.nextElementSibling.select()" value="i">
  <input name="pin1[]" maxlength=1 value="m">
</div>

<div>
  <input name="pin2[]" maxlength=1 oninput="this.nextElementSibling.select()" value="i">
  <input name="pin2[]" maxlength=1 oninput="this.nextElementSibling.select()" value="m">
  <input name="pin2[]" maxlength=1 value="i">
</div></code>```

Body:
As have been said, letter-spacing does not have a mean to position the character in the unit, more precisely really just adds "tracking".

From your comment it is apparent what you want to get, and it is kinda achievable, provided you can split your input to multiple one-character ones:

div {
  border: 1px solid black;
  overflow: hidden;
  float: left;
  clear: both;
}

input {
  border: none;
  display: block;
  float: left;
  width: 20px; /* mimics letter-spacing*/
  text-align: center;
}

<div>
  <input name="pin1[]" maxlength=1 oninput="this.nextElementSibling.select()" value="m">
  <input name="pin1[]" maxlength=1 oninput="this.nextElementSibling.select()" value="i">
  <input name="pin1[]" maxlength=1 value="m">
</div>

<div>
  <input name="pin2[]" maxlength=1 oninput="this.nextElementSibling.select()" value="i">
  <input name="pin2[]" maxlength=1 oninput="this.nextElementSibling.select()" value="m">
  <input name="pin2[]" maxlength=1 value="i">
</div>


答:
An easy solution to your problem is adding the argument use.initial.values = TRUE. This argument states that the same initial values are used for model.robets as for model.robets.retrain. That makes sense, since by default the initial values are estimated in a short startup period, which is the same for both time series.

The solution:

```<code>library(robets)
ts.train <- ts(c(60,209,51,34,208,64,122,99,82,194,136,177,110,332,300,151,128,206,129,92,164,814,1286,826,893,949,1014,830,877,605,773,870,1610,970,1192,1222,466,1963,841), start=c(20001, 1), frequency=12)
model.robets <- robets(ts.train)
ts.train.dev <- ts(c(60,209,51,34,208,64,122,99,82,194,136,177,110,332,300,151,128,206,129,92,164,814,1286,826,893,949,1014,830,877,605,773,870,1610,970,1192,1222,466,1963,841,830,812,160,238,53,760), start=c(20001, 1), frequency=12)
model.robets.retrain <- robets(ts.train.dev, model=model.robets, use.initial.values = TRUE)
</code>```

However, the error you describe should not happen. Therefore I changed the default setting, and I solved the bug you found. A new version of robets will soon appear on CRAN.

Title: Error in retraining ROBETS time series forecasting model in R

Body:
I am using the package ROBETS in R to make forecast. I need to re-train my model on a extended time series. Below is the MWE:

library(robets)
ts.train <- ts(c(60,209,51,34,208,64,122,99,82,194,136,177,110,332,300,151,128,206,129,92,164,814,1286,826,893,949,1014,830,877,605,773,870,1610,970,1192,1222,466,1963,841), start=c(20001, 1), frequency=12)
model.robets <- robets(ts.train)
ts.train.dev <- ts(c(60,209,51,34,208,64,122,99,82,194,136,177,110,332,300,151,128,206,129,92,164,814,1286,826,893,949,1014,830,877,605,773,870,1610,970,1192,1222,466,1963,841,830,812,160,238,53,760), start=c(20001, 1), frequency=12)
model.robets.retrain <- robets(ts.train.dev, model=model.robets)

I get the following error:

Error in robetsTargetFunctionInit(par = par, y = y, errortype = errortype,  :
  k Problem!

Body:
An easy solution to your problem is adding the argument use.initial.values = TRUE. This argument states that the same initial values are used for model.robets as for model.robets.retrain. That makes sense, since by default the initial values are estimated in a short startup period, which is the same for both time series.

The solution:

library(robets)
ts.train <- ts(c(60,209,51,34,208,64,122,99,82,194,136,177,110,332,300,151,128,206,129,92,164,814,1286,826,893,949,1014,830,877,605,773,870,1610,970,1192,1222,466,1963,841), start=c(20001, 1), frequency=12)
model.robets <- robets(ts.train)
ts.train.dev <- ts(c(60,209,51,34,208,64,122,99,82,194,136,177,110,332,300,151,128,206,129,92,164,814,1286,826,893,949,1014,830,877,605,773,870,1610,970,1192,1222,466,1963,841,830,812,160,238,53,760), start=c(20001, 1), frequency=12)
model.robets.retrain <- robets(ts.train.dev, model=model.robets, use.initial.values = TRUE)

However, the error you describe should not happen. Therefore I changed the default setting, and I solved the bug you found. A new version of robets will soon appear on CRAN.


问:
Updating the wxBitmap on wxBitmap
I'm using a single wxButton:

```<code>wxButtonAction::wxButtonAction(wxWindow* parent) : wxButton(parent,wxID_ANY) {
#if defined __WXMSW__
    wxIcon ms_icon(wxT("START_ICON"), wxBITMAP_TYPE_ICO_RESOURCE, 16, 16);
    wxBitmap button_bmp;
    button_bmp.CopyFromIcon(ms_icon);
#else
    wxFileName icon_path(DATA_DIR, wxT("start.ico"));
    wxBitmap button_bmp(icon_path.GetFullPath(), wxBITMAP_TYPE_ICO);
#endif
    SetLabel(_("&Start"));
    SetBitmap(button_bmp);
}
</code>```

The bitmaped button is show as expected. This method helps me change both bitmap and label when user clicks that button:

```<code>void wxButtonAction::updateOnAction(bool isRunning) {
#if defined __WXMSW__
    wxIcon ms_icon((isRunning) ? wxT("STOP_ICON") : wxT("START_ICON"), wxBITMAP_TYPE_ICO_RESOURCE, 16, 16);
    wxBitmap button_bmp;
    button_bmp.CopyFromIcon(ms_icon);
#else
    wxFileName icon_path(DATA_DIR, (!isRunning) ? wxT("stop.ico") : wxT("start.ico"));
    wxBitmap button_bmp(icon_path.GetFullPath(), wxBITMAP_TYPE_ICO);
#endif
    SetLabel((!isRunning) ? _("&Stop") : _("&Start"));
    SetBitmap(button_bmp);
}
</code>```

and now the resource file:

```<code>AAPP_ICON ICON DISCARDABLE "../data/app.ico"
ABOUT_ICON ICON "../data/about.ico"
CLOSE_ICON ICON "../data/close.ico"
START_ICON ICON "../data/start.ico"
STOP_ICON ICON "../data/stop.ico"

1 24 "../data/manifest.xml"
</code>```

The label is changed propertly when the user toggle clicking the button, but not the icon is always in "start" bitmap. I can confirm that all icons exists in the same  folder

答:
You don't need to use CopyFromIcon() at all, there is an implicit conversion from wxIcon to wxBitmap under MSW (because under the other platforms they're exactly the same thing). This being said, calling it explicitly should still work, so it's not clear what the problem is.

I'd like to recommend two other things: first, prefer using PNG (with real alpha transparency) to ICO nowadays. You might find wxBITMAP_PNG() useful to avoid the preprocessor checks, too.

Second, remove the manifest line from your .rc file and add #include "wx/msw/wx.rc" instead. This will do the right thing for the manifest and also define other stuff needed by wxWidgets applications.

Title: Updating the wxBitmap on wxBitmap

Body:
I'm using a single wxButton:

wxButtonAction::wxButtonAction(wxWindow* parent) : wxButton(parent,wxID_ANY) {
#if defined __WXMSW__
    wxIcon ms_icon(wxT("START_ICON"), wxBITMAP_TYPE_ICO_RESOURCE, 16, 16);
    wxBitmap button_bmp;
    button_bmp.CopyFromIcon(ms_icon);
#else
    wxFileName icon_path(DATA_DIR, wxT("start.ico"));
    wxBitmap button_bmp(icon_path.GetFullPath(), wxBITMAP_TYPE_ICO);
#endif
    SetLabel(_("&Start"));
    SetBitmap(button_bmp);
}

The bitmaped button is show as expected. This method helps me change both bitmap and label when user clicks that button:

void wxButtonAction::updateOnAction(bool isRunning) {
#if defined __WXMSW__
    wxIcon ms_icon((isRunning) ? wxT("STOP_ICON") : wxT("START_ICON"), wxBITMAP_TYPE_ICO_RESOURCE, 16, 16);
    wxBitmap button_bmp;
    button_bmp.CopyFromIcon(ms_icon);
#else
    wxFileName icon_path(DATA_DIR, (!isRunning) ? wxT("stop.ico") : wxT("start.ico"));
    wxBitmap button_bmp(icon_path.GetFullPath(), wxBITMAP_TYPE_ICO);
#endif
    SetLabel((!isRunning) ? _("&Stop") : _("&Start"));
    SetBitmap(button_bmp);
}

and now the resource file:

AAPP_ICON ICON DISCARDABLE "../data/app.ico"
ABOUT_ICON ICON "../data/about.ico"
CLOSE_ICON ICON "../data/close.ico"
START_ICON ICON "../data/start.ico"
STOP_ICON ICON "../data/stop.ico"

1 24 "../data/manifest.xml"

The label is changed propertly when the user toggle clicking the button, but not the icon is always in "start" bitmap. I can confirm that all icons exists in the same  folder