问:
how to output a user selected shape & color, whose location and dimensions depend upon the coordinate location of user clicks
As part of a larger project I'm trying to create a basic UI that will allow a user to click a JButton to select a desired color and then allow that user to click another JButton to designate a shape to be displayed, filled in according to the previously selected color.  I understand that I must make use of action events.

Please note I am referencing this similar question:

GUI Application that allows the user to choose the shape and color of a drawing

My code thus far is:

```<code>import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

public class GUI extends JFrame implements ActionListener, WindowListener
{
private final JButton circleButton, rectangleButton, redButton;
private final JButton greenButton, blueButton, exitButton;
private final JTextArea textArea;
private final JLabel label1;
private final JPanel colorPane;

private String shapeColor = "black";
private String actualShape = "rectangle";

private static final int ROWS = 2, COLS = 3;

public GUI (String title)
{
    super(title);
    //setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    colorPane = new JPanel();

    label1 = new JLabel("current date here");
    label1.setVerticalAlignment(SwingConstants.BOTTOM);
    label1.setHorizontalAlignment(SwingConstants.LEFT);
    label1.setPreferredSize(new Dimension(200,0));
    getContentPane().add(label1, BorderLayout.WEST);

    colorPane.setLayout(new GridLayout(ROWS,COLS));
    getContentPane().add(colorPane, BorderLayout.CENTER);

    redButton = makeButton("Red");
    colorPane.add(redButton);
    greenButton = makeButton("Green");
    colorPane.add(greenButton);
    blueButton = makeButton("Blue");
    colorPane.add(blueButton);
    rectangleButton = makeButton("Rectangle");
    colorPane.add(rectangleButton);
    circleButton = makeButton("Circle");
    colorPane.add(circleButton);
    exitButton = makeButton("Exit");
    colorPane.add(exitButton);

    textArea = new JTextArea(0,20);
    getContentPane().add(textArea, BorderLayout.EAST);

    pack();
}

public void paint(Graphics g, String color)
{
    if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.BLUE);
        g.fillRect(50, 90, 100, 50);
    }
    else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.GREEN);
        g.fillOval(50, 180, 55, 55);
    }
    else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.RED);
        g.fillRect(50, 90, 100, 50);
    }
    else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.GREEN);
        g.fillRect(50,90,100,50);
    }
    else if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.BLUE);
        g.fillOval(50, 180, 55, 55);
    }
    else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.RED);
        g.fillOval(50, 180, 55, 55);
    }
}

//method designed to create new JButtons while avoiding code duplication
private JButton makeButton(String text)
{
    JButton b = new JButton(text);
    b.setHorizontalAlignment(SwingConstants.LEFT);
    b.addActionListener(this);
    b.setPreferredSize(new Dimension(125,55));

    return b;
}

@Override
public void windowOpened(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowClosing(WindowEvent e)
{
    System.exit(0);

}

@Override
public void windowClosed(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowIconified(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowDeiconified(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowActivated(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowDeactivated(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void actionPerformed(ActionEvent e)
{
    System.out.println( ( (JButton)e.getSource() ).getText() + " button pressed ");

    if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Red")) )
    {
        setShapeColor("Red");
        System.out.println("selected color is: " + shapeColor + " selected shape is: " + actualShape);
        //paint(this.getGraphics());
    }
    else if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Blue")) )
    {
        setShapeColor("Blue");
        System.out.println("selected color is: " + shapeColor + " selected shape is: " + actualShape);
        //paint(this.getGraphics());
    }

    else if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Green")) )
    {
        setShapeColor("Green");
        System.out.println("selected color is: " + shapeColor + " selected shape is: " + actualShape);
        //paint(this.getGraphics());
    }

    if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Rectangle")) )
    {
        setActualShape("rectangle");
        System.out.println("selected shape is: " + actualShape + " selected color is: " + shapeColor);
        paint(this.getGraphics(), shapeColor);

    }

    else if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Circle")) )
    {
        setActualShape("circle");
        System.out.println("selected shape is: " + actualShape + " selected color is: " + shapeColor);
        paint(this.getGraphics(), shapeColor);
    }

}

public String getShapeColor() {
    return shapeColor;
}

public void setShapeColor(String shapeColor) {
    this.shapeColor = shapeColor;
}

public String getActualShape() {
    return actualShape;
}

public void setActualShape(String actualShape) {
    this.actualShape = actualShape;
}

public static void main(String[] args)
{
    new GUI("My Gui").setVisible(true);
}
</code>```

}

What I've thus far achieved is an output that shows both the selected color as well as the selected shape to be rendered in the selected color.

Furthermore, I've been successful in outputting a shape whose position is hard-coded but whose type (either circle or square) and whose color (red, blue or green), is correctly output as a result of the user clicks.

The final phase, upon which I am struggling, is the implementation of the shape's output so that the user's sequence of clicks determines the location and dimensions of the shape output to the screen.

The goal is to achieve the functionality demonstrated here:

https://metrostate.learn.minnstate.edu/content/2020/4560296-20201000539/ICS372%20-%20Assignment%202%20Video.mp4?d2lSessionVal=ARifwbCHriCBrkgxBWpL9g8fL&ou=4560296

I'm relatively certain that the correct solution is similar to the following code:

```<code>import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

/**
 *  Note: Normally the ButtonPanel and DrawingArea would not be static
classes.
 *  This was done for the convenience of posting the code in one class and
to
 *  highlight the differences between the two approaches. All the
differences
 *  are found in the DrawingArea class.
 */
public class DrawOnComponent
{
public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

private static void createAndShowGUI()
{
    DrawingArea drawingArea = new DrawingArea();
    ButtonPanel buttonPanel = new ButtonPanel( drawingArea );

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Draw On Component");
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.getContentPane().add(drawingArea);
    frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    frame.setSize(400, 400);
    frame.setLocationRelativeTo( null );
    frame.setVisible(true);
}

static class ButtonPanel extends JPanel implements ActionListener
{
    private DrawingArea drawingArea;

    public ButtonPanel(DrawingArea drawingArea)
    {
        this.drawingArea = drawingArea;

        add( createButton(" ", Color.BLACK) );
        add( createButton(" ", Color.RED) );
        add( createButton(" ", Color.GREEN) );
        add( createButton(" ", Color.BLUE) );
        add( createButton(" ", Color.ORANGE) );
        add( createButton(" ", Color.YELLOW) );
        add( createButton("Clear Drawing", null) );
    }

    private JButton createButton(String text, Color background)
    {
        JButton button = new JButton( text );
        button.setBackground( background );
        button.addActionListener( this );

        return button;
    }

    public void actionPerformed(ActionEvent e)
    {
        JButton button = (JButton)e.getSource();

        if ("Clear Drawing".equals(e.getActionCommand()))
            drawingArea.clear();
        else
            drawingArea.setForeground( button.getBackground() );
    }
}

static class DrawingArea extends JPanel
{
    private final static int AREA_SIZE = 400;
    private ArrayList<ColoredRectangle> coloredRectangles = new ArrayList<ColoredRectangle>();
    private Rectangle shape;

    public DrawingArea()
    {
        setBackground(Color.WHITE);

        MyMouseListener ml = new MyMouseListener();
        addMouseListener(ml);
        addMouseMotionListener(ml);
    }

    @Override
    public Dimension getPreferredSize()
    {
        return isPreferredSizeSet() ?
            super.getPreferredSize() : new Dimension(AREA_SIZE, AREA_SIZE);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        //  Custom code to paint all the Rectangles from the List

        Color foreground = g.getColor();

        g.setColor( Color.BLACK );
        g.drawString("Add a rectangle by doing mouse press, drag and release!", 40, 15);

        for (DrawingArea.ColoredRectangle cr : coloredRectangles)
        {
            g.setColor( cr.getForeground() );
            Rectangle r = cr.getRectangle();
            g.drawRect(r.x, r.y, r.width, r.height);
        }

        //  Paint the Rectangle as the mouse is being dragged

        if (shape != null)
        {
            Graphics2D g2d = (Graphics2D)g;
            g2d.setColor( foreground );
            g2d.draw( shape );
        }
    }

    public void addRectangle(Rectangle rectangle, Color color)
    {
        //  Add the Rectangle to the List so it can be repainted

        ColoredRectangle cr = new ColoredRectangle(color, rectangle);
        coloredRectangles.add( cr );
        repaint();
    }

    public void clear()
    {
        coloredRectangles.clear();
        repaint();
    }

    class MyMouseListener extends MouseInputAdapter
    {
        private Point startPoint;

        public void mousePressed(MouseEvent e)
        {
            startPoint = e.getPoint();
            shape = new Rectangle();
        }

        public void mouseDragged(MouseEvent e)
        {
            int x = Math.min(startPoint.x, e.getX());
            int y = Math.min(startPoint.y, e.getY());
            int width = Math.abs(startPoint.x - e.getX());
            int height = Math.abs(startPoint.y - e.getY());

            shape.setBounds(x, y, width, height);
            repaint();
        }

        public void mouseReleased(MouseEvent e)
        {
            if (shape.width != 0 || shape.height != 0)
            {
                addRectangle(shape, e.getComponent().getForeground());
            }

            shape = null;
        }
    }

    class ColoredRectangle
    {
        private Color foreground;
        private Rectangle rectangle;

        public ColoredRectangle(Color foreground, Rectangle rectangle)
        {
            this.foreground = foreground;
            this.rectangle = rectangle;
        }

        public Color getForeground()
        {
            return foreground;
        }

        public void setForeground(Color foreground)
        {
            this.foreground = foreground;
        }

        public Rectangle getRectangle()
        {
            return rectangle;
        }
    }
}
}
</code>```

I know that I must override the 'paint' method  and as a hard-coded exercise I have included the following in my code:

```<code>public void paint(Graphics g, String color)
{
    if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.BLUE);
        g.fillRect(50, 90, 100, 50);
    }
    else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.GREEN);
        g.fillOval(50, 180, 55, 55);
    }
    else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.RED);
        g.fillRect(50, 90, 100, 50);
    }
    else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.GREEN);
        g.fillRect(50,90,100,50);
    }
    else if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.BLUE);
        g.fillOval(50, 180, 55, 55);
    }
    else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.RED);
        g.fillOval(50, 180, 55, 55);
    }
}
}
</code>```

