问:
If x = 1:10 and y = list(x,x), then the memory size of y is equivalent to two times the memory size of x
If x = 1:10 and y = list(x,x), then the memory size of y is equivalent to two times the memory size of x.

This is one of my r homework question, but I cannot figure out why this is false.

```<code>> x=10
> x=1:10
> list(x,x)
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
 [1]  1  2  3  4  5  6  7  8  9 10
</code>```

答:
you can use object.size function to report the space allocated for an object

```<code>x <- 1:10
y <- list(x,x)

object.size(x)
88 bytes
object.size(y)
232 bytes
</code>```

Body:
If x = 1:10 and y = list(x,x), then the memory size of y is equivalent to two times the memory size of x.

This is one of my r homework question, but I cannot figure out why this is false.

> x=10
> x=1:10
> list(x,x)
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10

[[2]]
 [1]  1  2  3  4  5  6  7  8  9 10

Body:
you can use object.size function to report the space allocated for an object

x <- 1:10
y <- list(x,x)

object.size(x)
88 bytes
object.size(y)
232 bytes


来源: stackexchange

问:
how to convert x-www-form-urlencoded payload to json
i am using the npm request module to post data.
by default the posy is of x-www-form-urlencoded
so on the server side i am receiving the data like this

```<code>{
  'files[0][path]': 'myfile1',
  'files[0][contents]': 'some content',
  'files[0][active]': 'true'
}
</code>```

how do i parse the data to json?
like

```<code>{
  files: [{
    path: 'mypath',
    content: 'mycontent',
    active: true
  } {
    path: 'mypath2',
    content: 'mycontent2',
    active: false
  }]
}
</code>```

I think express js might use a middle wire for this, but I am using hapi server.
what are my options to parse the payload to json?

答: There are a number of existing node packages that deal with parsing requests. Check out https://www.npmjs.com/package/body-parser-json. To write a solution from scratch would just be a waste of time.</p>

ContentLicense: CC BY-SA 3.0

Body:
i am using the npm request module to post data.
by default the posy is of x-www-form-urlencoded
so on the server side i am receiving the data like this

{
  'files[0][path]': 'myfile1',
  'files[0][contents]': 'some content',
  'files[0][active]': 'true'
}

how do i parse the data to json?
like

{
  files: [{
    path: 'mypath',
    content: 'mycontent',
    active: true
  } {
    path: 'mypath2',
    content: 'mycontent2',
    active: false
  }]
}

I think express js might use a middle wire for this, but I am using hapi server.
what are my options to parse the payload to json?


问:
Flickering when repainting java
This is my paint code. I know I should use a buffer but I don't understand how to use it on my code and what it does so please can you help by explaining what it is and what it does and/or edit my code so it can stop flickering thank you.</p>

```<code> public void paint(Graphics g ) {
    g.fillRect(BulletX, BulletY,0,0);
    g.setColor(Color.yellow);
    try{
    FileInputStream saveFile = new FileInputStream("Wins1.sav");
    ObjectInputStream save = new ObjectInputStream(saveFile);

    wins1 = (int) save.readObject();

    save.close();
    }
    catch(Exception exc){
    exc.printStackTrace();
    }
    Image image;
    URL resource = getClass().getClassLoader().getResource("moon1.jpg");
       URL resource1 = getClass().getClassLoader().getResource("Tank.jpg");
       URL resource2 = getClass().getClassLoader().getResource("Tank2.jpg");

       ImageIcon i2 = new ImageIcon(resource);
        ImageIcon i1 = new ImageIcon(resource1);
        ImageIcon i3 = new ImageIcon(resource2);
    image = i2.getImage();
        g.drawImage(image, 0,0,null);
        if (SHOW.equals("ON")){
        g.setFont(new Font("TimesRoman", Font.BOLD, 30));
        g.drawString("Player 1's health ="+Integer.toString(Player1H), 50, 25);}
    if (wins == 1){
        g.setColor(Color.BLACK);
        g.fillOval(20, 10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins == 2){
        g.setColor(Color.BLACK);
        g.fillOval(20, 10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 60,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins == 3){
        g.setColor(Color.BLACK);
        g.fillOval(20, 10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 60,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 100,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins == 4){
        g.setColor(Color.BLACK);
        g.fillOval(20, 10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 60,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 100,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval(140,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins1 == 1){
        g.setColor(Color.BLACK);
        g.fillOval( 360,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins1 == 2){
        g.setColor(Color.BLACK);
        g.fillOval( 360,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 400,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins1 == 3){
        g.setColor(Color.BLACK);
        g.fillOval( 360,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 400,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 480,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins1 == 4){
        g.setColor(Color.BLACK);
        g.fillOval( 360,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 400,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 480,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 520,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    image = i1.getImage();
    g.drawImage(image,myX, myY,null);
    image = i3.getImage();
    g.setColor(Color.blue);
    if (Boss == 1){
        g.setColor(Color.RED);
        g.fillOval(myX1, myY1, 50, 50);
         try {
        Thread.sleep(800);
    } catch (InterruptedException ex) {
        Logger.getLogger(onePlayer1.class.getName()).log(Level.SEVERE, null, ex);
    }
         Boss = 2;
        win();
    }

    g.drawImage(image,myX1, myY1,null);

    if (hit2 ==1){
        g.setColor(Color.red);
        hit2 =0;
        g.fillOval(myX1, myY1, 20, 20);

        try {
        Thread.sleep(200);
    } catch (InterruptedException ex) {
        Logger.getLogger(onePlayer1.class.getName()).log(Level.SEVERE, null, ex);
    }
        repaint();
    }
    if (hit1 ==1){
        g.setColor(Color.red);
        hit1 =0;
        g.fillOval(myX, myY, 20, 20);

        try {
        Thread.sleep(200);
    } catch (InterruptedException ex) {
        Logger.getLogger(onePlayer1.class.getName()).log(Level.SEVERE, null, ex);
    }
        repaint();
    }
    if (Explode == true){
        g.setColor(Color.RED);
        g.fillOval(myX11,myY11,40,40);
        number = 0;
        Explode = false;
        myX11 = -10;
        myY11 = -10;
        Player3H = 0;

        try {
        Thread.sleep(800);
    } catch (InterruptedException ex) {
        Logger.getLogger(onePlayer1.class.getName()).log(Level.SEVERE, null, ex);
    }
        repaint();
    }
    if (number ==11){
        URL resource3 = getClass().getClassLoader().getResource("Dynamite.jpg");
        ImageIcon i4 = new ImageIcon(resource3);
        image = i4.getImage();
        g.setColor(Color.GREEN);
                g.drawImage(image,myX11, myY11,null);
    }
    if (number == 1){

        g.setColor(Color.GREEN);
        myX11 = myX1+10;
        myY11 = myY1+10;
                g.drawImage(image,myX11, myY11,null);
        number =11;
        Player3H = 10;
        repaint();
    }
    g.setColor(Color.BLACK);
    if (fire1.equals("Yes")){

        if (aim1.equals("right")){
        BulletY1 = myY1;
        BulletX1 = myX1;

        g.fillRect(BulletX1, BulletY1, 1000, 5);

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire1="no";
        repaint();}
        if (aim1.equals("down")){
        BulletY1 = myY1;
        BulletX1 = myX1;
        g.fillRect(BulletX1, BulletY1, 5, 1000);

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire1="no";
        repaint();}
        if (aim1.equals("left")){
        BulletY1 = myY1;
        BulletX1 = myX1-1000;
        g.fillRect(BulletX1, BulletY1, 1000,5);
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire1="no";
        repaint();}
        if (aim1.equals("up")){

        BulletY1 = myY1-1000;
        BulletX1 = myX1;
        g.fillRect(BulletX1, BulletY1, 5, 1000);

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire1="no";
        repaint();}}
    if (fire.equals("Yes")){

        if (aim.equals("right")){
        BulletY = myY;
        BulletX = myX;
        BulletXX = myX+10;
        BulletYY = myY+10;

        g.fillRect(BulletXX, BulletYY, 1000, 5);
        g.fillRect(BulletX, BulletY, 1000, 5);

        fire="no";

            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                Logger.getLogger(onePlayer1.class.getName()).log(Level.SEVERE, null, ex);
            }
        repaint();}
        if (aim.equals("down")){
        BulletY = myY;
        BulletX = myX;
        BulletXX = myX+10;
        BulletYY = myY+10;

        g.fillRect(BulletXX, BulletYY, 5, 1000);
        g.fillRect(BulletX, BulletY, 5, 1000);

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire="no";
        repaint();}
        if (aim.equals("left")){
        BulletY = myY;
        BulletX = myX-1000;
         BulletXX = myX-990;
         BulletYY = myY+10;

        g.fillRect(BulletXX, BulletYY, 1000, 5);
        g.fillRect(BulletX, BulletY, 1000,5);
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire="no";
        repaint();}
        if (aim.equals("up")){

        BulletY = myY-1000;
        BulletX = myX;
         BulletXX = myX+10;
         BulletYY = myY-990;

        g.fillRect(BulletXX, BulletYY, 5, 1000);
        g.fillRect(BulletX, BulletY, 5, 1000);

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }
        g.fillRect(BulletX, BulletY, 0, 0);
        fire="no";
        repaint();}}}
</code>```

答:
Your code is sooo long, no one wants to debug it, but I find in a quick check that you have some errors in it:

public void paint(Graphics g ) { You should NEVER override paint(...) method but paintComponent(...), as Swing components are double-buffered (as explained by @Radiodef in his answer):

Swing ensures that the appropriate type of Graphics object (offscreen image Graphics for double-buffering, regular Graphics otherwise) is passed to the component's paint callback, so all the component needs to do is draw with it

I'm going to guess that the only reason you're using this method is because you're extending JFrame, and you should extend JPanel instead and build your GUI based on them, as a JFrame is a rigid container, read more here: Extends JFrame vs. creating it inside the program

You're not calling super.paint(g); (Or if following above recommendation super.paintComponent(g); as the first line in the method... that could break the paint chain

Reading files inside the painting methods could be the reason your program is flickering as it adds processing time and lag, these lines:

```<code>FileInputStream saveFile = new FileInputStream("Wins1.sav");
ObjectInputStream save = new ObjectInputStream(saveFile);
...
//until this line
image = i2.getImage();
</code>```

would be better placed at constructor level , paint methods should paint and only that, as painting methods are called several times (everytime you move your mouse over the GUI it gets repainted, so it's loading resources everytime)

Thread.sleep(...); You're blocking the Event Dispatch Thread, so that's probably another reason your program is flickering, you should instead use a Swing Timer to do peridic tasks

Boss = 2;, Explode == true You're not following Java naming conventions:

FirstWordUpperCaseClass

firstWordLowerCaseVariable

firstWordLowerCaseMethod()

ALL_WORDS_UPPER_CASE_CONSTANT

You're calling repaint(); several times inside the paint(...) method! That's another reason as it's a recursive call everytime...

if (Explode == true), can be written as if (explode) which will prevent typos like this one if (explode = true)

Your code is not correctly indented and thus it's hard to read

If you follow all the above recommendations and still have problems, consider posting a valid Minimal, Complete and Verifiable Example that demonstrates the problem, it should be short but still complete and compilable

Title: Flickering when repainting java

Body:
This is my paint code. I know I should use a buffer but I don't understand how to use it on my code and what it does so please can you help by explaining what it is and what it does and/or edit my code so it can stop flickering thank you.

 public void paint(Graphics g ) {
    g.fillRect(BulletX, BulletY,0,0);
    g.setColor(Color.yellow);
    try{
    FileInputStream saveFile = new FileInputStream("Wins1.sav");
    ObjectInputStream save = new ObjectInputStream(saveFile);

    wins1 = (int) save.readObject();

    save.close();
    }
    catch(Exception exc){
    exc.printStackTrace();
    }
    Image image;
    URL resource = getClass().getClassLoader().getResource("moon1.jpg");
       URL resource1 = getClass().getClassLoader().getResource("Tank.jpg");
       URL resource2 = getClass().getClassLoader().getResource("Tank2.jpg");

       ImageIcon i2 = new ImageIcon(resource);
        ImageIcon i1 = new ImageIcon(resource1);
        ImageIcon i3 = new ImageIcon(resource2);
    image = i2.getImage();
        g.drawImage(image, 0,0,null);
        if (SHOW.equals("ON")){
        g.setFont(new Font("TimesRoman", Font.BOLD, 30));
        g.drawString("Player 1's health ="+Integer.toString(Player1H), 50, 25);}
    if (wins == 1){
        g.setColor(Color.BLACK);
        g.fillOval(20, 10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins == 2){
        g.setColor(Color.BLACK);
        g.fillOval(20, 10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 60,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins == 3){
        g.setColor(Color.BLACK);
        g.fillOval(20, 10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 60,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 100,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins == 4){
        g.setColor(Color.BLACK);
        g.fillOval(20, 10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 60,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 100,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval(140,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins1 == 1){
        g.setColor(Color.BLACK);
        g.fillOval( 360,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins1 == 2){
        g.setColor(Color.BLACK);
        g.fillOval( 360,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 400,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins1 == 3){
        g.setColor(Color.BLACK);
        g.fillOval( 360,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 400,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 480,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    if (wins1 == 4){
        g.setColor(Color.BLACK);
        g.fillOval( 360,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 400,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 480,10, 30, 30);
        g.setColor(Color.BLACK);
        g.fillOval( 520,10, 30, 30);
        g.setColor(Color.YELLOW);
    }
    image = i1.getImage();
    g.drawImage(image,myX, myY,null);
    image = i3.getImage();
    g.setColor(Color.blue);
    if (Boss == 1){
        g.setColor(Color.RED);
        g.fillOval(myX1, myY1, 50, 50);
         try {
        Thread.sleep(800);
    } catch (InterruptedException ex) {
        Logger.getLogger(onePlayer1.class.getName()).log(Level.SEVERE, null, ex);
    }
         Boss = 2;
        win();
    }

    g.drawImage(image,myX1, myY1,null);

    if (hit2 ==1){
        g.setColor(Color.red);
        hit2 =0;
        g.fillOval(myX1, myY1, 20, 20);

        try {
        Thread.sleep(200);
    } catch (InterruptedException ex) {
        Logger.getLogger(onePlayer1.class.getName()).log(Level.SEVERE, null, ex);
    }
        repaint();
    }
    if (hit1 ==1){
        g.setColor(Color.red);
        hit1 =0;
        g.fillOval(myX, myY, 20, 20);

        try {
        Thread.sleep(200);
    } catch (InterruptedException ex) {
        Logger.getLogger(onePlayer1.class.getName()).log(Level.SEVERE, null, ex);
    }
        repaint();
    }
    if (Explode == true){
        g.setColor(Color.RED);
        g.fillOval(myX11,myY11,40,40);
        number = 0;
        Explode = false;
        myX11 = -10;
        myY11 = -10;
        Player3H = 0;

        try {
        Thread.sleep(800);
    } catch (InterruptedException ex) {
        Logger.getLogger(onePlayer1.class.getName()).log(Level.SEVERE, null, ex);
    }
        repaint();
    }
    if (number ==11){
        URL resource3 = getClass().getClassLoader().getResource("Dynamite.jpg");
        ImageIcon i4 = new ImageIcon(resource3);
        image = i4.getImage();
        g.setColor(Color.GREEN);
                g.drawImage(image,myX11, myY11,null);
    }
    if (number == 1){

        g.setColor(Color.GREEN);
        myX11 = myX1+10;
        myY11 = myY1+10;
                g.drawImage(image,myX11, myY11,null);
        number =11;
        Player3H = 10;
        repaint();
    }
    g.setColor(Color.BLACK);
    if (fire1.equals("Yes")){

        if (aim1.equals("right")){
        BulletY1 = myY1;
        BulletX1 = myX1;

        g.fillRect(BulletX1, BulletY1, 1000, 5);

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire1="no";
        repaint();}
        if (aim1.equals("down")){
        BulletY1 = myY1;
        BulletX1 = myX1;
        g.fillRect(BulletX1, BulletY1, 5, 1000);

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire1="no";
        repaint();}
        if (aim1.equals("left")){
        BulletY1 = myY1;
        BulletX1 = myX1-1000;
        g.fillRect(BulletX1, BulletY1, 1000,5);
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire1="no";
        repaint();}
        if (aim1.equals("up")){

        BulletY1 = myY1-1000;
        BulletX1 = myX1;
        g.fillRect(BulletX1, BulletY1, 5, 1000);

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire1="no";
        repaint();}}
    if (fire.equals("Yes")){

        if (aim.equals("right")){
        BulletY = myY;
        BulletX = myX;
        BulletXX = myX+10;
        BulletYY = myY+10;

        g.fillRect(BulletXX, BulletYY, 1000, 5);
        g.fillRect(BulletX, BulletY, 1000, 5);

        fire="no";

            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                Logger.getLogger(onePlayer1.class.getName()).log(Level.SEVERE, null, ex);
            }
        repaint();}
        if (aim.equals("down")){
        BulletY = myY;
        BulletX = myX;
        BulletXX = myX+10;
        BulletYY = myY+10;

        g.fillRect(BulletXX, BulletYY, 5, 1000);
        g.fillRect(BulletX, BulletY, 5, 1000);

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire="no";
        repaint();}
        if (aim.equals("left")){
        BulletY = myY;
        BulletX = myX-1000;
         BulletXX = myX-990;
         BulletYY = myY+10;

        g.fillRect(BulletXX, BulletYY, 1000, 5);
        g.fillRect(BulletX, BulletY, 1000,5);
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }

        fire="no";
        repaint();}
        if (aim.equals("up")){

        BulletY = myY-1000;
        BulletX = myX;
         BulletXX = myX+10;
         BulletYY = myY-990;

        g.fillRect(BulletXX, BulletYY, 5, 1000);
        g.fillRect(BulletX, BulletY, 5, 1000);

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(HandlingEvents.class.getName()).log(Level.SEVERE, null, ex);
        }
        g.fillRect(BulletX, BulletY, 0, 0);
        fire="no";
        repaint();}}}

Body:
Your code is sooo long, no one wants to debug it, but I find in a quick check that you have some errors in it:

public void paint(Graphics g ) { You should NEVER override paint(...) method but paintComponent(...), as Swing components are double-buffered (as explained by @Radiodef in his answer):

Swing ensures that the appropriate type of Graphics object (offscreen image Graphics for double-buffering, regular Graphics otherwise) is passed to the component's paint callback, so all the component needs to do is draw with it

I'm going to guess that the only reason you're using this method is because you're extending JFrame, and you should extend JPanel instead and build your GUI based on them, as a JFrame is a rigid container, read more here: Extends JFrame vs. creating it inside the program

You're not calling super.paint(g); (Or if following above recommendation super.paintComponent(g); as the first line in the method... that could break the paint chain

Reading files inside the painting methods could be the reason your program is flickering as it adds processing time and lag, these lines:

FileInputStream saveFile = new FileInputStream("Wins1.sav");
ObjectInputStream save = new ObjectInputStream(saveFile);
...
//until this line
image = i2.getImage();

would be better placed at constructor level , paint methods should paint and only that, as painting methods are called several times (everytime you move your mouse over the GUI it gets repainted, so it's loading resources everytime)

Thread.sleep(...); You're blocking the Event Dispatch Thread, so that's probably another reason your program is flickering, you should instead use a Swing Timer to do peridic tasks

Boss = 2;, Explode == true You're not following Java naming conventions:

FirstWordUpperCaseClass

firstWordLowerCaseVariable

firstWordLowerCaseMethod()

ALL_WORDS_UPPER_CASE_CONSTANT

You're calling repaint(); several times inside the paint(...) method! That's another reason as it's a recursive call everytime...

if (Explode == true), can be written as if (explode) which will prevent typos like this one if (explode = true)

Your code is not correctly indented and thus it's hard to read

If you follow all the above recommendations and still have problems, consider posting a valid Minimal, Complete and Verifiable Example that demonstrates the problem, it should be short but still complete and compilable


问:
Keras CNN for multiclass categorical crossentropy loss function
This is my code i typed to classify some classes consisting of birds, dogs and cats. Its the same code for the binary classification but when I add another class and changed the loss function of compile method to use categorical_Crossentropy, it gives me the following error ( => at the end of the code ). can anyone explain what is the issue here or the mistake I have made ?

```<code># Importing Keras and Tensorflow modules

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenerator
from keras.models import load_model
from keras.utils.np_utils import to_categorical
import os.path

# Initilize the CNN

classifier = Sequential()
# Step 1 - Convolution

classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

# Step 2 - Pooling

classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 2(b) - Add 2nd Convolution Layer making it Deep followed by a Pooling Layer

classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 3 - Flattening

classifier.add(Flatten())

# Step 4 - Fully Connected Neural Network

# Hidden Layer - Activation Function RELU
classifier.add(Dense(units = 128, activation = 'relu'))
# Output Layer - Activation Function Softmax(to clasify multiple classes)
classifier.add(Dense(units = 1, activation = 'softmax'))

# Compile the CNN

# Categorical Crossentropy - to classify between multiple classes of images
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy',
metrics = ['accuracy'])

# Image Augmentation and Training Section

# Image Augmentation to prevent Overfitting (Applying random transformation on
images to train set.ie.
# scalling, rotating and streching)

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory(
        'dataset/training_set',
        target_size=(64, 64),
        batch_size=8,
        class_mode='categorical')

test_set = test_datagen.flow_from_directory(
        'dataset/test_set',
        target_size=(64, 64),
        batch_size=8,
        class_mode='categorical')

#Fit the clasifier on the CNN data
if(os.path.isfile('my_model.h5') == False):
    classifier.fit_generator(
            training_set,
            steps_per_epoch=8000,
            epochs=2,
            validation_data=test_set,
            validation_steps=2000
                                  )
# Save the generated model to my_model.h5
classifier.save('my_model.h5')
else:
    classifier = load_model('my_model.h5')
</code>```

答:
You need to have one neuron per class on your last (Dense) layer.

```<code>classifier.add(Dense(3))
</code>```

Right now you have only one neuron and by that your network is still setup for only two classes.

Body:
This is my code i typed to classify some classes consisting of birds, dogs and cats. Its the same code for the binary classification but when I add another class and changed the loss function of compile method to use categorical_Crossentropy, it gives me the following error ( => at the end of the code ). can anyone explain what is the issue here or the mistake I have made ?

# Importing Keras and Tensorflow modules

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenerator
from keras.models import load_model
from keras.utils.np_utils import to_categorical
import os.path

# Initilize the CNN

classifier = Sequential()
# Step 1 - Convolution

classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

# Step 2 - Pooling

classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 2(b) - Add 2nd Convolution Layer making it Deep followed by a Pooling Layer

classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 3 - Flattening

classifier.add(Flatten())

# Step 4 - Fully Connected Neural Network

# Hidden Layer - Activation Function RELU
classifier.add(Dense(units = 128, activation = 'relu'))
# Output Layer - Activation Function Softmax(to clasify multiple classes)
classifier.add(Dense(units = 1, activation = 'softmax'))

# Compile the CNN

# Categorical Crossentropy - to classify between multiple classes of images
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy',
metrics = ['accuracy'])

# Image Augmentation and Training Section

# Image Augmentation to prevent Overfitting (Applying random transformation on
images to train set.ie.
# scalling, rotating and streching)

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory(
        'dataset/training_set',
        target_size=(64, 64),
        batch_size=8,
        class_mode='categorical')

test_set = test_datagen.flow_from_directory(
        'dataset/test_set',
        target_size=(64, 64),
        batch_size=8,
        class_mode='categorical')

#Fit the clasifier on the CNN data
if(os.path.isfile('my_model.h5') == False):
    classifier.fit_generator(
            training_set,
            steps_per_epoch=8000,
            epochs=2,
            validation_data=test_set,
            validation_steps=2000
                                  )
# Save the generated model to my_model.h5
classifier.save('my_model.h5')
else:
    classifier = load_model('my_model.h5')

Body:
You need to have one neuron per class on your last (Dense) layer.

classifier.add(Dense(3))

Right now you have only one neuron and by that your network is still setup for only two classes.


问:
SQL Generating combinations of columns
I have a bunch of columns in an SQL Table. What I would like to do is return all possible combinations of the entries in my table, so: let's say column 1 has "Cat, Dog, Horse", and column 2 has "Red, Green, Blue", I would like to return a table that says:

```<code>Cat Red
Cat Green
Cat Blue
Dog Red
Dog Green
Dog Blue
Horse Red
Horse Green
Horse Blue
</code>```

and so on.

How could I accomplish this in SQL-Server?

Thanks. I should mention that some of the columns contain different types, so I don't think union would work!

答:
That's called a cross join.

Exemple query :

```<code>SELECT table1.column1, table2.column2 FROM table1 CROSS JOIN table2
</code>```

It should produce the result you expect.

If you have a single table (like in your case) you can use aliases like this

```<code>SELECT table1.column1, table2.column2 FROM table1 CROSS JOIN table1 as table2
</code>```

Title: SQL Generating combinations of columns

Body:
I have a bunch of columns in an SQL Table. What I would like to do is return all possible combinations of the entries in my table, so: let's say column 1 has "Cat, Dog, Horse", and column 2 has "Red, Green, Blue", I would like to return a table that says:

Cat Red
Cat Green
Cat Blue
Dog Red
Dog Green
Dog Blue
Horse Red
Horse Green
Horse Blue

and so on.

How could I accomplish this in SQL-Server?

Thanks. I should mention that some of the columns contain different types, so I don't think union would work!

Body:
That's called a cross join.

Exemple query :

SELECT table1.column1, table2.column2 FROM table1 CROSS JOIN table2

It should produce the result you expect.

If you have a single table (like in your case) you can use aliases like this

SELECT table1.column1, table2.column2 FROM table1 CROSS JOIN table1 as table2


问:
DateTime.Value = ds.Tables[0].Rows[0][3].ToString("yyyy/MM/dd");
I want to assign the value coming from database into dataset and then to the DateTime in My code Can Anyone Fix my Code For That... </p>

答:
Without testing it out myself, you might want to consider something like this:

```<code>DateTime dt = Convert.ToDateTime(ds.Tables[0].Rows[0][3].ToString());
</code>```

Please note that some defensive programming caution should be applied, such as making sure the data format in the row is valid.

Body:
Without testing it out myself, you might want to consider something like this:

DateTime dt = Convert.ToDateTime(ds.Tables[0].Rows[0][3].ToString());

Please note that some defensive programming caution should be applied, such as making sure the data format in the row is valid.


问:
How to retrieve JSON using retrofit with headers?
Situation: I have an API token and want to get json data. But that token has to be used as header,not as query parametr. As I've understood I couldn't type on my browser request with header. For more information about API that I use,you can look there: https://developer.fantasydata.com/docs/services/594407b00f14bf15264fd958/operations/5944088b14338d0eb80b2809

Problem: Because of I do not know what kind of fields does JSON request have ,I cannot create a class for that json data. I want to use JacksonConverter. So the question is: how to get that JSON and look how it looks like,then create a class for that in order to convert?

Below you can see my code with understandable comments:

My PrefsApplication class for creating http request:

```<code>public class PrefsApplication extends Application {
    private static Retrofit retrofit = null;

    static String base = "https://api.fantasydata.net/v3/soccer/scores/"; // my base url

    public static Retrofit getClient() {
        if(retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(base).addConverterFactory(JacksonConverterFactory.create()).build();
        }
        return retrofit;
    }
}
</code>```

My interface for doing get request and putting header

```<code>public interface RestInterface {
    @Headers("Ocp-Apim-Subscription-Key: {MY_KEY}") // here is header, I don't know is it properly written?
    @GET("scores/json/Areas") // my get request
    Call<List<Country>> getCountries(); // here, I want to get list of countries
}
</code>```

There is MainActivity:

```<code>public class MainActivity extends AppCompatActivity  {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RestInterface rest = PrefsApplication.getClient().create(RestInterface.class);

        Call<List<Country>>call = rest.getCountries();
        call.enqueue(new Callback<List<Country>>() {
            @Override
            public void onResponse(Call<List<Country>> call, Response<List<Country>> response) { }

            @Override
            public void onFailure(Call<List<Country>> call, Throwable t) { }
        });
    }
}
</code>```

答:
You need to add an interceptor to your Retrofit HttpClient instance. This way you can setup custom headers.

A quick example is:

```<code>private static final String API_URL = "URL"; // Override with the service URL
private static final String YOUR_KEY = "KEY"; // Override with your key from the service

private static Retrofit.Builder retrofit = new Retrofit.Builder().baseUrl(API_URL);
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

public static RestInterface endpoint() {
    httpClient.interceptors().clear();

    httpClient.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();

            Request.Builder requestBuilder = original.newBuilder()
                    .header("Ocp-Apim-Subscription-Key", YOUR_KEY)
                    .method(original.method(), original.body());

            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });

    return retrofit.client(httpClient.build()).build().create(RestInterface.class);
}

// Then call to use a Retrofit instance with the headers
PrefsApplication.endpoint().getCountries();
</code>```

This is used in all sorts of ways, like adding authentication. You can read more about it in this complete guide for Retrofit

This example is for Retrofit 2+ so be sure to add compile 'com.squareup.retrofit2:retrofit:2.1.0' to your dependencies.

Body:
Situation: I have an API token and want to get json data. But that token has to be used as header,not as query parametr. As I've understood I couldn't type on my browser request with header. For more information about API that I use,you can look there: https://developer.fantasydata.com/docs/services/594407b00f14bf15264fd958/operations/5944088b14338d0eb80b2809

Problem: Because of I do not know what kind of fields does JSON request have ,I cannot create a class for that json data. I want to use JacksonConverter. So the question is: how to get that JSON and look how it looks like,then create a class for that in order to convert?

Below you can see my code with understandable comments:

My PrefsApplication class for creating http request:

public class PrefsApplication extends Application {
    private static Retrofit retrofit = null;

    static String base = "https://api.fantasydata.net/v3/soccer/scores/"; // my base url

    public static Retrofit getClient() {
        if(retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl(base).addConverterFactory(JacksonConverterFactory.create()).build();
        }
        return retrofit;
    }
}

My interface for doing get request and putting header

public interface RestInterface {
    @Headers("Ocp-Apim-Subscription-Key: {MY_KEY}") // here is header, I don't know is it properly written?
    @GET("scores/json/Areas") // my get request
    Call<List<Country>> getCountries(); // here, I want to get list of countries
}

There is MainActivity:

public class MainActivity extends AppCompatActivity  {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RestInterface rest = PrefsApplication.getClient().create(RestInterface.class);

        Call<List<Country>>call = rest.getCountries();
        call.enqueue(new Callback<List<Country>>() {
            @Override
            public void onResponse(Call<List<Country>> call, Response<List<Country>> response) { }

            @Override
            public void onFailure(Call<List<Country>> call, Throwable t) { }
        });
    }
}

Body:
You need to add an interceptor to your Retrofit HttpClient instance. This way you can setup custom headers.

A quick example is:

private static final String API_URL = "URL"; // Override with the service URL
private static final String YOUR_KEY = "KEY"; // Override with your key from the service

private static Retrofit.Builder retrofit = new Retrofit.Builder().baseUrl(API_URL);
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

public static RestInterface endpoint() {
    httpClient.interceptors().clear();

    httpClient.addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();

            Request.Builder requestBuilder = original.newBuilder()
                    .header("Ocp-Apim-Subscription-Key", YOUR_KEY)
                    .method(original.method(), original.body());

            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });

    return retrofit.client(httpClient.build()).build().create(RestInterface.class);
}

// Then call to use a Retrofit instance with the headers
PrefsApplication.endpoint().getCountries();

This is used in all sorts of ways, like adding authentication. You can read more about it in this complete guide for Retrofit

This example is for Retrofit 2+ so be sure to add compile 'com.squareup.retrofit2:retrofit:2.1.0' to your dependencies.


答:
Swing components are already double-buffered by default. You're overriding paint which subverts that mechanism. If you override paintComponent instead (as we ought to do when painting in Swing), then painting will be double-buffered automatically.

However:

You're reading files in paint, which you shouldn't be doing. This makes your painting very inefficient, to the point where the low frame rate will likely be obviously noticeable. Instead, you should load your files once when the program first starts and put the resources somewhere you can easily reference from within the program.

You're calling Thread.sleep in paint which freezes the GUI. Swing program should use a Timer instead.

You're calling repaint() recursively which floods the event queue with paint events and starts an infinite loop which you don't have control over. Using a Timer is far, far better.

If you want to learn how to write simple games with Swing, you might take a look at these two answers of mine: https://stackoverflow.com/a/44371593/2891664, https://stackoverflow.com/a/30175751/2891664.

Title: Flickering when repainting java


问:
Remove certain html tags from text based content
I'm using CKE text editor  http://ckeditor.com on my web site.

When user create content using this text editor, text  may have paragraphs, bullet lists, headers with different sizes etc... and all content is stored in mysql database as HTML format...So, when text is displayed from database, let say on home page as a featured article, it is displayed in same form as user stored it to db, so it causes aesthetics problems
I want to know the best way to remove html tags from text string with PHP or Javacript  and leave just text, because I dont wanna manualy  type all possible html tags with str_replace() function. Thanks in advance

答:
You're after PHP's strip_tags function. This removes both HTML and PHP tags from a string. Reference page: http://php.net/manual/en/function.strip-tags.php

Example:

```<code>$text = "<p>My string</p>";
echo strip_tags($text); //This would print "My string"
</code>```

Body:
You're after PHP's strip_tags function. This removes both HTML and PHP tags from a string. Reference page: http://php.net/manual/en/function.strip-tags.php

Example:

$text = "<p>My string</p>";
echo strip_tags($text); //This would print "My string"


问:
c++ if else statement won't go right pathway for text adventure game, always goes to the same Void Function
I have c++ issues.
On a text adventure game I am making, and on a part where I have choices for different options on what to do in a house, every choice I make always goes to the void Sleep() function:

```<code>void Home()
{
    cout << "\nYou are in the living room of your rented home. Everything looks nice and tidy." << endl;
    cout << "Choices:" << endl;
    cout << "Sleep" << endl;
    cout << "Leave" << endl;
    cout << "Stats" << endl;
    cin >> choice;

    if (choice == "Sleep" || "sleep")
    {
        Sleep(); // No matter what choice I make, it always
        //goes to the Sleep(); void.
    }
    if (choice == "Leave" || choice == "leave"){
        TownSquare();
    } if (choice == "Stats" || choice == "stats") {
        StatsH();
    }
    else {
        cout << "Please choose correctly!" << endl;
        Home();
    }
}
</code>```

All help will be much appreciated. Thank you!

答:
Your line:

```<code>if (choice == "Sleep" || "sleep")
</code>```

Evaluates as:

```<code>if ((choice == "Sleep") || "sleep")
</code>```

Which is always true since "sleep" will always trigger. You may want to make a proper look-up table here and force the input as lower-case if that's a concern.

Body:
I have c++ issues.
On a text adventure game I am making, and on a part where I have choices for different options on what to do in a house, every choice I make always goes to the void Sleep() function:

void Home()
{
    cout << "\nYou are in the living room of your rented home. Everything looks nice and tidy." << endl;
    cout << "Choices:" << endl;
    cout << "Sleep" << endl;
    cout << "Leave" << endl;
    cout << "Stats" << endl;
    cin >> choice;

    if (choice == "Sleep" || "sleep")
    {
        Sleep(); // No matter what choice I make, it always
        //goes to the Sleep(); void.
    }
    if (choice == "Leave" || choice == "leave"){
        TownSquare();
    } if (choice == "Stats" || choice == "stats") {
        StatsH();
    }
    else {
        cout << "Please choose correctly!" << endl;
        Home();
    }
}

All help will be much appreciated. Thank you!

Body:
Your line:

if (choice == "Sleep" || "sleep")

Evaluates as:

if ((choice == "Sleep") || "sleep")

Which is always true since "sleep" will always trigger. You may want to make a proper look-up table here and force the input as lower-case if that's a concern.


问:
ionic serve results in white screen
Anyone else encountering this? After running ionic serve -cs the server spins up but a blank webpage gets shown with no errors in the console.

Here is my setup:

global packages:

```<code>@ionic/cli-utils : 1.4.0
Cordova CLI      : 7.0.1
Ionic CLI        : 3.4.0
</code>```

local packages:

```<code>@ionic/app-scripts              : 1.3.12
@ionic/cli-plugin-cordova       : 1.4.0
@ionic/cli-plugin-ionic-angular : 1.3.1
Cordova Platforms               : browser 4.0.0
Ionic Framework                 : ionic-angular 3.5.0
</code>```

System:

```<code>Node       : v8.1.3
OS         : macOS Sierra
Xcode      : Xcode 8.3.3 Build version 8E3004b
ios-deploy : 1.9.0
ios-sim    : 5.0.9
npm        : 5.0.3
</code>```

答: Found the issue. For some reason the cli command ionic serve defaults to --address 0.0.0.0. When the browser auto launches it uses localhost instead of 0.0.0.0. Replaced localhost with 0.0.0.0 and fixed my problem.

Title: ionic serve results in white screen

Body:
Anyone else encountering this? After running ionic serve -cs the server spins up but a blank webpage gets shown with no errors in the console.

Here is my setup:

global packages:

@ionic/cli-utils : 1.4.0
Cordova CLI      : 7.0.1
Ionic CLI        : 3.4.0

local packages:

@ionic/app-scripts              : 1.3.12
@ionic/cli-plugin-cordova       : 1.4.0
@ionic/cli-plugin-ionic-angular : 1.3.1
Cordova Platforms               : browser 4.0.0
Ionic Framework                 : ionic-angular 3.5.0

System:

Node       : v8.1.3
OS         : macOS Sierra
Xcode      : Xcode 8.3.3 Build version 8E3004b
ios-deploy : 1.9.0
ios-sim    : 5.0.9
npm        : 5.0.3


问:
Use match from file in string
I have a list of user ids in a file and I'm trying to generate some sql from the file.

```<code>cat users.json | awk '/UID/{print "INSERT IGNORE INTO potential_problem_users VALUES ("$2");" }'
</code>```

But it's not doing what I expected it to do:

```<code>);SERT IGNORE INTO potential_problem_users VALUES ("1"
);SERT IGNORE INTO potential_problem_users VALUES ("2"
</code>```

The query I am trying for is:

```<code>INSERT IGNORE INTO potential_problem_users VALUES ([userID]);
</code>```

example json if it helps:

```<code>{
  "results": [
    {
      "UID": "abc"
    },
    {
      "UID": "124"
    }
  ],
  "objectsCount": 5,
  "totalCount": 10966,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}
</code>```

Am I using the right tool? If I am, what am I doing wrong?

答:
You have several JSON parsers available to you on OS X that will also work on Linux. You can use Perl, Python or Ruby among others.

Here is a demo in Ruby:

Given:

```<code>$ cat json
{
    "results": [
        {
            "UID": "abc"
        },
        {
            "UID": "124"
        }
    ],
    "objectsCount": 5,
    "totalCount": 10966,
    "statusCode": 200,
    "errorCode": 0,
    "statusReason": "OK"
}
</code>```

You can parse that file and print to lines of interest this way:

```<code>$ ruby -0777 -lane 'require "json"
                    d=JSON.parse($_)
                    d["results"].each {|e| puts "INSERT IGNORE INTO potential_problem_users VALUES (#{e["UID"]})" }' json
INSERT IGNORE INTO potential_problem_users VALUES (abc)
INSERT IGNORE INTO potential_problem_users VALUES (124)
</code>```

Title: Use match from file in string

Body:
I have a list of user ids in a file and I'm trying to generate some sql from the file.

cat users.json | awk '/UID/{print "INSERT IGNORE INTO potential_problem_users VALUES ("$2");" }'

But it's not doing what I expected it to do:

);SERT IGNORE INTO potential_problem_users VALUES ("1"
);SERT IGNORE INTO potential_problem_users VALUES ("2"

The query I am trying for is:

INSERT IGNORE INTO potential_problem_users VALUES ([userID]);

example json if it helps:

{
  "results": [
    {
      "UID": "abc"
    },
    {
      "UID": "124"
    }
  ],
  "objectsCount": 5,
  "totalCount": 10966,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}

Am I using the right tool? If I am, what am I doing wrong?

Body:
You have several JSON parsers available to you on OS X that will also work on Linux. You can use Perl, Python or Ruby among others.

Here is a demo in Ruby:

Given:

$ cat json
{
    "results": [
        {
            "UID": "abc"
        },
        {
            "UID": "124"
        }
    ],
    "objectsCount": 5,
    "totalCount": 10966,
    "statusCode": 200,
    "errorCode": 0,
    "statusReason": "OK"
}

You can parse that file and print to lines of interest this way:

$ ruby -0777 -lane 'require "json"
                    d=JSON.parse($_)
                    d["results"].each {|e| puts "INSERT IGNORE INTO potential_problem_users VALUES (#{e["UID"]})" }' json
INSERT IGNORE INTO potential_problem_users VALUES (abc)
INSERT IGNORE INTO potential_problem_users VALUES (124)


答: Have you looked into jQuery's serializeArray() api? This might be good enough depending on your use case but here's another library built on top of serializeArray().</p>

Title: how to convert x-www-form-urlencoded payload to json


问:
Plot histogram for discrete data
I'm struggling a lot to plot histogram using R for the following data:

```<code>ip_addr_player_id,event_name,level,time_to_finish,

118.93.180.241, Puzzle Complete, Puzzle 1,33.28 seconds
</code>```

This is a single row of data. I need to pot histogram of the number player vs the number of levels played. I was able to successfully plot scatter plot, points, lines etc. but no histogram.

```<code>on Xaxis: number of levels.
Yaxis: Number of player.
</code>```

Each ip address is unique and multiple levels can be played by single ip address. I have attached a sample picture.

答:
table() should do the job:

Creating data:

```<code>ips <- sample(seq(100,999), 100, replace = TRUE)
levels <- sample(LETTERS, 100, replace = TRUE)
data <- data.frame(ips, levels)
</code>```

now counting:

```<code>unique.levels <- sort(unique(data$levels))
count <- table(data$levels)
count.df <- data.frame(unique.levels, count)
</code>```

Now plot:

```<code>plot <- ggplot(count.df, aes(unique.levels, Freq, fill=unique.levels))

plot + geom_bar(stat="identity") +
        labs(title="Level Count",
             subtitle="count for every lvl played",
                     y="Count", x="Levels") +
        theme(legend.position="none")
</code>```

I know that geom_bar() alone  will count levels for you if you use data$levels in aes(), BUT count.df carries that info so you can use it elsewhere.

ContentLicense: CC BY-SA 4.0

Title: Plot histogram for discrete data

Body:
I'm struggling a lot to plot histogram using R for the following data:

ip_addr_player_id,event_name,level,time_to_finish,

118.93.180.241, Puzzle Complete, Puzzle 1,33.28 seconds

This is a single row of data. I need to pot histogram of the number player vs the number of levels played. I was able to successfully plot scatter plot, points, lines etc. but no histogram.

on Xaxis: number of levels.
Yaxis: Number of player.

Each ip address is unique and multiple levels can be played by single ip address. I have attached a sample picture.

Body:
table() should do the job:

Creating data:

ips <- sample(seq(100,999), 100, replace = TRUE)
levels <- sample(LETTERS, 100, replace = TRUE)
data <- data.frame(ips, levels)

now counting:

unique.levels <- sort(unique(data$levels))
count <- table(data$levels)
count.df <- data.frame(unique.levels, count)

Now plot:

plot <- ggplot(count.df, aes(unique.levels, Freq, fill=unique.levels))

plot + geom_bar(stat="identity") +
        labs(title="Level Count",
             subtitle="count for every lvl played",
                     y="Count", x="Levels") +
        theme(legend.position="none")

I know that geom_bar() alone  will count levels for you if you use data$levels in aes(), BUT count.df carries that info so you can use it elsewhere.


问:
How to retrieve the Content-Type and the Content-Disposition from an outlook msg file using Apache POI-HSMF?
I need to write a Java program to extract all attachments from messages saved by Outlook 2016 in the native msg format. The program should skip inline images. Also some of the mails have multipart/alternative parts where the program should retrieve the "best" content-type, e.g. text/html over text/plain.

In order to do that, I need to find out the content-type and content-disposition of all parts and attachments of the message.

I tried the following:

```<code>public static void main(String[] args) throws IOException {
    String mfile = "test/test2.msg";
    MAPIMessage msg = new MAPIMessage(mfile);

    AttachmentChunks[] attachments = msg.getAttachmentFiles();
    if (attachments.length > 0) {
        for (AttachmentChunks attachment : attachments) {
            System.out.println("long file name = " + attachment.getAttachLongFileName());
            System.out.println("content id = " + attachment.getAttachContentId());
            System.out.println("mime tag = " + attachment.getAttachMimeTag());
            System.out.println("embedded = " + attachment.isEmbeddedMessage());
        }
    }
    msg.close();
}
</code>```

The problem is, that the "mime tag" (i.e. the content-type) is returned only for some attachments and returns null for all others. The content-disposition seems to be totally missing.

For example, I get the following output on a mail saved by OL2016 (the mail contains a PDF attachment and an inline logo image):

```<code>long file name = Vertretungsvollmacht Übersiedlung.pdf
content id = null
mime tag = null
embedded = false
long file name = image001.jpg
content id = image001.jpg@01D2E697.12EC9370
mime tag = image/jpeg
embedded = false
</code>```

Is there a way to get these attributes out of the msg files or is there a more complete & convenient way to achieve what I want in Java with some other library than Apache POI-HSMF?

答: The fact that an attachment has a content-id tag does not mean it is an embedded image - Lotus Notes adds content-id to all attachments. The only valid check is to load the HTML body and figure out what the  tags refer to.

Body:
I need to write a Java program to extract all attachments from messages saved by Outlook 2016 in the native msg format. The program should skip inline images. Also some of the mails have multipart/alternative parts where the program should retrieve the "best" content-type, e.g. text/html over text/plain.

In order to do that, I need to find out the content-type and content-disposition of all parts and attachments of the message.

I tried the following:

public static void main(String[] args) throws IOException {
    String mfile = "test/test2.msg";
    MAPIMessage msg = new MAPIMessage(mfile);

    AttachmentChunks[] attachments = msg.getAttachmentFiles();
    if (attachments.length > 0) {
        for (AttachmentChunks attachment : attachments) {
            System.out.println("long file name = " + attachment.getAttachLongFileName());
            System.out.println("content id = " + attachment.getAttachContentId());
            System.out.println("mime tag = " + attachment.getAttachMimeTag());
            System.out.println("embedded = " + attachment.isEmbeddedMessage());
        }
    }
    msg.close();
}

The problem is, that the "mime tag" (i.e. the content-type) is returned only for some attachments and returns null for all others. The content-disposition seems to be totally missing.

For example, I get the following output on a mail saved by OL2016 (the mail contains a PDF attachment and an inline logo image):

long file name = Vertretungsvollmacht Übersiedlung.pdf
content id = null
mime tag = null
embedded = false
long file name = image001.jpg
content id = image001.jpg@01D2E697.12EC9370
mime tag = image/jpeg
embedded = false

Is there a way to get these attributes out of the msg files or is there a more complete & convenient way to achieve what I want in Java with some other library than Apache POI-HSMF?

Body: The fact that an attachment has a content-id tag does not mean it is an embedded image - Lotus Notes adds content-id to all attachments. The only valid check is to load the HTML body and figure out what the <img> tags refer to.


问:
Why does the animation reset on slideToggle()? (jQuery)
I've positioned a div (fixed) at the bottom of the viewport to act as a contact tab, when then tab is clicked it triggers a panel to slide out, this is working correctly.

I'm also trying to get the tab to slide out when it is clicked and slide back in when then close button is clicked on the panel.

The tab has the ID #menufixed

The panel close button has the class .nest-custom-button-wrapper

This is the JS I'm currently using which is causing a weird animation reset everytime the slideToggle is triggered:

```<code><script>
jQuery(document).ready(function(){
    jQuery("#menufixed").click(function(){
        jQuery("#menufixed").slideToggle();
    });
});
</script>
</code>```

View the issue:

https://content.screencast.com/users/Vanstone/folders/Default/media/aa25e806-e0c0-4f8c-b112-e1162ede41da/11new.mp4

How can I get the tab to stay hidden and only trigger the slide up when the .nest-custom-button-wrapper is clicked?

EDIT:

CSS:

```<code>#menufixed {
    z-index: 99999999!important;
    display: block!important;
    position: fixed!important;
    margin: 0 auto!important;
    bottom: 0;
    left: 45%;
    width: 10%;
    height: 40px;
    box-shadow: 0 0 3px 0px rgba(0, 0, 0, 0.3);
}
</code>```

答:
This is because you have this in your CSS for #menufix

```<code>display: block!important
</code>```

jQuery is trying to hide the element but this style is overriding it. If you remove just the !important part of that style it should work fine.

Updated CSS

```<code>#menufixed {
    z-index: 99999999!important;
    display: block; /* removed the !important style */
    position: fixed!important;
    margin: 0 auto!important;
    bottom: 0;
    left: 45%;
    width: 10%;
    height: 40px;
    box-shadow: 0 0 3px 0px rgba(0, 0, 0, 0.3);
}
</code>```

In order to get the button tab to slide up from .nest-custom-button-wrapper you can just add another click event to slideToggle the #menufixed

JS Code

```<code>jQuery(document).ready(function(){
    jQuery("#menufixed").click(function(){
        jQuery("#menufixed").slideToggle();
    });
    jQuery('.nest-custom-button-wrapper').click(function(e) {
        e.preventDefault(); // not sure if this is an 'a' tag or not

        jQuery("#menufixed").slideToggle();
    });
});
</code>```

Body:
I've positioned a div (fixed) at the bottom of the viewport to act as a contact tab, when then tab is clicked it triggers a panel to slide out, this is working correctly.

I'm also trying to get the tab to slide out when it is clicked and slide back in when then close button is clicked on the panel.

The tab has the ID #menufixed

The panel close button has the class .nest-custom-button-wrapper

This is the JS I'm currently using which is causing a weird animation reset everytime the slideToggle is triggered:

View the issue:

https://content.screencast.com/users/Vanstone/folders/Default/media/aa25e806-e0c0-4f8c-b112-e1162ede41da/11new.mp4

How can I get the tab to stay hidden and only trigger the slide up when the .nest-custom-button-wrapper is clicked?

EDIT:

CSS:

#menufixed {
    z-index: 99999999!important;
    display: block!important;
    position: fixed!important;
    margin: 0 auto!important;
    bottom: 0;
    left: 45%;
    width: 10%;
    height: 40px;
    box-shadow: 0 0 3px 0px rgba(0, 0, 0, 0.3);
}

Body:
This is because you have this in your CSS for #menufix

display: block!important

jQuery is trying to hide the element but this style is overriding it. If you remove just the !important part of that style it should work fine.

Updated CSS

#menufixed {
    z-index: 99999999!important;
    display: block; /* removed the !important style */
    position: fixed!important;
    margin: 0 auto!important;
    bottom: 0;
    left: 45%;
    width: 10%;
    height: 40px;
    box-shadow: 0 0 3px 0px rgba(0, 0, 0, 0.3);
}

In order to get the button tab to slide up from .nest-custom-button-wrapper you can just add another click event to slideToggle the #menufixed

JS Code

jQuery(document).ready(function(){
    jQuery("#menufixed").click(function(){
        jQuery("#menufixed").slideToggle();
    });
    jQuery('.nest-custom-button-wrapper').click(function(e) {
        e.preventDefault(); // not sure if this is an 'a' tag or not

        jQuery("#menufixed").slideToggle();
    });
});


问:
How can I make my openAM SDK app know where to find OpenAM server?
I am writing a complemental service for OpenAM for some features not available as RESTful services in default server. I am using OpenAM Client SDK (12 or 13). I get the folloing error:

```<code>DebugConfiguration:07/03/2017 04:13:12:530 PM IRDT:
Thread[main,5,main]
'/debugconfig.properties' isn't valid, the default configuration will be used instead: Can't find the configuration file

'/debugconfig.properties'.
amAuthContext:07/03/2017 04:13:12:564 PM IRDT: Thread[main,5,main]:
TransactionId[unknown]
 ERROR: Failed to obtain auth service url from server: null://null:null
 amNaming:07/03/2017 04:13:12:573 PM IRDT: Thread[main,5,main]:
TransactionId[unknown]
ERROR: Failed to initialize naming service
java.lang.Exception: Cannot find Naming Service URL.
at com.iplanet.services.naming.WebtopNaming.getNamingServiceURL(WebtopNaming.java:1254)
at com.iplanet.services.naming.WebtopNaming.initializeNamingService(WebtopNaming.java:272)
at com.iplanet.services.naming.WebtopNaming.updateNamingTable(WebtopNaming.java:1149)
at com.iplanet.services.naming.WebtopNaming.getNamingProfile(WebtopNaming.java:1070)
at com.iplanet.services.naming.WebtopNaming.getServiceAllURLs(WebtopNaming.java:494)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:654)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:584)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:386)
at MainKt.realmLogin(Main.kt:56)
at MainKt.main(Main.kt:144)

IdRepoSampleUtils: Failed to start login for default authmodule
Exception in thread "main"
com.sun.identity.authentication.spi.AuthLoginException: Failed to create new Authentication Context: null
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:657)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:584)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:386)
at MainKt.realmLogin(Main.kt:56)
at MainKt.main(Main.kt:144)
</code>```

The main error is SDk does not find STS server url. How can I fix it?

答: I found the solution with checking the Example SDK client. The solution is to use Java's well-knwon properties file. There is a AMConfig.properties in there which the SDK jar automatically tries to extract values from it. For the format of the file we can refer to Oracle OpenSSO, and use the AMConfig.properties.template within the OpenAM example client application.</p>

Body:
I am writing a complemental service for OpenAM for some features not available as RESTful services in default server. I am using OpenAM Client SDK (12 or 13). I get the folloing error:

DebugConfiguration:07/03/2017 04:13:12:530 PM IRDT:
Thread[main,5,main]
'/debugconfig.properties' isn't valid, the default configuration will be used instead: Can't find the configuration file

'/debugconfig.properties'.
amAuthContext:07/03/2017 04:13:12:564 PM IRDT: Thread[main,5,main]:
TransactionId[unknown]
 ERROR: Failed to obtain auth service url from server: null://null:null
 amNaming:07/03/2017 04:13:12:573 PM IRDT: Thread[main,5,main]:
TransactionId[unknown]
ERROR: Failed to initialize naming service
java.lang.Exception: Cannot find Naming Service URL.
at com.iplanet.services.naming.WebtopNaming.getNamingServiceURL(WebtopNaming.java:1254)
at com.iplanet.services.naming.WebtopNaming.initializeNamingService(WebtopNaming.java:272)
at com.iplanet.services.naming.WebtopNaming.updateNamingTable(WebtopNaming.java:1149)
at com.iplanet.services.naming.WebtopNaming.getNamingProfile(WebtopNaming.java:1070)
at com.iplanet.services.naming.WebtopNaming.getServiceAllURLs(WebtopNaming.java:494)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:654)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:584)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:386)
at MainKt.realmLogin(Main.kt:56)
at MainKt.main(Main.kt:144)

IdRepoSampleUtils: Failed to start login for default authmodule
Exception in thread "main"
com.sun.identity.authentication.spi.AuthLoginException: Failed to create new Authentication Context: null
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:657)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:584)
at com.sun.identity.authentication.AuthContext.login(AuthContext.java:386)
at MainKt.realmLogin(Main.kt:56)
at MainKt.main(Main.kt:144)