I am unsure how to record coordinates of a user's button click and to then pass those coordinates into the constructor of the desired shape.

答:
There are a couple of errors to change in your code:

Don't extend JFrame, see Extends JFrame vs. creating it inside the program, instead create an instance of it inside your class. If you need to extend from a JComponent let it be a more flexible one such as JPanel.

Don't override paint(...) method, you need to override JPanel's paintComponent(...) method and don't forget to call super.paintComponent(g) as the first line in it, otherwise you might break the paint chain and have funny / weird behaviors. Neither pass the getGraphics() object, see the Tutorial on Custom Painting

Use the Shape API rather than drawing directly on the JPanel as it provides more functionality. See this post: Create the square, rectangle, triangle of java in jframe

Don't call setPreferredSize, override the getPreferredSize, see: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

Place your program on the EDT, see point #7 in the linked post in point #3 in this same answer.

So, here's an example that follows the above recommendations:

```<code>import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.event.*;

public class PaintExample {
    private JFrame frame;
    private JPanel pane;
    private JPanel buttonsPane;
    private CustomShape customShape;
    private JButton squareButton;
    private JButton circleButton;
    private JButton purpleButton;
    private JButton blueButton;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new PaintExample().createAndShowGUI());
    }

    private void createAndShowGUI() {
        frame = new JFrame(getClass().getSimpleName()); //Create a new JFrame with a title = this class name
        pane = new JPanel();
        buttonsPane = new JPanel();

        buttonsPane.setLayout(new GridLayout(2, 2, 5, 5)); // We generate a grid layout of 2 x 2 for our JButtons

        squareButton = new JButton("Square");
        circleButton = new JButton("Circle");
        purpleButton = new JButton("Purple");
        blueButton = new JButton("Blue");

        squareButton.addActionListener(listener);
        circleButton.addActionListener(listener);
        purpleButton.addActionListener(listener);
        blueButton.addActionListener(listener);

        buttonsPane.add(squareButton);
        buttonsPane.add(circleButton);
        buttonsPane.add(purpleButton);
        buttonsPane.add(blueButton);

        customShape = new CustomShape(); // We create an instance of our custom JPanel class

        pane.setLayout(new BorderLayout());
        pane.add(customShape);
        pane.add(buttonsPane, BorderLayout.SOUTH);

        frame.add(pane);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    ActionListener listener = e -> { //Java 8+, for Java 7- add the actionPerformed method instead of the lambda expression
        // We check which button was clicked and set the shape / color for our custom class
        if (e.getSource().equals(squareButton)) {
            customShape.setShape(ShapeToDraw.SQUARE);
        } else if (e.getSource().equals(circleButton)) {
            customShape.setShape(ShapeToDraw.CIRCLE);
        } else if (e.getSource().equals(purpleButton)) {
            customShape.setColor(Color.MAGENTA);
        } else if (e.getSource().equals(blueButton)) {
            customShape.setColor(Color.BLUE);
        }
    };

    enum ShapeToDraw {
        SQUARE, CIRCLE // You can define here other properties for each enum option
    }

    class CustomShape extends JPanel {
        private Color color;
        private ShapeToDraw shape;

        public CustomShape() {

        }

        public Color getColor() {
            return color;
        }

        public void setColor(Color color) {
            this.color = color;
            this.repaint(); // Everytime we set the color we ask the component to repaint itself
        }

        public ShapeToDraw getShape() {
            return shape;
        }

        public void setShape(ShapeToDraw shape) {
            this.shape = shape;
            this.repaint(); // Everytime we set the shape we ask the component to repaint itself
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200); // We define the panel's size
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(color != null ? color : Color.BLACK); //If we haven't set the Color yet, we default it to black, otherwise we set the color to the one chosen by the user.
            if (shape == ShapeToDraw.SQUARE) { //If the shape is a square, we draw a square
                g2d.draw(new Rectangle2D.Double(50, 50, 100, 100)); // Change the coordinates that you get by user click using the MouseListener
            } else if (shape == ShapeToDraw.CIRCLE) { // Or we draw a circle
                g2d.draw(new Ellipse2D.Double(50, 50, 100, 100));
            }
        }
    }
}
</code>```

This is how the program looks like:

I am unsure how to record coordinates of a user's button click and to then pass those coordinates into the constructor of the desired shape.

To get the coordinates relative to your window see: How to get location of a mouse click relative to a swing window

Body:
As part of a larger project I'm trying to create a basic UI that will allow a user to click a JButton to select a desired color and then allow that user to click another JButton to designate a shape to be displayed, filled in according to the previously selected color.  I understand that I must make use of action events.

Please note I am referencing this similar question:

GUI Application that allows the user to choose the shape and color of a drawing

My code thus far is:

import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

public class GUI extends JFrame implements ActionListener, WindowListener
{
private final JButton circleButton, rectangleButton, redButton;
private final JButton greenButton, blueButton, exitButton;
private final JTextArea textArea;
private final JLabel label1;
private final JPanel colorPane;

private String shapeColor = "black";
private String actualShape = "rectangle";

private static final int ROWS = 2, COLS = 3;

public GUI (String title)
{
    super(title);
    //setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    colorPane = new JPanel();

    label1 = new JLabel("current date here");
    label1.setVerticalAlignment(SwingConstants.BOTTOM);
    label1.setHorizontalAlignment(SwingConstants.LEFT);
    label1.setPreferredSize(new Dimension(200,0));
    getContentPane().add(label1, BorderLayout.WEST);

    colorPane.setLayout(new GridLayout(ROWS,COLS));
    getContentPane().add(colorPane, BorderLayout.CENTER);

    redButton = makeButton("Red");
    colorPane.add(redButton);
    greenButton = makeButton("Green");
    colorPane.add(greenButton);
    blueButton = makeButton("Blue");
    colorPane.add(blueButton);
    rectangleButton = makeButton("Rectangle");
    colorPane.add(rectangleButton);
    circleButton = makeButton("Circle");
    colorPane.add(circleButton);
    exitButton = makeButton("Exit");
    colorPane.add(exitButton);

    textArea = new JTextArea(0,20);
    getContentPane().add(textArea, BorderLayout.EAST);

    pack();
}

public void paint(Graphics g, String color)
{
    if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.BLUE);
        g.fillRect(50, 90, 100, 50);
    }
    else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.GREEN);
        g.fillOval(50, 180, 55, 55);
    }
    else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.RED);
        g.fillRect(50, 90, 100, 50);
    }
    else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.GREEN);
        g.fillRect(50,90,100,50);
    }
    else if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.BLUE);
        g.fillOval(50, 180, 55, 55);
    }
    else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.RED);
        g.fillOval(50, 180, 55, 55);
    }
}

//method designed to create new JButtons while avoiding code duplication
private JButton makeButton(String text)
{
    JButton b = new JButton(text);
    b.setHorizontalAlignment(SwingConstants.LEFT);
    b.addActionListener(this);
    b.setPreferredSize(new Dimension(125,55));

    return b;
}

@Override
public void windowOpened(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowClosing(WindowEvent e)
{
    System.exit(0);

}

@Override
public void windowClosed(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowIconified(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowDeiconified(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowActivated(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void windowDeactivated(WindowEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void actionPerformed(ActionEvent e)
{
    System.out.println( ( (JButton)e.getSource() ).getText() + " button pressed ");

    if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Red")) )
    {
        setShapeColor("Red");
        System.out.println("selected color is: " + shapeColor + " selected shape is: " + actualShape);
        //paint(this.getGraphics());
    }
    else if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Blue")) )
    {
        setShapeColor("Blue");
        System.out.println("selected color is: " + shapeColor + " selected shape is: " + actualShape);
        //paint(this.getGraphics());
    }

    else if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Green")) )
    {
        setShapeColor("Green");
        System.out.println("selected color is: " + shapeColor + " selected shape is: " + actualShape);
        //paint(this.getGraphics());
    }

    if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Rectangle")) )
    {
        setActualShape("rectangle");
        System.out.println("selected shape is: " + actualShape + " selected color is: " + shapeColor);
        paint(this.getGraphics(), shapeColor);

    }

    else if ( ( ((JButton) e.getSource()).getText().equalsIgnoreCase("Circle")) )
    {
        setActualShape("circle");
        System.out.println("selected shape is: " + actualShape + " selected color is: " + shapeColor);
        paint(this.getGraphics(), shapeColor);
    }

}

public String getShapeColor() {
    return shapeColor;
}

public void setShapeColor(String shapeColor) {
    this.shapeColor = shapeColor;
}

public String getActualShape() {
    return actualShape;
}

public void setActualShape(String actualShape) {
    this.actualShape = actualShape;
}

public static void main(String[] args)
{
    new GUI("My Gui").setVisible(true);
}

}

What I've thus far achieved is an output that shows both the selected color as well as the selected shape to be rendered in the selected color.

Furthermore, I've been successful in outputting a shape whose position is hard-coded but whose type (either circle or square) and whose color (red, blue or green), is correctly output as a result of the user clicks.

The final phase, upon which I am struggling, is the implementation of the shape's output so that the user's sequence of clicks determines the location and dimensions of the shape output to the screen.

The goal is to achieve the functionality demonstrated here:

https://metrostate.learn.minnstate.edu/content/2020/4560296-20201000539/ICS372%20-%20Assignment%202%20Video.mp4?d2lSessionVal=ARifwbCHriCBrkgxBWpL9g8fL&ou=4560296

I'm relatively certain that the correct solution is similar to the following code:

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

/**
 *  Note: Normally the ButtonPanel and DrawingArea would not be static
classes.
 *  This was done for the convenience of posting the code in one class and
to
 *  highlight the differences between the two approaches. All the
differences
 *  are found in the DrawingArea class.
 */
public class DrawOnComponent
{
public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

private static void createAndShowGUI()
{
    DrawingArea drawingArea = new DrawingArea();
    ButtonPanel buttonPanel = new ButtonPanel( drawingArea );

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Draw On Component");
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.getContentPane().add(drawingArea);
    frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    frame.setSize(400, 400);
    frame.setLocationRelativeTo( null );
    frame.setVisible(true);
}

static class ButtonPanel extends JPanel implements ActionListener
{
    private DrawingArea drawingArea;

    public ButtonPanel(DrawingArea drawingArea)
    {
        this.drawingArea = drawingArea;

        add( createButton(" ", Color.BLACK) );
        add( createButton(" ", Color.RED) );
        add( createButton(" ", Color.GREEN) );
        add( createButton(" ", Color.BLUE) );
        add( createButton(" ", Color.ORANGE) );
        add( createButton(" ", Color.YELLOW) );
        add( createButton("Clear Drawing", null) );
    }

    private JButton createButton(String text, Color background)
    {
        JButton button = new JButton( text );
        button.setBackground( background );
        button.addActionListener( this );

        return button;
    }

    public void actionPerformed(ActionEvent e)
    {
        JButton button = (JButton)e.getSource();

        if ("Clear Drawing".equals(e.getActionCommand()))
            drawingArea.clear();
        else
            drawingArea.setForeground( button.getBackground() );
    }
}

static class DrawingArea extends JPanel
{
    private final static int AREA_SIZE = 400;
    private ArrayList<ColoredRectangle> coloredRectangles = new ArrayList<ColoredRectangle>();
    private Rectangle shape;

    public DrawingArea()
    {
        setBackground(Color.WHITE);

        MyMouseListener ml = new MyMouseListener();
        addMouseListener(ml);
        addMouseMotionListener(ml);
    }

    @Override
    public Dimension getPreferredSize()
    {
        return isPreferredSizeSet() ?
            super.getPreferredSize() : new Dimension(AREA_SIZE, AREA_SIZE);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        //  Custom code to paint all the Rectangles from the List

        Color foreground = g.getColor();

        g.setColor( Color.BLACK );
        g.drawString("Add a rectangle by doing mouse press, drag and release!", 40, 15);

        for (DrawingArea.ColoredRectangle cr : coloredRectangles)
        {
            g.setColor( cr.getForeground() );
            Rectangle r = cr.getRectangle();
            g.drawRect(r.x, r.y, r.width, r.height);
        }

        //  Paint the Rectangle as the mouse is being dragged

        if (shape != null)
        {
            Graphics2D g2d = (Graphics2D)g;
            g2d.setColor( foreground );
            g2d.draw( shape );
        }
    }

    public void addRectangle(Rectangle rectangle, Color color)
    {
        //  Add the Rectangle to the List so it can be repainted

        ColoredRectangle cr = new ColoredRectangle(color, rectangle);
        coloredRectangles.add( cr );
        repaint();
    }

    public void clear()
    {
        coloredRectangles.clear();
        repaint();
    }

    class MyMouseListener extends MouseInputAdapter
    {
        private Point startPoint;

        public void mousePressed(MouseEvent e)
        {
            startPoint = e.getPoint();
            shape = new Rectangle();
        }

        public void mouseDragged(MouseEvent e)
        {
            int x = Math.min(startPoint.x, e.getX());
            int y = Math.min(startPoint.y, e.getY());
            int width = Math.abs(startPoint.x - e.getX());
            int height = Math.abs(startPoint.y - e.getY());

            shape.setBounds(x, y, width, height);
            repaint();
        }

        public void mouseReleased(MouseEvent e)
        {
            if (shape.width != 0 || shape.height != 0)
            {
                addRectangle(shape, e.getComponent().getForeground());
            }

            shape = null;
        }
    }

    class ColoredRectangle
    {
        private Color foreground;
        private Rectangle rectangle;

        public ColoredRectangle(Color foreground, Rectangle rectangle)
        {
            this.foreground = foreground;
            this.rectangle = rectangle;
        }

        public Color getForeground()
        {
            return foreground;
        }

        public void setForeground(Color foreground)
        {
            this.foreground = foreground;
        }

        public Rectangle getRectangle()
        {
            return rectangle;
        }
    }
}
}

I know that I must override the 'paint' method  and as a hard-coded exercise I have included the following in my code:

public void paint(Graphics g, String color)
{
    if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.BLUE);
        g.fillRect(50, 90, 100, 50);
    }
    else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.GREEN);
        g.fillOval(50, 180, 55, 55);
    }
    else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.RED);
        g.fillRect(50, 90, 100, 50);
    }
    else if (shapeColor.equalsIgnoreCase("green") && actualShape.equalsIgnoreCase("rectangle"))
    {
        g.setColor(Color.GREEN);
        g.fillRect(50,90,100,50);
    }
    else if (shapeColor.equalsIgnoreCase("blue") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.BLUE);
        g.fillOval(50, 180, 55, 55);
    }
    else if (shapeColor.equalsIgnoreCase("red") && actualShape.equalsIgnoreCase("circle"))
    {
        g.setColor(Color.RED);
        g.fillOval(50, 180, 55, 55);
    }
}
}

I am unsure how to record coordinates of a user's button click and to then pass those coordinates into the constructor of the desired shape.

Body:
There are a couple of errors to change in your code:

Don't extend JFrame, see Extends JFrame vs. creating it inside the program, instead create an instance of it inside your class. If you need to extend from a JComponent let it be a more flexible one such as JPanel.

Don't override paint(...) method, you need to override JPanel's paintComponent(...) method and don't forget to call super.paintComponent(g) as the first line in it, otherwise you might break the paint chain and have funny / weird behaviors. Neither pass the getGraphics() object, see the Tutorial on Custom Painting

Use the Shape API rather than drawing directly on the JPanel as it provides more functionality. See this post: Create the square, rectangle, triangle of java in jframe

Don't call setPreferredSize, override the getPreferredSize, see: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

Place your program on the EDT, see point #7 in the linked post in point #3 in this same answer.

So, here's an example that follows the above recommendations:

import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.event.*;

public class PaintExample {
    private JFrame frame;
    private JPanel pane;
    private JPanel buttonsPane;
    private CustomShape customShape;
    private JButton squareButton;
    private JButton circleButton;
    private JButton purpleButton;
    private JButton blueButton;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new PaintExample().createAndShowGUI());
    }

    private void createAndShowGUI() {
        frame = new JFrame(getClass().getSimpleName()); //Create a new JFrame with a title = this class name
        pane = new JPanel();
        buttonsPane = new JPanel();

        buttonsPane.setLayout(new GridLayout(2, 2, 5, 5)); // We generate a grid layout of 2 x 2 for our JButtons

        squareButton = new JButton("Square");
        circleButton = new JButton("Circle");
        purpleButton = new JButton("Purple");
        blueButton = new JButton("Blue");

        squareButton.addActionListener(listener);
        circleButton.addActionListener(listener);
        purpleButton.addActionListener(listener);
        blueButton.addActionListener(listener);

        buttonsPane.add(squareButton);
        buttonsPane.add(circleButton);
        buttonsPane.add(purpleButton);
        buttonsPane.add(blueButton);

        customShape = new CustomShape(); // We create an instance of our custom JPanel class

        pane.setLayout(new BorderLayout());
        pane.add(customShape);
        pane.add(buttonsPane, BorderLayout.SOUTH);

        frame.add(pane);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    ActionListener listener = e -> { //Java 8+, for Java 7- add the actionPerformed method instead of the lambda expression
        // We check which button was clicked and set the shape / color for our custom class
        if (e.getSource().equals(squareButton)) {
            customShape.setShape(ShapeToDraw.SQUARE);
        } else if (e.getSource().equals(circleButton)) {
            customShape.setShape(ShapeToDraw.CIRCLE);
        } else if (e.getSource().equals(purpleButton)) {
            customShape.setColor(Color.MAGENTA);
        } else if (e.getSource().equals(blueButton)) {
            customShape.setColor(Color.BLUE);
        }
    };

    enum ShapeToDraw {
        SQUARE, CIRCLE // You can define here other properties for each enum option
    }

    class CustomShape extends JPanel {
        private Color color;
        private ShapeToDraw shape;

        public CustomShape() {

        }

        public Color getColor() {
            return color;
        }

        public void setColor(Color color) {
            this.color = color;
            this.repaint(); // Everytime we set the color we ask the component to repaint itself
        }

        public ShapeToDraw getShape() {
            return shape;
        }

        public void setShape(ShapeToDraw shape) {
            this.shape = shape;
            this.repaint(); // Everytime we set the shape we ask the component to repaint itself
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200); // We define the panel's size
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(color != null ? color : Color.BLACK); //If we haven't set the Color yet, we default it to black, otherwise we set the color to the one chosen by the user.
            if (shape == ShapeToDraw.SQUARE) { //If the shape is a square, we draw a square
                g2d.draw(new Rectangle2D.Double(50, 50, 100, 100)); // Change the coordinates that you get by user click using the MouseListener
            } else if (shape == ShapeToDraw.CIRCLE) { // Or we draw a circle
                g2d.draw(new Ellipse2D.Double(50, 50, 100, 100));
            }
        }
    }
}

This is how the program looks like:

I am unsure how to record coordinates of a user's button click and to then pass those coordinates into the constructor of the desired shape.

To get the coordinates relative to your window see: How to get location of a mouse click relative to a swing window


来源: stackexchange

问:
What does the ! mean in the angular syntax?
I've been seeing this creep up in a few places now but have not found any answers on it.

I'm curious what the '!' bang does in the angular syntax.

答:
Its called the "Non-null assertion operator" and has nothing todo with Angular perse, it is from typescript.

```<code>let s = e!.name;  // Assert that e is non-null and access name
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Its called the "Non-null assertion operator" and has nothing todo with Angular perse, it is from typescript.

let s = e!.name;  // Assert that e is non-null and access name


问:
SQL Server Conditional Flow
If I write two SELECT statements in a IF EXISTS condition with a AND clause in between these select queries, does both queries get executed even if the first SELECT returns false?

```<code>IF EXISTS (SELECT....) AND EXISTS(SELECT ....)
BEGIN