The main error is SDk does not find STS server url. How can I fix it?


问:
Android dropshadow on custom vector
I would like to be able to add a dropshadow to vectors that I have in my drawables folder.  Currently, when I import the svg which has a dropshadow into Android Studio, the conversion to xml removes the dropshadow.

How would I go about creating a dropshadow for a vector graphic in Android Studio?

This is an example image of the vector I'm trying to add dropshadow to.

答:
If you have an svg editor tool like sketch, I would add the shadow through that and save the svg. Then use the following tool to convert it to an android drawable.
http://a-student.github.io/SvgToVectorDrawableConverter.Web/

Then finally either download the xml file to your drawable folder or select and copy the content and manually create a new drawable resource in your project and copy the  content into it. Easy peasy :). Let me know how that works out for you.

Title: Android dropshadow on custom vector


问:
eclipse neon 3 UI Glitch Marketplace no longer accessible
Good Morning, Good Evening, Good Afternoon everyone. :P Today, I ran into a problem shortly after I updated the Eclipse IDE from Neon 2 to Neon 3. It does appear that I am no longer able to access the MPC (Market Place Client). The help menu no longer has any options for MPC.

I do clarify that I was able to access it once after the update, and I used it to try and download a few plugins that went missing after the update. But for some reason, when I restarted eclipse to finalize the plugin install, the help menu no longer had any links to it. (And the link in the Welcome Screen does nothing in case somebody were to mention it, tho it did give a small notification once telling me there was an exception trying to execute the UI command.)