END
</code>```

Does the SQL Server Engine execute both the SQL Statement in this scenario?

Thanks
Krish

答:
I'm taking the following quotes from the following blog entry on sqlteam:

How SQL Server short-circuits WHERE condition evaluation

It does when it feels like it, but not in the way you immediately think of.

As a developer you must be aware that SQL Server does not do short-circuiting like it is done in other programming languages and there's nothing you can do to force it to.

For further details check the first link in the above blog entry, which is leading to another blog:

Does SQL Server Short-Circuit?

The final verdict?  Well, I don't really have one yet, but it is probably safe to say that the only time you can ensure a specific short-circuit is when you express multiple WHEN conditions in a CASE expression.  With standard boolean expressions, the optimizer will move things around as it sees fit based on the tables, indexes and data you are querying.

ContentLicense: CC BY-SA 2.5

Title: SQL Server Conditional Flow

Body:
If I write two SELECT statements in a IF EXISTS condition with a AND clause in between these select queries, does both queries get executed even if the first SELECT returns false?

IF EXISTS (SELECT....) AND EXISTS(SELECT ....)
BEGIN

END

Does the SQL Server Engine execute both the SQL Statement in this scenario?

Thanks
Krish

ContentLicense: CC BY-SA 3.0


问:
How can I include JSON body API examples in Swagger2Markup API requirements (when converting from Swagger YAML)?
I've used the Swagger editor (editor.swagger.io) to create API requirements that look great online in a web browser, but I want to convert this Swagger YAML documentation into a format that can be printed (Word, PDF, Excel, HTML) and read offline.

The only way I've seen to convert the Swagger YAML into a clean, printable API requirements document is using the Swagger2Markup CLI (here's the reference documentation: http://swagger2markup.github.io/swagger2markup/1.3.3/ - Chapter 8 describes the CLI), then converting this adoc format to HTML from AsciiDoctor. The final product is very readable as you can see from the Swagger2Markup reference documentation.

However, unfortunately, the final Swagger2Markup documentation of an API doesn't include JSON or xml examples of the API body, which is arguably the most important part of the documentation in my opinion! For example, in the Swagger editor's petstore, this would be the json body example for the POST /pet API:

```<code>{
  "id": 0,
  "category": {
    "id": 0,
    "name": "string"
  },
  "name": "doggie",
  "photoUrls": [
    "string"
  ],
  "tags": [
    {
      "id": 0,
      "name": "string"
    }
  ],
  "status": "available"
}
</code>```

But this JSON example isn't included in the Swagger2Markup documentation.

So my question is, is it possible to update Swagger2Markup (or change the Swagger2Markup properties) to include JSON body API examples in the final document?

If not, is there a different way you recommend converting Swagger YAML into a readable document that includes JSON body API examples?

答: To add json body API examples to the adoc with swagger2markup, create a config file (config.properties) and add "swagger2markup.generatedExamplesEnabled=TRUE". Per the swagger2markup reference document, section 3.2.5, this property specifies if http rquest and response examples should be generated. Awesome!</p>

Body:
I've used the Swagger editor (editor.swagger.io) to create API requirements that look great online in a web browser, but I want to convert this Swagger YAML documentation into a format that can be printed (Word, PDF, Excel, HTML) and read offline.

The only way I've seen to convert the Swagger YAML into a clean, printable API requirements document is using the Swagger2Markup CLI (here's the reference documentation: http://swagger2markup.github.io/swagger2markup/1.3.3/ - Chapter 8 describes the CLI), then converting this adoc format to HTML from AsciiDoctor. The final product is very readable as you can see from the Swagger2Markup reference documentation.

However, unfortunately, the final Swagger2Markup documentation of an API doesn't include JSON or xml examples of the API body, which is arguably the most important part of the documentation in my opinion! For example, in the Swagger editor's petstore, this would be the json body example for the POST /pet API:

{
  "id": 0,
  "category": {
    "id": 0,
    "name": "string"
  },
  "name": "doggie",
  "photoUrls": [
    "string"
  ],
  "tags": [
    {
      "id": 0,
      "name": "string"
    }
  ],
  "status": "available"
}

But this JSON example isn't included in the Swagger2Markup documentation.

So my question is, is it possible to update Swagger2Markup (or change the Swagger2Markup properties) to include JSON body API examples in the final document?

If not, is there a different way you recommend converting Swagger YAML into a readable document that includes JSON body API examples?


问:
How to increase efficiency while web scraping?
I have a node script that is constantly scraping a list of websites for information. I would like to try and increase the efficiency of the script; however, nodejs a is single-threaded runtime. But behind the scenes, nodejs is multi-threaded to allow for asynchronous code. Is there a way to take advantage of this to increase efficiency? If not, alternatives?

Right now the script runs synchronously. I have tried a mix of synchronous and asynchronous code, but I always exhausted the stack. Example code does not include logic, for scraping the data or checking the data, because it is irrelevant.

const request = require('request-promise');
const cheerio = require('cheerio');

const siteList = require('./websites.json');

async function scrapePage(link)
{
    let $, data = {};

    $ = await request({
        uri: link,
        transform: (body) => { return cheerio.load(body) },
        connection : 'keep-alive',
    });

    // Scrape data using cheerio

    return data;
}

async function scrapePages()
{
    for(let site of siteList)
    {
        let data = await scrapePage(site.url);

        // Check data for favored result
    }

    // Tail call to reuse stack space
    return scrapePages();
}

scrapePages();
```

For individuals questioning the scope of the scraping, the list of websites is less than 100.

答:
Your code right now is going to wait for scrapePage() to finish:

```<code>let data = await scrapePage(site.url);
</code>```

If you want to scrape multiple pages at a time, change the way your for loop works.  Use .forEach() on an array, for example.

To make it easy to control the number of simultaneous operations, consider a package like await-semaphore.

https://www.npmjs.com/package/await-semaphore

Then, you can do something like this...

```<code>import {Semaphore} from 'await-semaphore';
const semaphore = new Semaphore(10); // 10 operations at a time

// Then, inside a loop...
semaphore.use(() => {
  // do your work here
});
</code>```

Body:
I have a node script that is constantly scraping a list of websites for information. I would like to try and increase the efficiency of the script; however, nodejs a is single-threaded runtime. But behind the scenes, nodejs is multi-threaded to allow for asynchronous code. Is there a way to take advantage of this to increase efficiency? If not, alternatives?

Right now the script runs synchronously. I have tried a mix of synchronous and asynchronous code, but I always exhausted the stack. Example code does not include logic, for scraping the data or checking the data, because it is irrelevant.

const request = require('request-promise');
const cheerio = require('cheerio');

const siteList = require('./websites.json');

async function scrapePage(link)
{
    let $, data = {};

    $ = await request({
        uri: link,
        transform: (body) => { return cheerio.load(body) },
        connection : 'keep-alive',
    });

    // Scrape data using cheerio

    return data;
}

async function scrapePages()
{
    for(let site of siteList)
    {
        let data = await scrapePage(site.url);

        // Check data for favored result
    }

    // Tail call to reuse stack space
    return scrapePages();
}

scrapePages();

For individuals questioning the scope of the scraping, the list of websites is less than 100.

Body:
Your code right now is going to wait for scrapePage() to finish:

let data = await scrapePage(site.url);

If you want to scrape multiple pages at a time, change the way your for loop works.  Use .forEach() on an array, for example.

To make it easy to control the number of simultaneous operations, consider a package like await-semaphore.

https://www.npmjs.com/package/await-semaphore

Then, you can do something like this...

import {Semaphore} from 'await-semaphore';
const semaphore = new Semaphore(10); // 10 operations at a time

// Then, inside a loop...
semaphore.use(() => {
  // do your work here
});


问:
Drawing in a WPF App (.NET Core) throws a runtime error
I'm trying to port a WPF graphics application to .NET Core.  I found a test case on the web, but it doesn't work with the latest (Preview) release of .NET core.
The program throws an exception on line 6.

Here is a screen capture of my Visual Studio 2019 screen:

The screen capture may be hard to read, so here is my code:

```<code>using System.Windows;
using System.Drawing;

using Brushes = System.Drawing.Brushes;
using Color = System.Drawing.Color;
using FontFamily = System.Drawing.FontFamily;
using FontStyle = System.Drawing.FontStyle;
using Image = System.Drawing.Image;
using Pen = System.Drawing.Pen;
using Point = System.Drawing.Point;

namespace TestGraphics {
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow:Window {
    private static void TestGraphics() {
      System.Drawing.Image image = new Bitmap(2000, 1024);
      Graphics graph = Graphics.FromImage(image);
      graph.Clear(System.Drawing.Color.Azure);
      Pen pen = new Pen(Brushes.Black);
      graph.DrawLines(pen, new Point[] { new Point(10, 10), new Point(800, 900) });
      graph.DrawString("Hello drawing from .NET Core :)",
                       new Font(new FontFamily("DecoType Thuluth"),
                                20,
                                System.Drawing.FontStyle.Bold),
                       Brushes.Blue,
                       new PointF(150, 90));
    }
    public MainWindow() {
      InitializeComponent();
      TestGraphics();
    }
  }
}
</code>```

Here is my ".csproj":

```<code><Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.Compatibility" Version="3.0.0-preview5.19224.8" />
    <PackageReference Include="System.Drawing.Common" Version="4.6.0-preview5.19224.8" />
  </ItemGroup>

</Project>
</code>```

I hope someone can suggest a fix for this problem.

Charles

答:
Microsoft released a cross platform library for .NET core to handle System.Drawing:

System.Drawing.Common

I haven't used it yet, but should do the trick.

Body:
I'm trying to port a WPF graphics application to .NET Core.  I found a test case on the web, but it doesn't work with the latest (Preview) release of .NET core.
The program throws an exception on line 6.

Here is a screen capture of my Visual Studio 2019 screen:

The screen capture may be hard to read, so here is my code:

using System.Windows;
using System.Drawing;

using Brushes = System.Drawing.Brushes;
using Color = System.Drawing.Color;
using FontFamily = System.Drawing.FontFamily;
using FontStyle = System.Drawing.FontStyle;
using Image = System.Drawing.Image;
using Pen = System.Drawing.Pen;
using Point = System.Drawing.Point;

namespace TestGraphics {
  ///
  /// Interaction logic for MainWindow.xaml
  ///
  public partial class MainWindow:Window {
    private static void TestGraphics() {
      System.Drawing.Image image = new Bitmap(2000, 1024);
      Graphics graph = Graphics.FromImage(image);
      graph.Clear(System.Drawing.Color.Azure);
      Pen pen = new Pen(Brushes.Black);
      graph.DrawLines(pen, new Point[] { new Point(10, 10), new Point(800, 900) });
      graph.DrawString("Hello drawing from .NET Core :)",
                       new Font(new FontFamily("DecoType Thuluth"),
                                20,
                                System.Drawing.FontStyle.Bold),
                       Brushes.Blue,
                       new PointF(150, 90));
    }
    public MainWindow() {
      InitializeComponent();
      TestGraphics();
    }
  }
}