I am running Arch Linux x86_64 and updated eclipse through pacman in case that's a needed detail. I do believe this to be a bug, but if nobody else is experiencing this, I would definitely appreciate some help.

答: I still don't entirely understand the problem, but I fixed it by deleting everything in /home/[user]/.eclipse. I can now go about installing updates, new plugins, and the like again.


问:
How to find records ONLY having multiple rows in SQL Server 2014?
Customers have accounts with us for their vehicles. Some accounts have multiple vehicles.

I would like to create a report of accounts ONLY with multiple vehicles (i.e. Multiple AccountIDs and Licence Plate numbers.)

Table Account A

Table Plate P

A.AccountId = P.AccountId

```<code>SELECT A.AccountNumber
      ,A.AccountId
      ,P.LicPlateNo

FROM Account A
INNER JOIN Plate P ON A.AccountId = P.AccountId

WHERE A.RegDate > '2017-01-01'
  AND (Select Count(P.LicPlateNo) GROUP BY A.AccountNumber) > 1
   -- HAVING Count(P.LicPlateNo) > 1 ????

ORDER BY A.AccountNumber
</code>```

答:
Use count() over()

```<code>SELECT AccountNumber
      ,AccountId
      ,LicPlateNo
FROM (
    SELECT A.AccountNumber
          ,A.AccountId
          ,P.LicPlateNo
          ,cnt = count(P.LicPlateNo) over(partition by P.AccountId)
    FROM Account A
    INNER JOIN Plate P ON A.AccountId = P.AccountId
    WHERE A.RegDate > '2017-01-01'
) t
WHERE cnt > 1
ORDER BY AccountNumber
</code>```