Here is my ".csproj":

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UseWPF>true</UseWPF>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Windows.Compatibility" Version="3.0.0-preview5.19224.8" />
    <PackageReference Include="System.Drawing.Common" Version="4.6.0-preview5.19224.8" />
  </ItemGroup>

</Project>

I hope someone can suggest a fix for this problem.

Charles


问:
How to explain embedded message binary wire format of protocol buffer?
I'm trying to understand protocol buffer encoding method, when translating message to binary(or hexadecimal) format, I can't understand how the embedded message is encoded.

I guess maybe it's related to memory address, but I can't find the accurate relationship.

Here is what i've done.

Step 1: I defined two messages in test.proto file,

```<code>syntax = "proto3";
package proto_test;

message Education {
    string college = 1;
}

message Person {
    int32 age = 1;
    string name = 2;
    Education edu = 3;
}
</code>```

Step 2: And then I generated some go code,

```<code>protoc --go_out=. test.proto
</code>```

Step 3: Then I check the encoded format of the message,

p := proto_test.Person{
    Age:  666,
    Name: "Tom",
    Edu: &proto_test.Education{
        College: "SOMEWHERE",
    },
}
var b []byte
out, err := p.XXX_Marshal(b, true)
if err != nil {
    log.Fatalln("fail to marshal with error: ", err)
}
fmt.Printf("hexadecimal format:% x \n", out)
fmt.Printf("binary format:% b \n", out)
```

<p>which outputs,</p>

<pre class="lang-sh prettyprint-override"><code>hexadecimal format:08 9a 05 12 03 54 6f 6d 1a fd 96 d1 08 0a 09 53 4f 4d 45 57 48 45 52 45
binary format:[ 1000  10011010  101  10010  11  1010100  1101111  1101101  11010  11111101  10010110  11010001  1000  1010  1001  1010011  1001111  1001101  1000101  1010111  1001000  1000101  1010010  1000101]
</code>```

what I understand is ,