Body:
Customers have accounts with us for their vehicles. Some accounts have multiple vehicles.

I would like to create a report of accounts ONLY with multiple vehicles (i.e. Multiple AccountIDs and Licence Plate numbers.)

Table Account A

Table Plate P

A.AccountId = P.AccountId

SELECT A.AccountNumber
      ,A.AccountId
      ,P.LicPlateNo

FROM Account A
INNER JOIN Plate P ON A.AccountId = P.AccountId

WHERE A.RegDate > '2017-01-01'
  AND (Select Count(P.LicPlateNo) GROUP BY A.AccountNumber) > 1
   -- HAVING Count(P.LicPlateNo) > 1 ????

ORDER BY A.AccountNumber

Body:
Use count() over()

SELECT AccountNumber
      ,AccountId
      ,LicPlateNo
FROM (
    SELECT A.AccountNumber
          ,A.AccountId
          ,P.LicPlateNo
          ,cnt = count(P.LicPlateNo) over(partition by P.AccountId)
    FROM Account A
    INNER JOIN Plate P ON A.AccountId = P.AccountId
    WHERE A.RegDate > '2017-01-01'
) t
WHERE cnt > 1
ORDER BY AccountNumber


问:
c# DataSet.WriteXml(fileStream, XmlWriteMode.IgnoreSchema); corrupts my xml file
```<code><Data>
  <configs>
    <someEntry>"value1"</someEntry>
  </configs>
  <profiles>
    <someEntry>"value2"</someEntry>
  </profiles>
</Data>es>
    <someEntry>"value3"</someEntry>
  </profiles>
</Data>
</code>```