08                         - int32 wire type with tag number 1
9a 05                      - Varints for 666
12                         - string wire type with tag number 2
03                         - length delimited which is 3 byte
54 6f 6d                   - ascii for "TOM"
1a                         - embedded message wire type with tag number 3
fd 96 d1 08                - ? (here is what I don't understand)
0a                         - string wire type with tag number 1
09                         - length delimited which is 9 byte
53 4f 4d 45 57 48 45 52 45 - ascii for "SOMEWHERE"
```

What does fd 96 d1 08 stands for?
It seems like that d1 08 always be there, but fd 96 sometimes change, don't know why. Thanks for answering :)

Add

I debugged the marshal process and reported a bug here.

答:
At that location I/you would expect the number of bytes in the embedded message.

I have repeated your experiment in Python.

```<code>msg = Person()
msg.age = 666
msg.name = "Tom"
msg.edu.college = "SOMEWHERE"
</code>```

I got a different result, the one I would expect. A varint stating the size of the embedded message.

```<code>0x08
0x9A, 0x05
0x12
0x03
0x54 0x6F 0x6D
0x1A
0x0B                        <- Equals to 11 decimal.
0x0A
0x09
0x53 0x4F 0x4D 0x45 0x57 0x48 0x45 0x52 0x45
</code>```

Next I deserialized your bytes:

```<code>msg2 = Person()
str = bytearray(b'\x08\x9a\x05\x12\x03\x54\x6f\x6d\x1a\xfd\x96\xd1\x08\x0a\x09\x53\x4f\x4d\x45\x57\x48\x45\x52\x45')
msg2.ParseFromString(str)
print(msg2)
</code>```

The result of this is perfect:

```<code>age: 666
name: "Tom"
edu {
  college: "SOMEWHERE"
}
</code>```

The conclusion I come to is that there are some different ways of encoding in Protobuf. I do not know what is done in this case but I know the example of a negative 32 bit varint. A positive varint is encoded in five bytes, a negative value is cast as a 64 bit value and encoded to ten bytes.

Body:
I'm trying to understand protocol buffer encoding method, when translating message to binary(or hexadecimal) format, I can't understand how the embedded message is encoded.

I guess maybe it's related to memory address, but I can't find the accurate relationship.

Here is what i've done.

Step 1: I defined two messages in test.proto file,

syntax = "proto3";
package proto_test;

message Education {
    string college = 1;
}

message Person {
    int32 age = 1;
    string name = 2;
    Education edu = 3;
}

Step 2: And then I generated some go code,

protoc --go_out=. test.proto

Step 3: Then I check the encoded format of the message,

p := proto_test.Person{
    Age:  666,
    Name: "Tom",
    Edu: &proto_test.Education{
        College: "SOMEWHERE",
    },
}
var b []byte
out, err := p.XXX_Marshal(b, true)
if err != nil {
    log.Fatalln("fail to marshal with error: ", err)
}
fmt.Printf("hexadecimal format:% x \n", out)
fmt.Printf("binary format:% b \n", out)

which outputs,

hexadecimal format:08 9a 05 12 03 54 6f 6d 1a fd 96 d1 08 0a 09 53 4f 4d 45 57 48 45 52 45
binary format:[ 1000  10011010  101  10010  11  1010100  1101111  1101101  11010  11111101  10010110  11010001  1000  1010  1001  1010011  1001111  1001101  1000101  1010111  1001000  1000101  1010010  1000101]

what I understand is ,

08                         - int32 wire type with tag number 1
9a 05                      - Varints for 666
12                         - string wire type with tag number 2
03                         - length delimited which is 3 byte
54 6f 6d                   - ascii for "TOM"
1a                         - embedded message wire type with tag number 3
fd 96 d1 08                - ? (here is what I don't understand)
0a                         - string wire type with tag number 1
09                         - length delimited which is 9 byte
53 4f 4d 45 57 48 45 52 45 - ascii for "SOMEWHERE"

What does fd 96 d1 08 stands for?
It seems like that d1 08 always be there, but fd 96 sometimes change, don't know why. Thanks for answering :)

Add

I debugged the marshal process and reported a bug here.

Body:
At that location I/you would expect the number of bytes in the embedded message.

I have repeated your experiment in Python.

msg = Person()
msg.age = 666
msg.name = "Tom"
msg.edu.college = "SOMEWHERE"

I got a different result, the one I would expect. A varint stating the size of the embedded message.

0x08
0x9A, 0x05
0x12
0x03
0x54 0x6F 0x6D
0x1A
0x0B                        <- Equals to 11 decimal.
0x0A
0x09
0x53 0x4F 0x4D 0x45 0x57 0x48 0x45 0x52 0x45

Next I deserialized your bytes:

msg2 = Person()
str = bytearray(b'\x08\x9a\x05\x12\x03\x54\x6f\x6d\x1a\xfd\x96\xd1\x08\x0a\x09\x53\x4f\x4d\x45\x57\x48\x45\x52\x45')
msg2.ParseFromString(str)
print(msg2)

The result of this is perfect:

age: 666
name: "Tom"
edu {
  college: "SOMEWHERE"
}

The conclusion I come to is that there are some different ways of encoding in Protobuf. I do not know what is done in this case but I know the example of a negative 32 bit varint. A positive varint is encoded in five bytes, a negative value is cast as a 64 bit value and encoded to ten bytes.


问:
Select employees with less than 10 leaves in a given date range
I have a document with below structure

```<code>{
   id:1,
   leaves:[
            {
               "reason":"",
               "date":"2019-01-01"
            },
            {
               "reason":"",
               "date":"2019-04-30"
            }
          ]
}
</code>```

leaves is a nested document. Document structure can be changed.
I need to select employees with less that 10 leaves in a given range -2019-01-01 to 2019-05-30.

I tried bucket selector aggregation but "min_bucket" bucket path was not pointing to empty buckets (needed where no leaves where present in range). I was getting below response and no records were returned.

```<code>  "max_hourly_inner" : {
              "value" : null,
              "keys" : [ ]
            }
</code>```

答:
I came up with the below query. Its a bit tricky when it comes to performing aggregations on nested, however you can achieve it via the following aggregations which I've used.

Terms Aggregation

Nested Aggregation

Date Range Aggregation

Bucket Selector Aggregation

The equation I'm solving is show me the list of students with less than 2 leaves in specified date range i.e. from 2019-04-01 to 2019-05-30

Sample Documents:

```<code>// This student has 3 leaves over all and all 3 leaves in the specified date
POST myleaves/_doc/1
{
  "id": 1001,
  "leaves" : [
    {
      "reason" : "",
      "date" : "2019-04-01"
    },
    {
      "reason" : "",
      "date" : "2019-04-29"
    },
    {
      "reason" : "",
      "date" : "2019-04-30"
    }
  ]
}

//This student has 4 leaves out of which 2 are in specified date range
POST myleaves/_doc/2
{
  "id": 1002,
  "leaves" : [
    {
      "reason" : "",
      "date" : "2019-04-01"
    },
    {
      "reason" : "",
      "date" : "2019-04-04"
    },
    {
      "reason" : "",
      "date" : "2019-07-29"
    },
    {
      "reason" : "",
      "date" : "2019-07-30"
    }
  ]
}

// This student has one leave but no leaves in specified date range
POST myleaves/_doc/3
{
  "id": 1003,
  "leaves":[
    {
      "reason" : "",
      "date" : "2019-07-29"
    }
  ]
}

//This student has no leaves at all
POST myleaves/_doc/4
{
  "id": 1004,
  "leaves":[

    ]
}
</code>```

Below is the structure of the aggregation query

```<code>- Terms Aggregation on `id` field
 - Nested Aggregation on `leaves` field
  - Date Range aggregation on `leaves.date` field
   - Bucket Selector Aggregation on `count`. This is the part where we specify our condition
 - Bucket Selector Aggregation to retrieve only documents having one bucket. (To avoid showing bucket with 0 doc counts)
</code>```

Aggregation Query:

```<code>POST <your_index_name>/_search
{
   "size":0,
   "aggs":{
      "mystudents":{
         "terms":{
            "field":"id",
            "size":10
         },
         "aggs":{
            "mycount":{
               "nested":{
                  "path":"leaves"
               },
               "aggs": {
                 "valid_dates": {
                   "date_range": {
                     "field": "leaves.date",
                     "ranges": [
                       {
                         "from": "2019-04-01",
                         "to": "2019-05-30"
                       }
                     ]
                   },
                   "aggs": {
                     "myselector": {
                       "bucket_selector": {
                         "buckets_path": {
                           "myparams": "_count"
                         },
                         "script": "params.myparams <= 2"    <---- You may have to change this for less than 10 leaves params.myparams <=10
                       }
                     }
                   }
                 }
               }
            },
            "mybucket_selector":{
               "bucket_selector":{
                  "buckets_path":{
                     "my_bucket_count":"mycount>valid_dates._bucket_count"
                  },
                  "script":"params.my_bucket_count == 1"
               }
            }
         }
      }
   }
}
</code>```

Note the comment I've mentioned in the aggregation query.

Aggregation Response:

```<code>{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 4,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "mystudents" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 1002,
          "doc_count" : 1,
          "mycount" : {
            "doc_count" : 4,                                 <----- Total Count of Leaves
            "valid_dates" : {
              "buckets" : [
                {
                  "key" : "2019-04-01T00:00:00.000Z-2019-05-30T00:00:00.000Z",
                  "from" : 1.5540768E12,
                  "from_as_string" : "2019-04-01T00:00:00.000Z",
                  "to" : 1.5591744E12,
                  "to_as_string" : "2019-05-30T00:00:00.000Z",
                  "doc_count" : 2                            <------ Count of leaves in specified range
                }
              ]
            }
          }
        },
        {
          "key" : 1003,
          "doc_count" : 1,
          "mycount" : {
            "doc_count" : 1,
            "valid_dates" : {
              "buckets" : [
                {
                  "key" : "2019-04-01T00:00:00.000Z-2019-05-30T00:00:00.000Z",
                  "from" : 1.5540768E12,
                  "from_as_string" : "2019-04-01T00:00:00.000Z",
                  "to" : 1.5591744E12,
                  "to_as_string" : "2019-05-30T00:00:00.000Z",
                  "doc_count" : 0
                }
              ]
            }
          }
        },
        {
          "key" : 1004,
          "doc_count" : 1,
          "mycount" : {
            "doc_count" : 0,
            "valid_dates" : {
              "buckets" : [
                {
                  "key" : "2019-04-01T00:00:00.000Z-2019-05-30T00:00:00.000Z",
                  "from" : 1.5540768E12,
                  "from_as_string" : "2019-04-01T00:00:00.000Z",
                  "to" : 1.5591744E12,
                  "to_as_string" : "2019-05-30T00:00:00.000Z",
                  "doc_count" : 0
                }
              ]
            }
          }
        }
      ]
    }
  }
}
</code>```

If you look at the response,

1001 didn't appear as he had more than 2 leaves in specified date range,

1002 appears because he had exactly 2 leaves out of 4 leaves he has taken in specified date range

1003 and 1004 appears as they have not taken any leaves in the specified range.

Clause is select students with less than 2 leaves (including students who has not taken any leaves) in specified date range.

Hope this helps!

Body:
I have a document with below structure

{
   id:1,
   leaves:[
            {
               "reason":"",
               "date":"2019-01-01"
            },
            {
               "reason":"",
               "date":"2019-04-30"
            }
          ]
}

leaves is a nested document. Document structure can be changed.
I need to select employees with less that 10 leaves in a given range -2019-01-01 to 2019-05-30.

I tried bucket selector aggregation but "min_bucket" bucket path was not pointing to empty buckets (needed where no leaves where present in range). I was getting below response and no records were returned.

  "max_hourly_inner" : {
              "value" : null,
              "keys" : [ ]
            }

Body:
I came up with the below query. Its a bit tricky when it comes to performing aggregations on nested, however you can achieve it via the following aggregations which I've used.

Terms Aggregation

Nested Aggregation

Date Range Aggregation

Bucket Selector Aggregation

The equation I'm solving is show me the list of students with less than 2 leaves in specified date range i.e. from 2019-04-01 to 2019-05-30

Sample Documents:

// This student has 3 leaves over all and all 3 leaves in the specified date
POST myleaves/_doc/1
{
  "id": 1001,
  "leaves" : [
    {
      "reason" : "",
      "date" : "2019-04-01"
    },
    {
      "reason" : "",
      "date" : "2019-04-29"
    },
    {
      "reason" : "",
      "date" : "2019-04-30"
    }
  ]
}

//This student has 4 leaves out of which 2 are in specified date range
POST myleaves/_doc/2
{
  "id": 1002,
  "leaves" : [
    {
      "reason" : "",
      "date" : "2019-04-01"
    },
    {
      "reason" : "",
      "date" : "2019-04-04"
    },
    {
      "reason" : "",
      "date" : "2019-07-29"
    },
    {
      "reason" : "",
      "date" : "2019-07-30"
    }
  ]
}

// This student has one leave but no leaves in specified date range
POST myleaves/_doc/3
{
  "id": 1003,
  "leaves":[
    {
      "reason" : "",
      "date" : "2019-07-29"
    }
  ]
}

//This student has no leaves at all
POST myleaves/_doc/4
{
  "id": 1004,
  "leaves":[

    ]
}

Below is the structure of the aggregation query

- Terms Aggregation on `id` field
 - Nested Aggregation on `leaves` field
  - Date Range aggregation on `leaves.date` field
   - Bucket Selector Aggregation on `count`. This is the part where we specify our condition
 - Bucket Selector Aggregation to retrieve only documents having one bucket. (To avoid showing bucket with 0 doc counts)

Aggregation Query:

POST <your_index_name>/_search
{
   "size":0,
   "aggs":{
      "mystudents":{
         "terms":{
            "field":"id",
            "size":10
         },
         "aggs":{
            "mycount":{
               "nested":{
                  "path":"leaves"
               },
               "aggs": {
                 "valid_dates": {
                   "date_range": {
                     "field": "leaves.date",
                     "ranges": [
                       {
                         "from": "2019-04-01",
                         "to": "2019-05-30"
                       }
                     ]
                   },
                   "aggs": {
                     "myselector": {
                       "bucket_selector": {
                         "buckets_path": {
                           "myparams": "_count"
                         },
                         "script": "params.myparams <= 2"    <---- You may have to change this for less than 10 leaves params.myparams <=10
                       }
                     }
                   }
                 }
               }
            },
            "mybucket_selector":{
               "bucket_selector":{
                  "buckets_path":{
                     "my_bucket_count":"mycount>valid_dates._bucket_count"
                  },
                  "script":"params.my_bucket_count == 1"
               }
            }
         }
      }
   }
}

Note the comment I've mentioned in the aggregation query.

Aggregation Response:

{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 4,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "mystudents" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 1002,
          "doc_count" : 1,
          "mycount" : {
            "doc_count" : 4,                                 <----- Total Count of Leaves
            "valid_dates" : {
              "buckets" : [
                {
                  "key" : "2019-04-01T00:00:00.000Z-2019-05-30T00:00:00.000Z",
                  "from" : 1.5540768E12,
                  "from_as_string" : "2019-04-01T00:00:00.000Z",
                  "to" : 1.5591744E12,
                  "to_as_string" : "2019-05-30T00:00:00.000Z",
                  "doc_count" : 2                            <------ Count of leaves in specified range
                }
              ]
            }
          }
        },
        {
          "key" : 1003,
          "doc_count" : 1,
          "mycount" : {
            "doc_count" : 1,
            "valid_dates" : {
              "buckets" : [
                {
                  "key" : "2019-04-01T00:00:00.000Z-2019-05-30T00:00:00.000Z",
                  "from" : 1.5540768E12,
                  "from_as_string" : "2019-04-01T00:00:00.000Z",
                  "to" : 1.5591744E12,
                  "to_as_string" : "2019-05-30T00:00:00.000Z",
                  "doc_count" : 0
                }
              ]
            }
          }
        },
        {
          "key" : 1004,
          "doc_count" : 1,
          "mycount" : {
            "doc_count" : 0,
            "valid_dates" : {
              "buckets" : [
                {
                  "key" : "2019-04-01T00:00:00.000Z-2019-05-30T00:00:00.000Z",
                  "from" : 1.5540768E12,
                  "from_as_string" : "2019-04-01T00:00:00.000Z",
                  "to" : 1.5591744E12,
                  "to_as_string" : "2019-05-30T00:00:00.000Z",
                  "doc_count" : 0
                }
              ]
            }
          }
        }
      ]
    }
  }
}

If you look at the response,

1001 didn't appear as he had more than 2 leaves in specified date range,

1002 appears because he had exactly 2 leaves out of 4 leaves he has taken in specified date range

1003 and 1004 appears as they have not taken any leaves in the specified range.

Clause is select students with less than 2 leaves (including students who has not taken any leaves) in specified date range.

Hope this helps!


问:
Get key value from string using Powershell
I am trying to get key value using Regex in powershell.

```<code>$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name
</code>```

I want output like this :

```<code>$key1 = "value1"
$key2 = "value2"
$key3 = "value3"
</code>```

Output i am getting :

```<code>Name : :value1,key2:value2,
</code>```

答:
I see you already have you answer, but here is one more way to do this.</p>

```<code>("key1:value1,key2:value2,key3:value3").Split(',') |
%{$PSItem | ConvertFrom-Csv -Delimiter ':' -Header Name, Value}

# Results

Name Value
---- -----
key1 value1
key2 value2
key3 value3
</code>```

Body:
I am trying to get key value using Regex in powershell.

$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name

I want output like this :

$key1 = "value1"
$key2 = "value2"
$key3 = "value3"

Output i am getting :

Name : :value1,key2:value2,

Body:
I see you already have you answer, but here is one more way to do this.

("key1:value1,key2:value2,key3:value3").Split(',') |
%{$PSItem | ConvertFrom-Csv -Delimiter ':' -Header Name, Value}

# Results

Name Value
---- -----
key1 value1
key2 value2
key3 value3


问:
Is there some way to "figure out the application base dir" other than this?
I've made a PHP framework. To start it, you do:

```<code>require 'framework.php';
framework_start(__DIR__);
</code>```

I'm trying to eliminate the __DIR__ part, if at all possible. It's telling the framework what the "base dir" for the application is. I can't think of any way to determine the "__DIR__" for the file that calls framework_start(), from within framework_start().

I can't help but feel annoyed that it can't just be:

```<code>require 'framework.php';
framework_start();
</code>```

... and then framework_start(); somehow figures out the __DIR__ value on its own. But if I just reference __DIR__ from the PHP file that contains framework_start(), it will obviously return the wrong dir path.

Is this possible at all? If so, how?

答:
I would suggest the following. Define a constant at the top of framework.php file to be used in your framework instead of __DIR__:

```<code>$trace = debug_backtrace(false);
$levelsToGoUp = 0; // set to 1 if called from within the function
if (array_key_exists($levelsToGoUp, $trace)) {
    define('PARENTFILE', dirname($trace[$levelsToGoUp]['file']));
} else {
    define('PARENTFILE', __DIR__);
}
</code>```

If you called debug_backtrace() inside the function framework_start() you would need to look at the entry with key 1 in the array (the first is the function itself), which I would recommend.

Body:
I've made a PHP framework. To start it, you do:

require 'framework.php';
framework_start(__DIR__);

I'm trying to eliminate the __DIR__ part, if at all possible. It's telling the framework what the "base dir" for the application is. I can't think of any way to determine the "__DIR__" for the file that calls framework_start(), from within framework_start().

I can't help but feel annoyed that it can't just be:

require 'framework.php';
framework_start();

... and then framework_start(); somehow figures out the __DIR__ value on its own. But if I just reference __DIR__ from the PHP file that contains framework_start(), it will obviously return the wrong dir path.

Is this possible at all? If so, how?

Body:
I would suggest the following. Define a constant at the top of framework.php file to be used in your framework instead of __DIR__:

$trace = debug_backtrace(false);
$levelsToGoUp = 0; // set to 1 if called from within the function
if (array_key_exists($levelsToGoUp, $trace)) {
    define('PARENTFILE', dirname($trace[$levelsToGoUp]['file']));
} else {
    define('PARENTFILE', __DIR__);
}

If you called debug_backtrace() inside the function framework_start() you would need to look at the entry with key 1 in the array (the first is the function itself), which I would recommend.


问:
Default size for database fields
What the size that you use for common database fields, like firstName, lastName, Email, password, etc? I see these common fields in a lot of databases of blogs, forums, e-commerces, etc. But I don't know if there is some reference or default for the size for that common fields. So, I want to know what the method/reference/basis that you to use for selecting size for common fields.</p>

答:
What I tend to do is think of how long a field's value could possibly be, then double that to be safe.

E.g. Name: varchar(70)
Email: varchar(200)

OwnerDisplayName: Click Ok

Title: Default size for database fields

OwnerDisplayName: Fritz H

LastEditorDisplayName: Rich B


问:
Generic IDisposable wrapper for stream - alternative to catching all exceptions
So I've just written this implementation for a type that abstracts a file and implements IDisposable over the stream that it contains.  It is intended to be used in any project:

```<code>public void Dispose()
{
  if (_contentStream == null)
    return;
  lock (_contentStreamLocker)
  {
    if (_contentStream == null)
      return;

    try
    {
      _contentStream.Dispose();
    }
    catch (Exception)
    {
      //legitimate? - don't let any exception prevent
      //us from successfully disposing?
    }
    _contentStream = null;
  }
}
</code>```

So I feel dirty, obviously, because:

I'm catching Exception

I'm doing nothing with Exception

But since I can't guarantee the behaviour of the underlying stream (also accounting for custom implementations) - i.e. if it's already disposed or if it's in a state where the implementation decides disposal is impossible - I can't really see what else to do.

Obviously I shouldn't be hiding bad implementations of Stream's Dispose(); but I think there is a half-way-house here.

In particular is the fact that this object doesn't necessarily 'own' the stream, and therefore won't have to be always responsible for Dispose()ing.  It should therefore be tolerant to when the stream has been disposed by somebody else.

Clearly, in most cases this won't be an issue; get a file in a using block perhaps, read it, do something with it and then dispose of it.  But there's those edge-cases; and they bother me!

Initially I wrote it as catch(ObjectDisposedException){ } - but that's only an informal pattern that can't be relied upon either.

What should I do?  Keep it as this, despite the fact that exception gulping is bad karma? Gulp only ObjectDisposedException, even though that's not much better?  Or should I just not have any exception gulping or handling at all?

I can see merits in all cases; just can't figure out which of them wins.

答:
As you have said, if you do not own the disposable, then you should not dispose it. You should not be even temped to call Dispose.

Have a look at my answer here.

Disposing of arguments for an iterator block

UPDATE

OK, the question of whether you own the disposable is not answered by who created the disposable. Ownership can be passed to other classes. StreamReader will assume ownership as soon as a stream is passed to it. So the creator of stream does not have to calls dispose and can rely on StreamReader to do it.

Body:
So I've just written this implementation for a type that abstracts a file and implements IDisposable over the stream that it contains.  It is intended to be used in any project:

public void Dispose()
{
  if (_contentStream == null)
    return;
  lock (_contentStreamLocker)
  {
    if (_contentStream == null)
      return;

    try
    {
      _contentStream.Dispose();
    }
    catch (Exception)
    {
      //legitimate? - don't let any exception prevent
      //us from successfully disposing?
    }
    _contentStream = null;
  }
}

So I feel dirty, obviously, because:

I'm catching Exception

I'm doing nothing with Exception

But since I can't guarantee the behaviour of the underlying stream (also accounting for custom implementations) - i.e. if it's already disposed or if it's in a state where the implementation decides disposal is impossible - I can't really see what else to do.

Obviously I shouldn't be hiding bad implementations of Stream's Dispose(); but I think there is a half-way-house here.

In particular is the fact that this object doesn't necessarily 'own' the stream, and therefore won't have to be always responsible for Dispose()ing.  It should therefore be tolerant to when the stream has been disposed by somebody else.

Clearly, in most cases this won't be an issue; get a file in a using block perhaps, read it, do something with it and then dispose of it.  But there's those edge-cases; and they bother me!

Initially I wrote it as catch(ObjectDisposedException){ } - but that's only an informal pattern that can't be relied upon either.

What should I do?  Keep it as this, despite the fact that exception gulping is bad karma? Gulp only ObjectDisposedException, even though that's not much better?  Or should I just not have any exception gulping or handling at all?

I can see merits in all cases; just can't figure out which of them wins.


问:
How to print spiral array PHP
I have array and this function

$array = array(array(00,01,02,03), array(10,11,12,13), array(20,21,22,23));

```<code>function spiral($xSize, $ySize, array $matrix) {
$k = 0;
$l = 0;
$xSize--;
$ySize--;

while ($k <= $xSize && $l <= $ySize) {
    for ($i = $l; $i <= $ySize; ++$i) {
        print($matrix[$k][$i] + " ");
    }
    $k++;

    for ($i = $k; $i <= $xSize; ++$i) {
        print($matrix[$i][$ySize] + " ");
    }
    $ySize--;

    for ($i = $ySize; $i >= $l; --$i) {
        print($matrix[$xSize][$i] + " ");
    }
    $xSize--;

    for ($i = $xSize; $i >= $k; --$i) {
        print($matrix[$i][$l] + " ");
    }
    $l++;
}
}
</code>```

but don't working. Function must return this
00 01 02 03 13 23 22 21 20 10 11 12

but return this
01 23 13 23 22 21 20 10 11 12 11

答:
I have a better solution.
Here's how to print a spiral array:

```<code>function printSpiralArray($xSize, $ySize, $matrix){
    $printed = [];
    $numElems = $xSize*$ySize;
    $pos = [0,-1];
    $direction = 0;
    for($i=0;$i<$numElems;$i++){
        $checkPos = $pos;
        switch($direction%4){
            case 0:
                $checkPos[1]++;
            break;
            case 1:
                $checkPos[0]++;
            break;
            case 2:
                $checkPos[1]--;
            break;
            case 3:
                $checkPos[0]--;
            break;
        }
        if($checkPos[0]>=$xSize || $checkPos[1]>=$ySize || $checkPos[0]<0 || $checkPos[1]<0 || in_array($checkPos[0].'_'.$checkPos[1],$printed)){
            $direction++;
            $i--;
            continue;
        }
        $pos = $checkPos;
        echo $matrix[$pos[0]][$pos[1]]."\t";
        $printed[] = $pos[0].'_'.$pos[1];
    }
}
</code>```

And here's how to build a spiral array with given size:

```<code>function getSpiralArray($size){
    $matrix = [];
    $numElems = $size*$size;
    $pos = [0,-1];
    $direction = 0;
    $num = 1;
    for($i=0;$i<$numElems;$i++){
        $checkPos = $pos;
        switch($direction%4){
            case 0:
                $checkPos[1]++;
            break;
            case 1:
                $checkPos[0]++;
            break;
            case 2:
                $checkPos[1]--;
            break;
            case 3:
                $checkPos[0]--;
            break;
        }
        if($checkPos[0]>=$size || $checkPos[1]>=$size || $checkPos[0]<0 || $checkPos[1]<0 || isset($matrix[$checkPos[0]][$checkPos[1]])){
            $direction++;
            $i--;
            continue;
        }
        $pos = $checkPos;
        $matrix[$pos[0]][$pos[1]] = $num;
        $num++;

    }
    return $matrix;
}
</code>```

Title: How to print spiral array PHP

Body:
I have array and this function

$array = array(array(00,01,02,03), array(10,11,12,13), array(20,21,22,23));

function spiral($xSize, $ySize, array $matrix) {
$k = 0;
$l = 0;
$xSize--;
$ySize--;

while ($k <= $xSize && $l <= $ySize) {
    for ($i = $l; $i <= $ySize; ++$i) {
        print($matrix[$k][$i] + " ");
    }
    $k++;

    for ($i = $k; $i <= $xSize; ++$i) {
        print($matrix[$i][$ySize] + " ");
    }
    $ySize--;

    for ($i = $ySize; $i >= $l; --$i) {
        print($matrix[$xSize][$i] + " ");
    }
    $xSize--;

    for ($i = $xSize; $i >= $k; --$i) {
        print($matrix[$i][$l] + " ");
    }
    $l++;
}
}

but don't working. Function must return this
00 01 02 03 13 23 22 21 20 10 11 12

but return this
01 23 13 23 22 21 20 10 11 12 11

Body:
I have a better solution.
Here's how to print a spiral array:

function printSpiralArray($xSize, $ySize, $matrix){
    $printed = [];
    $numElems = $xSize*$ySize;
    $pos = [0,-1];
    $direction = 0;
    for($i=0;$i<$numElems;$i++){
        $checkPos = $pos;
        switch($direction%4){
            case 0:
                $checkPos[1]++;
            break;
            case 1:
                $checkPos[0]++;
            break;
            case 2:
                $checkPos[1]--;
            break;
            case 3:
                $checkPos[0]--;
            break;
        }
        if($checkPos[0]>=$xSize || $checkPos[1]>=$ySize || $checkPos[0]<0 || $checkPos[1]<0 || in_array($checkPos[0].'_'.$checkPos[1],$printed)){
            $direction++;
            $i--;
            continue;
        }
        $pos = $checkPos;
        echo $matrix[$pos[0]][$pos[1]]."\t";
        $printed[] = $pos[0].'_'.$pos[1];
    }
}

And here's how to build a spiral array with given size:

function getSpiralArray($size){
    $matrix = [];
    $numElems = $size*$size;
    $pos = [0,-1];
    $direction = 0;
    $num = 1;
    for($i=0;$i<$numElems;$i++){
        $checkPos = $pos;
        switch($direction%4){
            case 0:
                $checkPos[1]++;
            break;
            case 1:
                $checkPos[0]++;
            break;
            case 2:
                $checkPos[1]--;
            break;
            case 3:
                $checkPos[0]--;
            break;
        }
        if($checkPos[0]>=$size || $checkPos[1]>=$size || $checkPos[0]<0 || $checkPos[1]<0 || isset($matrix[$checkPos[0]][$checkPos[1]])){
            $direction++;
            $i--;
            continue;
        }
        $pos = $checkPos;
        $matrix[$pos[0]][$pos[1]] = $num;
        $num++;

    }
    return $matrix;
}


问:
How to make a js code output run within a specific DIV background
I run into a nice JS from codepen that outputs bouncing balls https://codepen.io/rglazebrook/pen/JbxaI

I tried to use it as a background to a specific div inside a webpage but when I use that code the output appears under the website footer (if you look into this empty page http://www.doronwolf.com/home2019/ and scroll way down you will see the bouncing are successfully loaded but only under the footer)
 so, how can I make that js code output run within the page and preferably within specific div called 'herosection' inside my page and not under the footer? down beleow,

you can see the js code but please note that it depends on an external script that can be found here: https://rawgithub.com/soulwire/sketch.js/master/js/sketch.min.js

```<code>var particles = [],
particleCount = 200;
Particle = function(x,y) {
  this.x = x;
  this.y = y;
  this.radius = random(3,30);
  this.rgba = 'rgba('+floor(random(0,255))+','+floor(random(0,255))+','+floor(random(0,255))+','+random(.1,.8)+')';
  this.vx = random(-2,2);
  this.vy = random(-2,2);

  // Draw our particle to the canvas.
  this.draw = function(ctx) {
    ctx.fillStyle = this.rgba;
    ctx.beginPath();
    ctx.arc(this.x,this.y,this.radius,0,TWO_PI);
    ctx.fill();
  };

  // Update our position.
  this.update = function(ctx) {
    this.x += this.vx;
    this.y += this.vy;
    // Bounce off edges.
    if(this.x + this.radius > ctx.width) {
      this.vx *= -1;
      this.x = ctx.width - this.radius;
    }
    if(this.x - this.radius < 0) {
      this.vx *= -1;
      this.x = this.radius;
    }
    if(this.y + this.radius > ctx.height) {
      this.vy *= -1;
      this.y = ctx.height - this.radius;
    }
    if(this.y - this.radius < 0) {
      this.vy *= -1;
      this.y = this.radius;
    }
  }
};