That </Data>es> is the problem.
It happens when I try to delete the "value3" DataRow in this example. The DataTable Visualizer of Visual Studio shows that my table is fine but the DataSet gets saved that way although it's suppossed to be this way:

```<code><Data>
  <configs>
    <someEntry>"value1"</someEntry>
  </configs>
  <profiles>
    <someEntry>"value2"</someEntry>
  </profiles>
</Data>
</code>```

Before starting using FileStream everything worked as expected. This is how I initiate my FileStream:

```<code>FileStream filestream = new FileStream(xmlLocation, FileMode.Open, FileAccess.ReadWrite);
</code>```

答:
You're using FileMode.Open, which doesn't truncate the file if it already exists.

Just use File.Create instead:

```<code>using (var stream = File.Create(directory))
{
    ...
}
</code>```

(You could specify FileMode.Create instead, as your post originally had before you edited it, but I find it much simpler to call the File.* simplified methods in almost all cases.)

Body:
<Data>
  <configs>
    <someEntry>"value1"</someEntry>
  </configs>
  <profiles>
    <someEntry>"value2"</someEntry>
  </profiles>
</Data>es>
    <someEntry>"value3"</someEntry>
  </profiles>
</Data>

That </Data>es> is the problem.
It happens when I try to delete the "value3" DataRow in this example. The DataTable Visualizer of Visual Studio shows that my table is fine but the DataSet gets saved that way although it's suppossed to be this way:

<Data>
  <configs>
    <someEntry>"value1"</someEntry>
  </configs>
  <profiles>
    <someEntry>"value2"</someEntry>
  </profiles>
</Data>

Before starting using FileStream everything worked as expected. This is how I initiate my FileStream:

FileStream filestream = new FileStream(xmlLocation, FileMode.Open, FileAccess.ReadWrite);

Body:
You're using FileMode.Open, which doesn't truncate the file if it already exists.

Just use File.Create instead:

using (var stream = File.Create(directory))
{
    ...
}

(You could specify FileMode.Create instead, as your post originally had before you edited it, but I find it much simpler to call the File.* simplified methods in almost all cases.)


问:
How to correct my python3 environment on Ubuntu 16.04 (64 bit)
I tried to install the mysql connector for my python environment.
I use python on my Linux (Ubuntu 16.04) machine.
On this machine python 2.7.12 and python 3.5.2.
I probably messed something up because of my inexperience with installing new python modules.
When I now try to install the mysql connector with the command

```<code>pip3 install mysql-connector-python-rf
</code>```

I get the following messages:

Collecting mysql-connector-python-rf   Downloading
  mysql-connector-python-rf-2.2.2.tar.gz (11.9MB)
      100% |████████████████████████████████| 11.9MB 131kB/s  Building wheels for collected packages: mysql-connector-python-rf   Running
  setup.py bdist_wheel for mysql-connector-python-rf ... done   Stored
  in directory:
  /home/claude/.cache/pip/wheels/bb/53/e4/dced82f8a15f96a8afbe626ebb2939d2901b29e610a97fc1ba
  Successfully built mysql-connector-python-rf Installing collected
  packages: mysql-connector-python-rf Exception: Traceback (most recent
  call last):   File
  "/home/claude/.local/lib/python3.5/site-packages/pip/basecommand.py",
  line 215, in main
      status = self.run(options, args)   File "/home/claude/.local/lib/python3.5/site-packages/pip/commands/install.py",
  line 342, in run
      prefix=options.prefix_path,   File "/home/claude/.local/lib/python3.5/site-packages/pip/req/req_set.py",
  line 784, in install
      **kwargs   File "/home/claude/.local/lib/python3.5/site-packages/pip/req/req_install.py",
  line 851, in install
      self.move_wheel_files(self.source_dir, root=root, prefix=prefix)   File
  "/home/claude/.local/lib/python3.5/site-packages/pip/req/req_install.py",
  line 1064, in move_wheel_files
      isolated=self.isolated,   File "/home/claude/.local/lib/python3.5/site-packages/pip/wheel.py", line
  345, in move_wheel_files
      clobber(source, lib_dir, True)   File "/home/claude/.local/lib/python3.5/site-packages/pip/wheel.py", line
  316, in clobber
      ensure_dir(destdir)   File "/home/claude/.local/lib/python3.5/site-packages/pip/utils/init.py",
  line 83, in ensure_dir
      os.makedirs(path)   File "/usr/lib/python3.5/os.py", line 241, in makedirs
      mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/mysql_connector_python_rf-2.2.2.dist-info'

How can a correct this problem?
Or How can I do a correct fresh install of my python2 and python3 environment on my Ubuntu 16.04 x86 Linux?

答:
There is nothing wrong with your installation. To install packages globally, you need superuser privileges; you would run that command under sudo.

However, you should avoid doing this. Create a virtualenv and install the package there.

Body:
I tried to install the mysql connector for my python environment.
I use python on my Linux (Ubuntu 16.04) machine.
On this machine python 2.7.12 and python 3.5.2.
I probably messed something up because of my inexperience with installing new python modules.
When I now try to install the mysql connector with the command

pip3 install mysql-connector-python-rf

I get the following messages:

Collecting mysql-connector-python-rf   Downloading
  mysql-connector-python-rf-2.2.2.tar.gz (11.9MB)
      100% |████████████████████████████████| 11.9MB 131kB/s  Building wheels for collected packages: mysql-connector-python-rf   Running
  setup.py bdist_wheel for mysql-connector-python-rf ... done   Stored
  in directory:
  /home/claude/.cache/pip/wheels/bb/53/e4/dced82f8a15f96a8afbe626ebb2939d2901b29e610a97fc1ba
  Successfully built mysql-connector-python-rf Installing collected
  packages: mysql-connector-python-rf Exception: Traceback (most recent
  call last):   File
  "/home/claude/.local/lib/python3.5/site-packages/pip/basecommand.py",
  line 215, in main
      status = self.run(options, args)   File "/home/claude/.local/lib/python3.5/site-packages/pip/commands/install.py",
  line 342, in run
      prefix=options.prefix_path,   File "/home/claude/.local/lib/python3.5/site-packages/pip/req/req_set.py",
  line 784, in install
      **kwargs   File "/home/claude/.local/lib/python3.5/site-packages/pip/req/req_install.py",
  line 851, in install
      self.move_wheel_files(self.source_dir, root=root, prefix=prefix)   File
  "/home/claude/.local/lib/python3.5/site-packages/pip/req/req_install.py",
  line 1064, in move_wheel_files
      isolated=self.isolated,   File "/home/claude/.local/lib/python3.5/site-packages/pip/wheel.py", line
  345, in move_wheel_files
      clobber(source, lib_dir, True)   File "/home/claude/.local/lib/python3.5/site-packages/pip/wheel.py", line
  316, in clobber
      ensure_dir(destdir)   File "/home/claude/.local/lib/python3.5/site-packages/pip/utils/init.py",
  line 83, in ensure_dir
      os.makedirs(path)   File "/usr/lib/python3.5/os.py", line 241, in makedirs
      mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/mysql_connector_python_rf-2.2.2.dist-info'

How can a correct this problem?
Or How can I do a correct fresh install of my python2 and python3 environment on my Ubuntu 16.04 x86 Linux?


问:
reStructuredText Multilevel
How can I get such a structur with reStructuredText? Is it even possible? </p>

```<code>1. Title
    1.1 Subtitle
         1.1.2 SubSubtitle
             1.1.2.1 SubSubtitle
    1.2 2ndSubtitle
         1.2.1 2ndSubSubtitle
</code>```

答:
Did you look at the Sphinx documentation for nested lists? Your question should show that you made some effort, including what documentation you read, what you tried, what you expected, and what you observed.

Nested lists are possible, but be aware that they must be separated from the parent list items by blank lines:

```<code>* this is
* a list

  * with a nested list
  * and some subitems

* and here the parent list continues
</code>```

Substitute #. for *.

Title: reStructuredText Multilevel

Body:
How can I get such a structur with reStructuredText? Is it even possible?

1. Title
    1.1 Subtitle
         1.1.2 SubSubtitle
             1.1.2.1 SubSubtitle
    1.2 2ndSubtitle
         1.2.1 2ndSubSubtitle

Body:
Did you look at the Sphinx documentation for nested lists? Your question should show that you made some effort, including what documentation you read, what you tried, what you expected, and what you observed.

Nested lists are possible, but be aware that they must be separated from the parent list items by blank lines:

* this is
* a list

  * with a nested list
  * and some subitems

* and here the parent list continues

Substitute #. for *.


问:
How to implement template function to create arbitrary class instance?
I need to implement a template function which would allow me to create an instance of arbitrary class using arbitrary constructor with any possible parameters which can be any combination of lvalues and rvalues.

Lets say I have two classes - A and B - which are as follows:

```<code>class A
{
public:

A(){}

};

class B
{
    A& a1; // I want to be able to call non-constant methods and modify object
    const A& a2; // This I need only as const member
    int i; //can be initialized with a temporary object

    public:

    B(A& a1_, const A& a2_, int i_) : a(a_), a2(a2_), i(i_) {}
};
</code>```

I tried to implement something like below but it would only allow me to use lvalues (named objects) and I will not be able to pass temporary objects.
Adding const keyword partly solves the issue but disallows ability to modify objects which may be required.

```<code>template <typename TType, typename ... TArgs>
TType create(TArgs&... args)
{
    return TType(args...);
}
</code>```

I want to use 'create' function like this:

```<code>int main()
{
   A a1;
   A a2;
   //function takes both lvalue and rvalue
   B b = create<B>(a1, a2, 1);
}
</code>```

Could someone please suggest a possible solution?

答:
Could someone please suggest a possible solution?

You just have a few typos. Especially you don't need to pass all arguments by non const reference as TArgs& to the create() function. The compiler would match the best fitting types (references) already.

```<code>class B
{
    A& a1; // I want to be able to call non-constant methods and modify object
    const A& a2; // This I need only as const member
    int i; //can be initialized with a temporary object

    public:

    B(A& a1_, const A& a2_, int i_) : a1(a1_), a2(a2_), i(i_) {}
       // ^                            ^  ^
};

template <typename TType, typename ... TArgs>
TType create(TArgs... args)
               // ^ Remove the reference here
{
    return TType(args...);
}

int main()
{
   A a1;
   const A a2;
// ^^^^^
   //function takes both lvalue and rvalue
   B b = create<B>(a1, a2, 1);
}
</code>```

See the fully compiling version live here.

Of course using a move reference as stated in other answers/comments would also fix the errors (besides the a for a1 typos.):

```<code>template <typename TType, typename ... TArgs>
TType create(TArgs&&... args)
{
    return TType(std::forward<TArgs>(args)...);
}
</code>```

See another live example.

Body:
I need to implement a template function which would allow me to create an instance of arbitrary class using arbitrary constructor with any possible parameters which can be any combination of lvalues and rvalues.

Lets say I have two classes - A and B - which are as follows:

class A
{
public:

A(){}

};

class B
{
    A& a1; // I want to be able to call non-constant methods and modify object
    const A& a2; // This I need only as const member
    int i; //can be initialized with a temporary object

    public:

    B(A& a1_, const A& a2_, int i_) : a(a_), a2(a2_), i(i_) {}
};

I tried to implement something like below but it would only allow me to use lvalues (named objects) and I will not be able to pass temporary objects.
Adding const keyword partly solves the issue but disallows ability to modify objects which may be required.

template <typename TType, typename ... TArgs>
TType create(TArgs&... args)
{
    return TType(args...);
}

I want to use 'create' function like this:

int main()
{
   A a1;
   A a2;
   //function takes both lvalue and rvalue
   B b = create(a1, a2, 1);
}

Could someone please suggest a possible solution?

Body:
Could someone please suggest a possible solution?

You just have a few typos. Especially you don't need to pass all arguments by non const reference as TArgs& to the create() function. The compiler would match the best fitting types (references) already.

class B
{
    A& a1; // I want to be able to call non-constant methods and modify object
    const A& a2; // This I need only as const member
    int i; //can be initialized with a temporary object

    public:

    B(A& a1_, const A& a2_, int i_) : a1(a1_), a2(a2_), i(i_) {}
       // ^                            ^  ^
};

template <typename TType, typename ... TArgs>
TType create(TArgs... args)
               // ^ Remove the reference here
{
    return TType(args...);
}

int main()
{
   A a1;
   const A a2;
// ^^^^^
   //function takes both lvalue and rvalue
   B b = create<B>(a1, a2, 1);
}

See the fully compiling version live here.

Of course using a move reference as stated in other answers/comments would also fix the errors (besides the a for a1 typos.):

template <typename TType, typename ... TArgs>
TType create(TArgs&&... args)
{
    return TType(std::forward<TArgs>(args)...);
}

See another live example.


问:
Safari trouble positioning SVG feSpotlight filter
I want to use a spotlight effect but it only seems to work in Chrome, looks "just ok" in Firefox, but will not position (x,y,z) in Safari. (Other browsers not tested)

I've tried different filter and primitive units, and while this makes a difference, Safari still cannot seem to position the lighting effect in any case.

In pursuit of understanding what is going on, I've tried lots of workarounds including different userSpaceOnUse/objectBoundingBox combos, and different svg structure but have never been able to find one that works on Safari.

Examples

Default filter/primitive units:
https://jsfiddle.net/localnerve/y470d52v/

objectBoundingBox units:
https://jsfiddle.net/localnerve/uyc7o52k/

A picture is also worth a 1000 words (Safari, Chrome, FF). The spotlight on Safari is rendered off-canvas to the right and bleeds in from the right.

To show the spotlight positions on Safari are "out of whack", here's me nudging them in web inspector so I can see the spotlight render at all:

Here is the code using objectBoundingBox filter and primitive units:

```<code><style>
  body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
    font-size: 16px;
    color: #fff;
  }
  * {
    transform-origin: 50% 50% 0;
  }
  .scene-container {
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
  }
  .scene-container.content {
    position: relative;
    width: 100%;
    height: 150vh;
    background-image: linear-gradient(hsla(240, 90%, 8%, 1) 0%, 99%, hsla(217,24%,71%,0) 100%);
    box-shadow: 0px -10px 20px hsl(240, 90%, 8%);
  }
  .spot {
    height: 100%;
    width: 100%;
  }
</style>

<body>
<div class="scene-container content">
  <h2>Here's a spotlight.</h2>
  <svg class="spot" viewBox="0 0 2000 3000" preserveAspectRatio="xMidYMid">
    <defs>
      <filter x="-0.2" y="-0.2" width="1.4" height="1.4" filterUnits="objectBoundingBox" primitiveUnits="objectBoundingBox" id="spotlight">
        <feGaussianBlur in="SourceAlpha" stdDeviation="8" result="blur1"></feGaussianBlur>
        <feSpecularLighting result="specOut" in="blur1" specularConstant="1.8" specularExponent="5" lighting-color="#ffffff">
          <feSpotLight x="0.5" y="-0.4" z="0.03" pointsAtX="0.5" pointsAtY="0.8" pointsAtZ="0" limitingConeAngle="13.7"></feSpotLight>
        </feSpecularLighting>
        <feComposite in="SourceGraphic" in2="specOut" operator="arithmetic" k1="0" k2="1" k3="1" k4="0"></feComposite>
      </filter>
      <clipPath id="spot-clip">
        <rect x="-50" y="2840" width="2200" height="200"></rect>
      </clipPath>
      <filter id="spot-blur">
        <feGaussianBlur in="SourceGraphic" stdDeviation="15">
        </feGaussianBlur>
      </filter>
    </defs>
    <g transform="translate(0, -175)" filter="url(#spotlight)">
      <ellipse cx="50%" cy="95.333%" rx="27%" ry="130" fill="#fff" clip-path="url(#spot-clip)" filter="url(#spot-blur)"></ellipse>
      <rect x="25%" y="43.667%" width="50%" height="50%" stroke="peru" stroke-width="3%" stroke-linejoin="round" fill="#000"></rect>
    </g>
  </svg>
</div>
</body>
</code>```

Any insight you can give is greatly appreciated.

答:
There are known bugs in webkit/Safari for light source positioning wrt transforms and oBB units. After the webkit/blink engine schism, no-one at Apple picked these bugs up from the Chrome team.

https://bugs.webkit.org/show_bug.cgi?id=88877
https://bugs.webkit.org/show_bug.cgi?id=113059

The workaround is not to use transforms and oBB units (do any dynamic positioning or sizing via JavaScript)

Body:
I want to use a spotlight effect but it only seems to work in Chrome, looks "just ok" in Firefox, but will not position (x,y,z) in Safari. (Other browsers not tested)

I've tried different filter and primitive units, and while this makes a difference, Safari still cannot seem to position the lighting effect in any case.

In pursuit of understanding what is going on, I've tried lots of workarounds including different userSpaceOnUse/objectBoundingBox combos, and different svg structure but have never been able to find one that works on Safari.

Examples

Default filter/primitive units:
https://jsfiddle.net/localnerve/y470d52v/

objectBoundingBox units:
https://jsfiddle.net/localnerve/uyc7o52k/

A picture is also worth a 1000 words (Safari, Chrome, FF). The spotlight on Safari is rendered off-canvas to the right and bleeds in from the right.

To show the spotlight positions on Safari are "out of whack", here's me nudging them in web inspector so I can see the spotlight render at all:

Here is the code using objectBoundingBox filter and primitive units:

Here's a spotlight.

  <svg class="spot" viewBox="0 0 2000 3000" preserveAspectRatio="xMidYMid">
    <defs>
      <filter x="-0.2" y="-0.2" width="1.4" height="1.4" filterUnits="objectBoundingBox" primitiveUnits="objectBoundingBox" id="spotlight">
        <feGaussianBlur in="SourceAlpha" stdDeviation="8" result="blur1"></feGaussianBlur>
        <feSpecularLighting result="specOut" in="blur1" specularConstant="1.8" specularExponent="5" lighting-color="#ffffff">
          <feSpotLight x="0.5" y="-0.4" z="0.03" pointsAtX="0.5" pointsAtY="0.8" pointsAtZ="0" limitingConeAngle="13.7"></feSpotLight>
        </feSpecularLighting>
        <feComposite in="SourceGraphic" in2="specOut" operator="arithmetic" k1="0" k2="1" k3="1" k4="0"></feComposite>
      </filter>
      <clipPath id="spot-clip">
        <rect x="-50" y="2840" width="2200" height="200"></rect>
      </clipPath>
      <filter id="spot-blur">
        <feGaussianBlur in="SourceGraphic" stdDeviation="15">
        </feGaussianBlur>
      </filter>
    </defs>
    <g transform="translate(0, -175)" filter="url(#spotlight)">
      <ellipse cx="50%" cy="95.333%" rx="27%" ry="130" fill="#fff" clip-path="url(#spot-clip)" filter="url(#spot-blur)"></ellipse>
      <rect x="25%" y="43.667%" width="50%" height="50%" stroke="peru" stroke-width="3%" stroke-linejoin="round" fill="#000"></rect>
    </g>
  </svg>

Any insight you can give is greatly appreciated.


问:
Go-compiled binary won't run in an alpine docker container on Ubuntu host
Given a binary, compiled with Go using GOOS=linux and GOARCH=amd64, deployed to a docker container based on alpine:3.3, the binary will not run if the docker engine host is Ubuntu (15.10):

```<code>sh: /bin/artisan: not found
</code>```

This same binary (compiled for the same OS and arch) will run just fine if the docker engine host is busybox (which is the base for alpine) deployed within a VirtualBox VM on Mac OS X.

This same binary will also run perfectly fine if the container is based on one of Ubuntu images.

Any idea what this binary is missing?

This is what I've done to reproduce (successful run in VirtualBox/busybox on OS X not shown):

Build (building explicitly with flags even though the arch matches):

```<code>➜  artisan git:(master) ✗ GOOS=linux GOARCH=amd64 go build
</code>```

Check it can run on the host:

```<code>➜  artisan git:(master) ✗ ./artisan
10:14:04.925 [ERROR] artisan: need a command, one of server, provision or build
</code>```

Copy to docker dir, build, run:

```<code>➜  artisan git:(master) ✗ cp artisan docker/build/bin/
➜  artisan git:(master) ✗ cd docker
➜  docker git:(master) ✗ cat Dockerfile
FROM docker:1.10
COPY build/ /
➜  docker git:(master) ✗ docker build -t artisan .
Sending build context to Docker daemon 10.15 MB
Step 1 : FROM docker:1.10
...
➜  docker git:(master) ✗ docker run -it artisan sh
/ # /bin/artisan
sh: /bin/artisan: not found
</code>```

Now changing the image base to phusion/baseimage:

```<code>➜  docker git:(master) ✗ cat Dockerfile
#FROM docker:1.10
FROM phusion/baseimage
COPY build/ /
➜  docker git:(master) ✗ docker build -t artisan .
Sending build context to Docker daemon 10.15 MB
Step 1 : FROM phusion/baseimage
...
➜  docker git:(master) ✗ docker run -it artisan sh
# /bin/artisan
08:16:39.424 [ERROR] artisan: need a command, one of server, provision or build
</code>```

答:
Go compiler from your build machine probably links your binary with libraries on different location than in Alpine. In my case it was compiled with dependencies under /lib64 but Alpine does not use that folder.

```<code>FROM alpine:edge AS build
RUN apk update
RUN apk upgrade
RUN apk add --update go=1.8.3-r0 gcc=6.3.0-r4 g++=6.3.0-r4
WORKDIR /app
ENV GOPATH /app
ADD src /app/src
RUN go get server # server is name of our application
RUN CGO_ENABLED=1 GOOS=linux go install -a server

FROM alpine:edge
WORKDIR /app
RUN cd /app
COPY --from=build /app/bin/server /app/bin/server
CMD ["bin/server"]
</code>```

I'm working on article about this issue. You can find draft with this solution here https://kefblog.com/Post/2017-07-04_golang-in-docker-without-disabling-cgo-on-alpine .

Body:
Given a binary, compiled with Go using GOOS=linux and GOARCH=amd64, deployed to a docker container based on alpine:3.3, the binary will not run if the docker engine host is Ubuntu (15.10):

sh: /bin/artisan: not found

This same binary (compiled for the same OS and arch) will run just fine if the docker engine host is busybox (which is the base for alpine) deployed within a VirtualBox VM on Mac OS X.

This same binary will also run perfectly fine if the container is based on one of Ubuntu images.

Any idea what this binary is missing?

This is what I've done to reproduce (successful run in VirtualBox/busybox on OS X not shown):

Build (building explicitly with flags even though the arch matches):

➜  artisan git:(master) ✗ GOOS=linux GOARCH=amd64 go build

Check it can run on the host:

➜  artisan git:(master) ✗ ./artisan
10:14:04.925 [ERROR] artisan: need a command, one of server, provision or build

Copy to docker dir, build, run:

➜  artisan git:(master) ✗ cp artisan docker/build/bin/
➜  artisan git:(master) ✗ cd docker
➜  docker git:(master) ✗ cat Dockerfile
FROM docker:1.10
COPY build/ /
➜  docker git:(master) ✗ docker build -t artisan .
Sending build context to Docker daemon 10.15 MB
Step 1 : FROM docker:1.10
...
➜  docker git:(master) ✗ docker run -it artisan sh
/ # /bin/artisan
sh: /bin/artisan: not found

Now changing the image base to phusion/baseimage:

➜  docker git:(master) ✗ cat Dockerfile
#FROM docker:1.10
FROM phusion/baseimage
COPY build/ /
➜  docker git:(master) ✗ docker build -t artisan .
Sending build context to Docker daemon 10.15 MB
Step 1 : FROM phusion/baseimage
...
➜  docker git:(master) ✗ docker run -it artisan sh
# /bin/artisan
08:16:39.424 [ERROR] artisan: need a command, one of server, provision or build

Body:
Go compiler from your build machine probably links your binary with libraries on different location than in Alpine. In my case it was compiled with dependencies under /lib64 but Alpine does not use that folder.

FROM alpine:edge AS build
RUN apk update
RUN apk upgrade
RUN apk add --update go=1.8.3-r0 gcc=6.3.0-r4 g++=6.3.0-r4
WORKDIR /app
ENV GOPATH /app
ADD src /app/src
RUN go get server # server is name of our application
RUN CGO_ENABLED=1 GOOS=linux go install -a server

FROM alpine:edge
WORKDIR /app
RUN cd /app
COPY --from=build /app/bin/server /app/bin/server
CMD ["bin/server"]

I'm working on article about this issue. You can find draft with this solution here https://kefblog.com/Post/2017-07-04_golang-in-docker-without-disabling-cgo-on-alpine .