var sketch = Sketch.create({
setup: function() {
var i = particleCount;
while(i--) {
  var p = new Particle(random(0, this.width),random(0, this.height));
  particles.push(p);
}
 },
update: function() {
var i = particleCount;
while(i--) {
  particles[i].update(this);
}
},
draw: function() {
var i = particleCount;
while(i--) {
  particles[i].draw(this);
}
}
});
</code>```

答:
there isn't a simple way of doing this with only the sketchjs librarie. try wrapping it in the p5 framework, they have helpers for that.

I did basic positing using

container: document.getElementById("YOURID")
 fullscreen: false,
 width: 3000,
 height: 400,
 as options to the Sketch.create() function

link to pen

Body:
I run into a nice JS from codepen that outputs bouncing balls https://codepen.io/rglazebrook/pen/JbxaI

I tried to use it as a background to a specific div inside a webpage but when I use that code the output appears under the website footer (if you look into this empty page http://www.doronwolf.com/home2019/ and scroll way down you will see the bouncing are successfully loaded but only under the footer)
 so, how can I make that js code output run within the page and preferably within specific div called 'herosection' inside my page and not under the footer? down beleow,

you can see the js code but please note that it depends on an external script that can be found here: https://rawgithub.com/soulwire/sketch.js/master/js/sketch.min.js

var particles = [],
particleCount = 200;
Particle = function(x,y) {
  this.x = x;
  this.y = y;
  this.radius = random(3,30);
  this.rgba = 'rgba('+floor(random(0,255))+','+floor(random(0,255))+','+floor(random(0,255))+','+random(.1,.8)+')';
  this.vx = random(-2,2);
  this.vy = random(-2,2);

  // Draw our particle to the canvas.
  this.draw = function(ctx) {
    ctx.fillStyle = this.rgba;
    ctx.beginPath();
    ctx.arc(this.x,this.y,this.radius,0,TWO_PI);
    ctx.fill();
  };

  // Update our position.
  this.update = function(ctx) {
    this.x += this.vx;
    this.y += this.vy;
    // Bounce off edges.
    if(this.x + this.radius > ctx.width) {
      this.vx *= -1;
      this.x = ctx.width - this.radius;
    }
    if(this.x - this.radius < 0) {
      this.vx *= -1;
      this.x = this.radius;
    }
    if(this.y + this.radius > ctx.height) {
      this.vy *= -1;
      this.y = ctx.height - this.radius;
    }
    if(this.y - this.radius < 0) {
      this.vy *= -1;
      this.y = this.radius;
    }
  }
};

var sketch = Sketch.create({
setup: function() {
var i = particleCount;
while(i--) {
  var p = new Particle(random(0, this.width),random(0, this.height));
  particles.push(p);
}
 },
update: function() {
var i = particleCount;
while(i--) {
  particles[i].update(this);
}
},
draw: function() {
var i = particleCount;
while(i--) {
  particles[i].draw(this);
}
}
});


问:
Add class to child
 under
 when div is clicked
the un-ordered lists on the page has an id but the child li elements has no class. i'm trying assign a class to all of the first level li elements when the parent div "top_nav" is clicked

i tried the below jquery script

$(document).on('click', 'div#top_nav ul li', function {
  $(this).child().addclass('new-class')
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="top-nav">
  show nav
  <ul id="root-nav">
    <li class="active">First Menu Item </li>
    <li>First Menu Item </li>
    <li>First Menu Item </li>
    <li>First Menu Item </li>
  </ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

after running the code , the class is not getting added when the div is clicked. can i have a second set of eyes just in case i'm missing something.

答:
You have a bunch of typos in your code. You're missing the () after function. .child() should be .children() and .addclass() should be .addClass(). #top_nav should be #top-nav.

You have the event handler on the wrong element. If you want to click on the top-nav element, it should be delegated to div#top-nav, not div#top-nav ul li. The li elements aren't direct children of top-nav, so you need to use .find() rather than .children().

$(document).on('click', 'div#top-nav', function() {
  $(this).find('> ul > li').addClass('new-class')
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.new-class {
  color: red;
}</code>```

  show nav

First Menu Item

First Menu Item

First Menu Item

First Menu Item

```

Title: Add class to child <li> under <ul> when div is clicked

Body:
the un-ordered lists on the page has an id but the child li elements has no class. i'm trying assign a class to all of the first level li elements when the parent div "top_nav" is clicked

i tried the below jquery script

$(document).on('click', 'div#top_nav ul li', function {
  $(this).child().addclass('new-class')
});

  show nav

First Menu Item

First Menu Item

First Menu Item

First Menu Item

after running the code , the class is not getting added when the div is clicked. can i have a second set of eyes just in case i'm missing something.

Body:
You have a bunch of typos in your code. You're missing the () after function. .child() should be .children() and .addclass() should be .addClass(). #top_nav should be #top-nav.

You have the event handler on the wrong element. If you want to click on the top-nav element, it should be delegated to div#top-nav, not div#top-nav ul li. The li elements aren't direct children of top-nav, so you need to use .find() rather than .children().

$(document).on('click', 'div#top-nav', function() {
  $(this).find('> ul > li').addClass('new-class')
});

.new-class {
  color: red;
}

<div id="top-nav">
  <a id="nav-icon">show nav</a>
  <ul id="root-nav">
    <li class="active">First Menu Item </li>
    <li>First Menu Item </li>
    <li>First Menu Item </li>
    <li>First Menu Item </li>
  </ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
Can I enumerate a variable group in VSTS?
TL;DR: Search and replace placeholders in a text file with the decrypted values of secrets in a variable group.

I would like to use a PowerShell script to receive a variable group in a release pipeline and then iterate through the list, performing search-and-replace on a file being released.

The variables in the variable list are secrets so I want to overwrite the placeholders in the file with the decrypted value of the variables.

The values of the variables are environment specific, so I do not want to provide the values at build time and do not want to include the decrypted values in a stored artifact.

The file being search-replaced will be used in an execution at release time but will not be deployed to a host, so will be destroyed upon completion of the pipeline execution.

答:
The Tokenization task from the Visual Studio Marketplace does this job well.  You'll need to install it into your Azure DevOps organisation, it's available at https://marketplace.visualstudio.com/items?itemName=TotalALM.totalalm-tokenization

By default the Tokenization task uses double underscores to identify the placeholders.  It will replace any text that that matches the name of a variable in your release definition as long as it's surrounded by double underscores.

So if you want to write the value of a variable called MySecretVariable into your file you'll need to add a place holder like __MySecretVariable__ into the file where ever you want that value to be written.

The Tokenization task will write any encrypted values into the file in plain text but in the release logs they will be obfuscated.

If you're storing your variables in a variable group just link that to the release definition and set the scope to the appropriate environment.