问:
KeyListener is irresponsive
I want to make a plane move across the board.
This should be pretty simple since I"ve done it before
I've setFocusable(true), I've added KeyListener, and I've also requestFocusInWindow()

I don't know what's wrong

When a key is pressed, it won't even enter the KeyPressed method

I tested by trying to print out "hi".

```<code>    package game;

    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JFrame;

    public class GUI{

        /* Author: Carl Zhang
         * Date:
         *
         */

        //player's username
        public static String user;

        //classes
        public static GUI gui;
        public static LoginPanel lp;
        public static MenuPanel mp;
        public static GamePanel gp;
        public static HighscorePanel hp;

        public static InstructionPanel ip;

        //dimensions
        private static final int WIDTH = 500;
        private static final int HEIGHT = 500;

        public GUI() {

        JFrame frame = new JFrame("ZCraft");
            frame.setSize(WIDTH, HEIGHT);
            frame.setResizable(false);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);

        //adding JPanels
        lp = new LoginPanel();
        frame.add(lp);

        mp = new MenuPanel();
        frame.add(mp);

        gp = new GamePanel();
        frame.add(gp);

        ip = new InstructionPanel();
        frame.add(ip);

        hp = new HighscorePanel();
        frame.add(hp);

        frame.setVisible(true);

    }//end constructor GUI()

    public static int getWidth() {
        return WIDTH;

    }//end getWIDTH()

    public static int getHeight() {
        return HEIGHT;

    }//end getHEIGHT

    public static void main(String[] args) {
        gui = new GUI();

    }//end main

}//end class GUI

        package game;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Timer;

public class GamePanel extends JPanel implements ActionListener, KeyListener {

    public static GamePanel gp;

    private boolean up = false;
    private boolean right = false;
    private boolean down = false;
    private boolean left = false;

    private ZCraft player;

    private JButton pause, back;

    public GamePanel(){
        //timer
        Timer timer = new Timer(5, this);

        setSize(GUI.getWidth(), GUI.getHeight());
        setBackground(Color.BLACK);
        setLayout(null);
        setVisible(false);

        /*

        pause = new JButton("Pause");
        pause.setHorizontalAlignment(SwingConstants.CENTER);
        pause.setBounds();
        pause.setBackground(Color.GREEN);
        pause.setForeground(Color.RED);
        pause.setOpaque(true);
        pause.setBorderPainted(false);
        pause.addActionListener(this);
        add(pause);

        back = new JButton("Back");
        back.setHorizontalAlignment(SwingConstants.CENTER);
        back.setBounds();
        back.setBackground(Color.GREEN);
        back.setForeground(Color.RED);
        back.setOpaque(true);
        back.setBorderPainted(false);
        back.addActionListener(this);
        add(back);

        */

        start();

        timer.start();

        setFocusable(true);
        addKeyListener(this);
        requestFocusInWindow();
        //setFocusTraversalKeysEnabled(false);
        //requestFocus();

    }//end constructor GamePanel()

    public void start() {
        player = new ZCraft(GUI.user);

    }//end start()

    public void update() {
        if(up) {
            player.moveYAxis(true);

        }else {
            player.moveYAxis(false);

        }

        if(right) {
            player.moveXAxis(true);

        }else {
            player.moveXAxis(false);

        }

    }//end update()

    public void render(Graphics g) {
        player.render(g);

    }//end render(Graphics g)

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        render(g);

    }//end paintComponent(Graphics g)

    @Override
    public void actionPerformed(ActionEvent e) {
        update();
        repaint();

    }//end actionPerformed(ActionEvent e)

    @Override
    public void keyTyped(KeyEvent e) {}//end keyTyped(KeyEvent e)

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();

        if(code == KeyEvent.VK_UP) {
            up = true;

        }

        if(code == KeyEvent.VK_RIGHT) {
            right = true;

        }

        if(code == KeyEvent.VK_DOWN) {
            down = true;

        }

        if(code == KeyEvent.VK_LEFT) {
            left = true;

        }

        if(code == KeyEvent.VK_SPACE) {
            //player.shoot();

        }

        if(code == KeyEvent.VK_1) {

        }

    }//end keyPressed(KeyEvent e)

    @Override
    public void keyReleased(KeyEvent e) {
        int code = e.getKeyCode();

        if(code == KeyEvent.VK_UP) {
            up = false;

        }

        if(code == KeyEvent.VK_RIGHT) {
            right = false;

        }

        if(code == KeyEvent.VK_DOWN) {
            down = false;

        }

        if(code == KeyEvent.VK_LEFT) {
            left = false;

        }

        if(code == KeyEvent.VK_SPACE) {
            //player.shoot();

        }

    }//end keyReleased(KeyEvent e)

}//end class GamePanel
</code>```

I just want to enter the method, I'll change the movement thing later

答:
You appear to be ignoring the layout manager used by JFrame. The JFrame's contentPane uses BorderLayout, and when adding multiple components to this, you cover previously added components, and so your GamePanel is not even showing much less having focus.

Best solutions:

Learn and use the layout managers well

Use Key Bindings, not KeyListeners.

When asking questions, please post a valid MCVE with your question, a small but complete program that only has necessary code to demonstrate your problem, that we can copy, paste, compile and run without modification, as this would help us to fully understand what you might be doing wrong.

My MCVE to test your code:

```<code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class GUI {
    public static String user;

    public static GUI gui;
    public static LoginPanel lp;
    public static MenuPanel mp;
    public static GamePanel gp;
    public static HighscorePanel hp;

    public static InstructionPanel ip;
    private static final int WIDTH = 500;
    private static final int HEIGHT = 500;

    public GUI() {

        JFrame frame = new JFrame("ZCraft");
        frame.setSize(WIDTH, HEIGHT);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        lp = new LoginPanel();
        frame.add(lp);

        mp = new MenuPanel();
        frame.add(mp);

        gp = new GamePanel();
        frame.add(gp);

        ip = new InstructionPanel();
        frame.add(ip);

        hp = new HighscorePanel();
        frame.add(hp);

        frame.setVisible(true);

    }

    public static int getWidth() {
        return WIDTH;

    }

    public static int getHeight() {
        return HEIGHT;

    }

    public static void main(String[] args) {
        gui = new GUI();

    }

}

class GamePanel extends JPanel implements ActionListener, KeyListener {

    public static GamePanel gp;

    private boolean up = false;
    private boolean right = false;
    private boolean down = false;
    private boolean left = false;

    private ZCraft player;

    private JButton pause, back;

    public GamePanel() {
        setBorder(BorderFactory.createTitledBorder("GamePanel")); // !!
        Timer timer = new Timer(5, this);

        setSize(GUI.getWidth(), GUI.getHeight());
        setBackground(Color.BLACK);
        setLayout(null);
        setVisible(false);

        start();

        timer.start();

        setFocusable(true);
        addKeyListener(this);
        requestFocusInWindow();

    }

    public void start() {
        player = new ZCraft(GUI.user);

    }

    public void update() {
        if (up) {
            player.moveYAxis(true);

        } else {
            player.moveYAxis(false);

        }

        if (right) {
            player.moveXAxis(true);

        } else {
            player.moveXAxis(false);

        }

    }

    public void render(Graphics g) {
        player.render(g);

    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        render(g);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        update();
        repaint();

    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("keypressed: " + e);
        int code = e.getKeyCode();

        if (code == KeyEvent.VK_UP) {
            up = true;

        }

        if (code == KeyEvent.VK_RIGHT) {
            right = true;

        }

        if (code == KeyEvent.VK_DOWN) {
            down = true;

        }

        if (code == KeyEvent.VK_LEFT) {
            left = true;

        }

        if (code == KeyEvent.VK_SPACE) {

        }

        if (code == KeyEvent.VK_1) {

        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        int code = e.getKeyCode();

        if (code == KeyEvent.VK_UP) {
            up = false;

        }

        if (code == KeyEvent.VK_RIGHT) {
            right = false;

        }

        if (code == KeyEvent.VK_DOWN) {
            down = false;

        }

        if (code == KeyEvent.VK_LEFT) {
            left = false;

        }

        if (code == KeyEvent.VK_SPACE) {

        }

    }

}

class LoginPanel extends MyJPanel {

}

class MenuPanel extends MyJPanel {

}

class HighscorePanel extends MyJPanel {

}

class InstructionPanel extends MyJPanel {

}

class MyJPanel extends JPanel {
    public MyJPanel() {
        setBorder(BorderFactory.createTitledBorder(getClass().getSimpleName()));
    }
}

class ZCraft {

    public ZCraft(String user) {
    }

    public void render(Graphics g) {

    }

    public void moveXAxis(boolean b) {

    }

    public void moveYAxis(boolean b) {

    }

}
</code>```

Note that only HighScore JPanel shows.

Other unrelated issues:

You are grossly over-using the static modifier, making it more difficult to test your code and enhance your code.

You are using null layouts, a very dangerous thing to do, one making it difficult to upgrade/update your program.

For example:

```<code>import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class GUI2 extends JPanel {
    private static final int PREF_W = 500;
    private static final int PREF_H = PREF_W;
    private LoginPanel lp = new LoginPanel();
    private MenuPanel mp = new MenuPanel();
    private MyGamePanel gp = new MyGamePanel();
    private HighscorePanel hp= new HighscorePanel();
    private InstructionPanel ip = new InstructionPanel();
    private JPanel[] panels = {lp, mp, gp, hp, ip};
    private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>();
    private JComboBox<String> panelsCombo = new JComboBox<>(comboModel);
    private CardLayout cardLayout = new CardLayout();
    private JPanel cardHolderPanel = new JPanel(cardLayout);

    public GUI2() {
        for (JPanel panel : panels) {
            String key = panel.getClass().getSimpleName();
            cardHolderPanel.add(panel, key);
            comboModel.addElement(key);
        }

        JPanel bottomPanel = new JPanel();
        bottomPanel.add(panelsCombo);

        panelsCombo.setFocusable(false);
        panelsCombo.addActionListener(e -> {
            String selection = (String) panelsCombo.getSelectedItem();
            cardLayout.show(cardHolderPanel, selection);
        });

        setLayout(new BorderLayout());
        add(cardHolderPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        GUI2 mainPanel = new GUI2();

        JFrame frame = new JFrame("GUI2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
</code>```

```<code>@SuppressWarnings("serial")
class MyGamePanel extends MyJPanel {
    public MyGamePanel() {
        setKeyBindings();
    }

    private void setKeyBindings() {
        int condition = WHEN_IN_FOCUSED_WINDOW;
        InputMap inputMap = getInputMap(condition);
        ActionMap actionMap = getActionMap();

        KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        String enterStrokeKey = enterStroke.toString();

        inputMap.put(enterStroke, enterStrokeKey);
        actionMap.put(enterStrokeKey, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Enter pressed");
            }
        });
        intoMap(inputMap, actionMap, Direction.UP, KeyEvent.VK_UP);
        intoMap(inputMap, actionMap, Direction.DOWN, KeyEvent.VK_DOWN);
        intoMap(inputMap, actionMap, Direction.LEFT, KeyEvent.VK_LEFT);
        intoMap(inputMap, actionMap, Direction.RIGHT, KeyEvent.VK_RIGHT);
    }

    private void intoMap(InputMap inputMap, ActionMap actionMap, Direction dir, int keyCode) {
        KeyStroke release = KeyStroke.getKeyStroke(keyCode, 0, true);
        KeyStroke pressed = KeyStroke.getKeyStroke(keyCode, 0, false);
        inputMap.put(pressed, pressed.toString());
        inputMap.put(release, release.toString());
        actionMap.put(pressed.toString(), new DirectionAction(dir, false));
        actionMap.put(release.toString(), new DirectionAction(dir, true));
    }

    private class DirectionAction extends AbstractAction {
        private Direction dir;
        private boolean onRelease;

        public DirectionAction(Direction dir, boolean onRelease) {
            this.dir = dir;
            this.onRelease = onRelease;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.printf("Direction: %s; On Released: %b%n", dir.toString(), onRelease);
        }
    }
}
</code>```

```<code>enum Direction {
    UP, DOWN, LEFT, RIGHT
}
</code>```

```<code>class LoginPanel extends MyJPanel {

}

class MenuPanel extends MyJPanel {

}

class HighscorePanel extends MyJPanel {

}

class InstructionPanel extends MyJPanel {

}

@SuppressWarnings("serial")
class MyJPanel extends JPanel {
    public MyJPanel() {
        setBorder(BorderFactory.createTitledBorder(getClass().getSimpleName()));
    }
}

class ZCraft {

    public ZCraft(String user) {
    }

    public void render(Graphics g) {

    }

    public void moveXAxis(boolean b) {

    }

    public void moveYAxis(boolean b) {

    }

}
</code>```

Title: KeyListener is irresponsive

Body:
I want to make a plane move across the board.
This should be pretty simple since I"ve done it before
I've setFocusable(true), I've added KeyListener, and I've also requestFocusInWindow()

I don't know what's wrong

When a key is pressed, it won't even enter the KeyPressed method

I tested by trying to print out "hi".

    package game;

    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    import javax.swing.JFrame;

    public class GUI{

        /* Author: Carl Zhang
         * Date:
         *
         */

        //player's username
        public static String user;

        //classes
        public static GUI gui;
        public static LoginPanel lp;
        public static MenuPanel mp;
        public static GamePanel gp;
        public static HighscorePanel hp;

        public static InstructionPanel ip;

        //dimensions
        private static final int WIDTH = 500;
        private static final int HEIGHT = 500;

        public GUI() {

        JFrame frame = new JFrame("ZCraft");
            frame.setSize(WIDTH, HEIGHT);
            frame.setResizable(false);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);

        //adding JPanels
        lp = new LoginPanel();
        frame.add(lp);

        mp = new MenuPanel();
        frame.add(mp);

        gp = new GamePanel();
        frame.add(gp);

        ip = new InstructionPanel();
        frame.add(ip);

        hp = new HighscorePanel();
        frame.add(hp);

        frame.setVisible(true);

    }//end constructor GUI()

    public static int getWidth() {
        return WIDTH;

    }//end getWIDTH()

    public static int getHeight() {
        return HEIGHT;

    }//end getHEIGHT

    public static void main(String[] args) {
        gui = new GUI();

    }//end main

}//end class GUI

        package game;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Timer;

public class GamePanel extends JPanel implements ActionListener, KeyListener {

    public static GamePanel gp;

    private boolean up = false;
    private boolean right = false;
    private boolean down = false;
    private boolean left = false;

    private ZCraft player;

    private JButton pause, back;

    public GamePanel(){
        //timer
        Timer timer = new Timer(5, this);

        setSize(GUI.getWidth(), GUI.getHeight());
        setBackground(Color.BLACK);
        setLayout(null);
        setVisible(false);

        /*

        pause = new JButton("Pause");
        pause.setHorizontalAlignment(SwingConstants.CENTER);
        pause.setBounds();
        pause.setBackground(Color.GREEN);
        pause.setForeground(Color.RED);
        pause.setOpaque(true);
        pause.setBorderPainted(false);
        pause.addActionListener(this);
        add(pause);

        back = new JButton("Back");
        back.setHorizontalAlignment(SwingConstants.CENTER);
        back.setBounds();
        back.setBackground(Color.GREEN);
        back.setForeground(Color.RED);
        back.setOpaque(true);
        back.setBorderPainted(false);
        back.addActionListener(this);
        add(back);

        */

        start();

        timer.start();

        setFocusable(true);
        addKeyListener(this);
        requestFocusInWindow();
        //setFocusTraversalKeysEnabled(false);
        //requestFocus();

    }//end constructor GamePanel()

    public void start() {
        player = new ZCraft(GUI.user);

    }//end start()

    public void update() {
        if(up) {
            player.moveYAxis(true);

        }else {
            player.moveYAxis(false);

        }

        if(right) {
            player.moveXAxis(true);

        }else {
            player.moveXAxis(false);

        }

    }//end update()

    public void render(Graphics g) {
        player.render(g);

    }//end render(Graphics g)

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        render(g);

    }//end paintComponent(Graphics g)

    @Override
    public void actionPerformed(ActionEvent e) {
        update();
        repaint();

    }//end actionPerformed(ActionEvent e)

    @Override
    public void keyTyped(KeyEvent e) {}//end keyTyped(KeyEvent e)

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();

        if(code == KeyEvent.VK_UP) {
            up = true;

        }

        if(code == KeyEvent.VK_RIGHT) {
            right = true;

        }

        if(code == KeyEvent.VK_DOWN) {
            down = true;

        }

        if(code == KeyEvent.VK_LEFT) {
            left = true;

        }

        if(code == KeyEvent.VK_SPACE) {
            //player.shoot();

        }

        if(code == KeyEvent.VK_1) {

        }

    }//end keyPressed(KeyEvent e)

    @Override
    public void keyReleased(KeyEvent e) {
        int code = e.getKeyCode();

        if(code == KeyEvent.VK_UP) {
            up = false;

        }

        if(code == KeyEvent.VK_RIGHT) {
            right = false;

        }

        if(code == KeyEvent.VK_DOWN) {
            down = false;

        }

        if(code == KeyEvent.VK_LEFT) {
            left = false;

        }

        if(code == KeyEvent.VK_SPACE) {
            //player.shoot();

        }

    }//end keyReleased(KeyEvent e)

}//end class GamePanel

I just want to enter the method, I'll change the movement thing later

Body:
You appear to be ignoring the layout manager used by JFrame. The JFrame's contentPane uses BorderLayout, and when adding multiple components to this, you cover previously added components, and so your GamePanel is not even showing much less having focus.

Best solutions:

Learn and use the layout managers well

Use Key Bindings, not KeyListeners.

When asking questions, please post a valid MCVE with your question, a small but complete program that only has necessary code to demonstrate your problem, that we can copy, paste, compile and run without modification, as this would help us to fully understand what you might be doing wrong.

My MCVE to test your code:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class GUI {
    public static String user;

    public static GUI gui;
    public static LoginPanel lp;
    public static MenuPanel mp;
    public static GamePanel gp;
    public static HighscorePanel hp;

    public static InstructionPanel ip;
    private static final int WIDTH = 500;
    private static final int HEIGHT = 500;

    public GUI() {

        JFrame frame = new JFrame("ZCraft");
        frame.setSize(WIDTH, HEIGHT);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        lp = new LoginPanel();
        frame.add(lp);

        mp = new MenuPanel();
        frame.add(mp);

        gp = new GamePanel();
        frame.add(gp);

        ip = new InstructionPanel();
        frame.add(ip);

        hp = new HighscorePanel();
        frame.add(hp);

        frame.setVisible(true);

    }

    public static int getWidth() {
        return WIDTH;

    }

    public static int getHeight() {
        return HEIGHT;

    }

    public static void main(String[] args) {
        gui = new GUI();

    }

}

class GamePanel extends JPanel implements ActionListener, KeyListener {

    public static GamePanel gp;

    private boolean up = false;
    private boolean right = false;
    private boolean down = false;
    private boolean left = false;

    private ZCraft player;

    private JButton pause, back;

    public GamePanel() {
        setBorder(BorderFactory.createTitledBorder("GamePanel")); // !!
        Timer timer = new Timer(5, this);

        setSize(GUI.getWidth(), GUI.getHeight());
        setBackground(Color.BLACK);
        setLayout(null);
        setVisible(false);

        start();

        timer.start();

        setFocusable(true);
        addKeyListener(this);
        requestFocusInWindow();

    }

    public void start() {
        player = new ZCraft(GUI.user);

    }

    public void update() {
        if (up) {
            player.moveYAxis(true);

        } else {
            player.moveYAxis(false);

        }

        if (right) {
            player.moveXAxis(true);

        } else {
            player.moveXAxis(false);

        }

    }

    public void render(Graphics g) {
        player.render(g);

    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        render(g);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        update();
        repaint();

    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("keypressed: " + e);
        int code = e.getKeyCode();

        if (code == KeyEvent.VK_UP) {
            up = true;

        }

        if (code == KeyEvent.VK_RIGHT) {
            right = true;

        }

        if (code == KeyEvent.VK_DOWN) {
            down = true;

        }

        if (code == KeyEvent.VK_LEFT) {
            left = true;

        }

        if (code == KeyEvent.VK_SPACE) {

        }

        if (code == KeyEvent.VK_1) {

        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        int code = e.getKeyCode();

        if (code == KeyEvent.VK_UP) {
            up = false;

        }

        if (code == KeyEvent.VK_RIGHT) {
            right = false;

        }

        if (code == KeyEvent.VK_DOWN) {
            down = false;

        }

        if (code == KeyEvent.VK_LEFT) {
            left = false;

        }

        if (code == KeyEvent.VK_SPACE) {

        }

    }

}

class LoginPanel extends MyJPanel {

}

class MenuPanel extends MyJPanel {

}

class HighscorePanel extends MyJPanel {

}

class InstructionPanel extends MyJPanel {

}

class MyJPanel extends JPanel {
    public MyJPanel() {
        setBorder(BorderFactory.createTitledBorder(getClass().getSimpleName()));
    }
}

class ZCraft {

    public ZCraft(String user) {
    }

    public void render(Graphics g) {

    }

    public void moveXAxis(boolean b) {

    }

    public void moveYAxis(boolean b) {

    }

}

Note that only HighScore JPanel shows.

Other unrelated issues:

You are grossly over-using the static modifier, making it more difficult to test your code and enhance your code.

You are using null layouts, a very dangerous thing to do, one making it difficult to upgrade/update your program.

For example:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class GUI2 extends JPanel {
    private static final int PREF_W = 500;
    private static final int PREF_H = PREF_W;
    private LoginPanel lp = new LoginPanel();
    private MenuPanel mp = new MenuPanel();
    private MyGamePanel gp = new MyGamePanel();
    private HighscorePanel hp= new HighscorePanel();
    private InstructionPanel ip = new InstructionPanel();
    private JPanel[] panels = {lp, mp, gp, hp, ip};
    private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>();
    private JComboBox<String> panelsCombo = new JComboBox<>(comboModel);
    private CardLayout cardLayout = new CardLayout();
    private JPanel cardHolderPanel = new JPanel(cardLayout);

    public GUI2() {
        for (JPanel panel : panels) {
            String key = panel.getClass().getSimpleName();
            cardHolderPanel.add(panel, key);
            comboModel.addElement(key);
        }

        JPanel bottomPanel = new JPanel();
        bottomPanel.add(panelsCombo);

        panelsCombo.setFocusable(false);
        panelsCombo.addActionListener(e -> {
            String selection = (String) panelsCombo.getSelectedItem();
            cardLayout.show(cardHolderPanel, selection);
        });

        setLayout(new BorderLayout());
        add(cardHolderPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        GUI2 mainPanel = new GUI2();

        JFrame frame = new JFrame("GUI2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

@SuppressWarnings("serial")
class MyGamePanel extends MyJPanel {
    public MyGamePanel() {
        setKeyBindings();
    }

    private void setKeyBindings() {
        int condition = WHEN_IN_FOCUSED_WINDOW;
        InputMap inputMap = getInputMap(condition);
        ActionMap actionMap = getActionMap();

        KeyStroke enterStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        String enterStrokeKey = enterStroke.toString();

        inputMap.put(enterStroke, enterStrokeKey);
        actionMap.put(enterStrokeKey, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Enter pressed");
            }
        });
        intoMap(inputMap, actionMap, Direction.UP, KeyEvent.VK_UP);
        intoMap(inputMap, actionMap, Direction.DOWN, KeyEvent.VK_DOWN);
        intoMap(inputMap, actionMap, Direction.LEFT, KeyEvent.VK_LEFT);
        intoMap(inputMap, actionMap, Direction.RIGHT, KeyEvent.VK_RIGHT);
    }

    private void intoMap(InputMap inputMap, ActionMap actionMap, Direction dir, int keyCode) {
        KeyStroke release = KeyStroke.getKeyStroke(keyCode, 0, true);
        KeyStroke pressed = KeyStroke.getKeyStroke(keyCode, 0, false);
        inputMap.put(pressed, pressed.toString());
        inputMap.put(release, release.toString());
        actionMap.put(pressed.toString(), new DirectionAction(dir, false));
        actionMap.put(release.toString(), new DirectionAction(dir, true));
    }

    private class DirectionAction extends AbstractAction {
        private Direction dir;
        private boolean onRelease;

        public DirectionAction(Direction dir, boolean onRelease) {
            this.dir = dir;
            this.onRelease = onRelease;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.printf("Direction: %s; On Released: %b%n", dir.toString(), onRelease);
        }
    }
}

enum Direction {
    UP, DOWN, LEFT, RIGHT
}

class LoginPanel extends MyJPanel {

}

class MenuPanel extends MyJPanel {

}

class HighscorePanel extends MyJPanel {

}

class InstructionPanel extends MyJPanel {

}

@SuppressWarnings("serial")
class MyJPanel extends JPanel {
    public MyJPanel() {
        setBorder(BorderFactory.createTitledBorder(getClass().getSimpleName()));
    }
}

class ZCraft {

    public ZCraft(String user) {
    }

    public void render(Graphics g) {

    }

    public void moveXAxis(boolean b) {

    }

    public void moveYAxis(boolean b) {

    }

}


来源: stackexchange

问:
Regression loop: several dep variables & several indep variables, one of these indep variables takes different values according to the dep variable
I have several dependent variables (let's call them dep1, dep2 and dep3) and I want to regress several independent variables on them. I have the independent variables a,b and c which I always want to include in the regression. However the independent variables d1, d2, d3 should only be used when the number matches the number of the dependent variable. This is:

```<code>lm(dep1 ~ a + b + c + d1)
lm(dep2 ~ a + b + c + d2)
lm(dep3 ~ a + b + c + d3)
</code>```

To be more exact, both my dependent and independent variables are a monthly time series (xts object). I merged the dependent variables to get the matrix "dep". a,b,c,d1,d2 and d3 are stored in the matrix "indep".

Is it possible to create a loop which does this automatically?

答:
We can use paste

```<code>v1 <- paste0("dep", 1:3)
v2 <- paste0("d", 1:3)
v3 <- paste(v1, paste(paste(letters[1:3], collapse=" + "), v2, sep=" + "), sep="~")
lapply(v3, function(x) lm(x))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have several dependent variables (let's call them dep1, dep2 and dep3) and I want to regress several independent variables on them. I have the independent variables a,b and c which I always want to include in the regression. However the independent variables d1, d2, d3 should only be used when the number matches the number of the dependent variable. This is:

lm(dep1 ~ a + b + c + d1)
lm(dep2 ~ a + b + c + d2)
lm(dep3 ~ a + b + c + d3)

To be more exact, both my dependent and independent variables are a monthly time series (xts object). I merged the dependent variables to get the matrix "dep". a,b,c,d1,d2 and d3 are stored in the matrix "indep".

Is it possible to create a loop which does this automatically?

Body:
We can use paste

v1 <- paste0("dep", 1:3)
v2 <- paste0("d", 1:3)
v3 <- paste(v1, paste(paste(letters[1:3], collapse=" + "), v2, sep=" + "), sep="~")
lapply(v3, function(x) lm(x))


问:
Floating point comparison functions for C#
Can someone point towards (or show) some good general floating point comparison functions in C# for comparing floating point values? I want to implement functions for IsEqual, IsGreater an IsLess. I also only really care about doubles not floats.

答:
Continuing from the answers provided by Michael and testing, an important thing to keep in mind when translating the original Java code to C# is that Java and C# define their constants differently. C#, for instance, lacks Java's MIN_NORMAL, and the definitions for MinValue differ greatly.

Java defines MIN_VALUE to be the smallest possible positive value, while C# defines it as the smallest possible representable value overall. The equivalent value in C# is Epsilon.

The lack of MIN_NORMAL is problematic for direct translation of the original algorithm - without it, things start to break down for small values near zero. Java's MIN_NORMAL follows the IEEE specification of the smallest possible number without having the leading bit of the significand as zero, and with that in mind, we can define our own normals for both singles and doubles (which dbc mentioned in the comments to the original answer).

The following C# code for singles passes all of the tests given on The Floating Point Guide, and the double edition passes all of the tests with minor modifications in the test cases to account for the increased precision.

```<code>public static bool ApproximatelyEqualEpsilon(float a, float b, float epsilon)
{
    const float floatNormal = (1 << 23) * float.Epsilon;
    float absA = Math.Abs(a);
    float absB = Math.Abs(b);
    float diff = Math.Abs(a - b);

    if (a == b)
    {
        // Shortcut, handles infinities
        return true;
    }

    if (a == 0.0f || b == 0.0f || diff < floatNormal)
    {
        // a or b is zero, or both are extremely close to it.
        // relative error is less meaningful here
        return diff < (epsilon * floatNormal);
    }

    // use relative error
    return diff / Math.Min((absA + absB), float.MaxValue) < epsilon;
}
</code>```

The version for doubles is identical save for type changes and that the normal is defined like this instead.

```<code>const double doubleNormal = (1L << 52) * double.Epsilon;
</code>```

Body:
Continuing from the answers provided by Michael and testing, an important thing to keep in mind when translating the original Java code to C# is that Java and C# define their constants differently. C#, for instance, lacks Java's MIN_NORMAL, and the definitions for MinValue differ greatly.

Java defines MIN_VALUE to be the smallest possible positive value, while C# defines it as the smallest possible representable value overall. The equivalent value in C# is Epsilon.

The lack of MIN_NORMAL is problematic for direct translation of the original algorithm - without it, things start to break down for small values near zero. Java's MIN_NORMAL follows the IEEE specification of the smallest possible number without having the leading bit of the significand as zero, and with that in mind, we can define our own normals for both singles and doubles (which dbc mentioned in the comments to the original answer).

The following C# code for singles passes all of the tests given on The Floating Point Guide, and the double edition passes all of the tests with minor modifications in the test cases to account for the increased precision.

public static bool ApproximatelyEqualEpsilon(float a, float b, float epsilon)
{
    const float floatNormal = (1 << 23) * float.Epsilon;
    float absA = Math.Abs(a);
    float absB = Math.Abs(b);
    float diff = Math.Abs(a - b);

    if (a == b)
    {
        // Shortcut, handles infinities
        return true;
    }

    if (a == 0.0f || b == 0.0f || diff < floatNormal)
    {
        // a or b is zero, or both are extremely close to it.
        // relative error is less meaningful here
        return diff < (epsilon * floatNormal);
    }

    // use relative error
    return diff / Math.Min((absA + absB), float.MaxValue) < epsilon;
}

The version for doubles is identical save for type changes and that the normal is defined like this instead.

const double doubleNormal = (1L << 52) * double.Epsilon;


问:
Tensorflow tf.cond evaluating both pedicate
```<code>import tensorflow as tf
import numpy as np

isTrain = tf.placeholder(tf.bool)
user_input = tf.placeholder(tf.float32)

# ema = tf.train.ExponentialMovingAverage(decay=.5)

with tf.device('/cpu:0'):
    beta = tf.Variable(tf.ones([1]))

    batch_mean = beta.assign(user_input)
    ema = tf.train.ExponentialMovingAverage(decay=0.5)
    ema_apply_op = ema.apply([batch_mean])
    ema_mean = ema.average(batch_mean)

    def mean_var_with_update():
        with tf.control_dependencies([ema_apply_op]):
            return tf.identity(batch_mean)

    mean = tf.cond(isTrain,
        mean_var_with_update,
        lambda: (ema_mean))

# ======= End Here ==========
saver = tf.train.Saver()
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

u_input = [[2], [3], [4] ]
for u in u_input:
    aa = sess.run([mean], feed_dict={user_input:u, isTrain: True })
    print("Train", aa)

for u in u_input:
    aa = sess.run([ema_mean], feed_dict={user_input:u, isTrain: False })
    print("Test correct", aa)

for u in u_input:
    aa = sess.run([mean], feed_dict={user_input:u, isTrain: False })
    print("Test", aa)
</code>```

This code snippet should calculate the mean of user_input across training stage and output mean during testing stage.

This is the output result :

```<code>('Train', [array([ 2.], dtype=float32)])
('Train', [array([ 3.], dtype=float32)])
('Train', [array([ 4.], dtype=float32)])
('Test correct', [array([ 3.], dtype=float32)])
('Test correct', [array([ 3.], dtype=float32)])
('Test correct', [array([ 3.], dtype=float32)])
('Test', [array([ 2.5], dtype=float32)])
('Test', [array([ 2.75], dtype=float32)])
('Test', [array([ 3.375], dtype=float32)])
</code>```

However, ema_mean always get evaluated when calling sess.run([mean]) even if isTrain = False.

Is there any mistake in the code ?  tensorflow version is 0.7.1

答:
I think that is the same as answered here. The tf.control_dependencies inside the conditionals will add the dependencies to the tf.cond itself.

So try to create the ema_apply_op inside the mean_var_with_update function.

Body:
import tensorflow as tf
import numpy as np

isTrain = tf.placeholder(tf.bool)
user_input = tf.placeholder(tf.float32)

# ema = tf.train.ExponentialMovingAverage(decay=.5)

with tf.device('/cpu:0'):
    beta = tf.Variable(tf.ones([1]))

    batch_mean = beta.assign(user_input)
    ema = tf.train.ExponentialMovingAverage(decay=0.5)
    ema_apply_op = ema.apply([batch_mean])
    ema_mean = ema.average(batch_mean)

    def mean_var_with_update():
        with tf.control_dependencies([ema_apply_op]):
            return tf.identity(batch_mean)

    mean = tf.cond(isTrain,
        mean_var_with_update,
        lambda: (ema_mean))

# ======= End Here ==========
saver = tf.train.Saver()
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

u_input = [[2], [3], [4] ]
for u in u_input:
    aa = sess.run([mean], feed_dict={user_input:u, isTrain: True })
    print("Train", aa)

for u in u_input:
    aa = sess.run([ema_mean], feed_dict={user_input:u, isTrain: False })
    print("Test correct", aa)

for u in u_input:
    aa = sess.run([mean], feed_dict={user_input:u, isTrain: False })
    print("Test", aa)

This code snippet should calculate the mean of user_input across training stage and output mean during testing stage.

This is the output result :

('Train', [array([ 2.], dtype=float32)])
('Train', [array([ 3.], dtype=float32)])
('Train', [array([ 4.], dtype=float32)])
('Test correct', [array([ 3.], dtype=float32)])
('Test correct', [array([ 3.], dtype=float32)])
('Test correct', [array([ 3.], dtype=float32)])
('Test', [array([ 2.5], dtype=float32)])
('Test', [array([ 2.75], dtype=float32)])
('Test', [array([ 3.375], dtype=float32)])

However, ema_mean always get evaluated when calling sess.run([mean]) even if isTrain = False.

Is there any mistake in the code ?  tensorflow version is 0.7.1


答:
We can use </p>

```<code>x[na.omit(x) > 0]
</code>```

Title: Select x>0 in x when NA in x

Body:
> x
 [1] -0.0006993769            NA  0.0605337483  0.0112900315  0.0166747653  0.0498045070 -0.0120633548  0.0034724936
 [9] -0.0107294362 -0.0021350540 -0.0092103916 -0.0369649485 -0.0136530145 -0.0127135534  0.0159644319 -0.0075359604
[17]  0.0138871055  0.0226605719 -0.0118107427  0.0168362283 -0.0175228517

> x>0
 [1] FALSE    NA  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE  TRUE  TRUE FALSE  TRUE
[21] FALSE

> x[x>0]
 [1]          NA 0.060533748 0.011290032 0.016674765 0.049804507 0.003472494 0.015964432 0.013887105 0.022660572 0.016836228

do not want to get NA in x[x>0], why NA were selected in this sequence

Body:
We can use

x[na.omit(x) > 0]


问:
read json array in jade / pug (writing the iteration loop in jade)
Can someone help me write my jade file to properly read my variables from json?

My Json file looks like:

```<code>[
 { "name":"Little Engine","desc":"I am the first post"},
 {"name":"Mighty mouse","desc":"I am the second post"}
]
</code>```

I'm able to properly read the file and add it to jade using gulp. (which places the array into a "data" object.

This is where I get stuck. p=data

returns
[object Object],[object Object]
 so I know the data is getting passed through.

I can access one of the object by doing p=data[1].name

But I just can't figure out how to loop to get each object. Since I don't know how to put the # in data[#].

答:
Ok... never mind, this was easier that I thought.

```<code>- each dot in data
  p  #{dot.name} ... #{dot.desc}
</code>```

Thanks anyway.

Body:
Can someone help me write my jade file to properly read my variables from json?

My Json file looks like:

[
 { "name":"Little Engine","desc":"I am the first post"},
 {"name":"Mighty mouse","desc":"I am the second post"}
]

I'm able to properly read the file and add it to jade using gulp. (which places the array into a "data" object.

This is where I get stuck. p=data

returns
[object Object],[object Object]
 so I know the data is getting passed through.

I can access one of the object by doing p=data[1].name

But I just can't figure out how to loop to get each object. Since I don't know how to put the # in data[#].

Body:
Ok... never mind, this was easier that I thought.

- each dot in data
  p  #{dot.name} ... #{dot.desc}

Thanks anyway.


问:
How to send my notes to Output window in Visual Studio?
Have a look at the picture. No matter where i put console.writeline, nothing is showing in output. Where could be a mistake? Is something wrong with my output editor or what?

答:
So you have 2 questions instead of one: your main one and the comment "How can i display console window instead of Output window?"

You can write to VS output by using Debug.WriteLine. This requires System.Diagnostics namespace.

You can also run console window alongside with your windows application. Right click the project in Solution Explorer, select Properties, change Output Type to "Console Application" like this.

ContentLicense: CC BY-SA 4.0


问:
PHP/HTML - Trying to make image appear using localhost
I am using XAMPP for APACHE server on localhost:8080 (I had to change the default port for it to work). Assume that I have the rest of the html needed to run.
Here is the current code:

home.html

```<code><body>
<script src="main/profile.php"></script>
</body>
</code>```

profile.php

```<code><?php
$imagepath ="omj/logo.jpg";
$image = imagecreatefromjpeg( $imagepath);
header('Content-Type: image/jpeg');
imagejpeg($image);
?>
</code>```

I tried referencing the following articles to no avail:

http://www.configure-all.com/howto_display_image.php

How to display images from a folder using php - PHP

Edit
I got the image to work using HTML by simply moving the image folder inside the html folder. Now the question remains, why isn't the php code running to show the image?

The image path is within the directory of the html file. Like this: /htmlfolder/imagefolder/image.jpg while html file is /htmlfolder/file.html

答:
As I said use with a variable like below </p>

```<code><?php
$image_url='images/your.png';
?>

<img src="<?php echo $image_url;?>">
</code>```

Body:
I am using XAMPP for APACHE server on localhost:8080 (I had to change the default port for it to work). Assume that I have the rest of the html needed to run.
Here is the current code:

home.html

profile.php

<?php
$imagepath ="omj/logo.jpg";
$image = imagecreatefromjpeg( $imagepath);
header('Content-Type: image/jpeg');
imagejpeg($image);
?>

I tried referencing the following articles to no avail:

http://www.configure-all.com/howto_display_image.php

How to display images from a folder using php - PHP

Edit
I got the image to work using HTML by simply moving the image folder inside the html folder. Now the question remains, why isn't the php code running to show the image?

The image path is within the directory of the html file. Like this: /htmlfolder/imagefolder/image.jpg while html file is /htmlfolder/file.html

Body:
As I said use with a variable like below

<?php
$image_url='images/your.png';
?>

<img src="<?php echo $image_url;?>">


问:
Hand made queries vs findDependentRowset
I have built a pretty big application with Zend and i was wondering which would be better, building query by hand (using the Zend object model)

```<code>$db->select()
   ->form('table')
   ->join('table2',
          'table.id = table2.table_id')
</code>```

or going with the findDependentRowset method (Zend doc for findDependentRowSet).

I was wondering since i did a test to fetch data over multiple tables and display all the informations from a table and the findDependentRowset seemed to run slower. I might be wrong but i guess it makes a new query every time findDependentRowset is called as in :

```<code>$table1 = new Model_Table1;
$rowset = $table1-fetchAll();
foreach($rowset as $row){
    $table2data = $row->findDependentRowset('Model_Table2', 'Map');

    echo $row['field'] . ' ' . $table2data['field'];
}
</code>```

So, which one is better and is there a way using findDependentRowset to build complexes queries that could span over 5 tables which would run as fast as a hand made query?

Thanks

答:
Generally, build your own query is the best way to go, because zend will create just one object (or set of objects) and do just one query.

If you use findDependentRowset Zend will perform another query and build another object (or set) with the result for each call.

You should use this only in very specific cases.

See this question: PHP - Query single value per iteration or fetch all at start and retrieve from array?

ContentLicense: CC BY-SA 2.5

Body:
I have built a pretty big application with Zend and i was wondering which would be better, building query by hand (using the Zend object model)

$db->select()
   ->form('table')
   ->join('table2',
          'table.id = table2.table_id')

or going with the findDependentRowset method (Zend doc for findDependentRowSet).

I was wondering since i did a test to fetch data over multiple tables and display all the informations from a table and the findDependentRowset seemed to run slower. I might be wrong but i guess it makes a new query every time findDependentRowset is called as in :

$table1 = new Model_Table1;
$rowset = $table1-fetchAll();
foreach($rowset as $row){
    $table2data = $row->findDependentRowset('Model_Table2', 'Map');

    echo $row['field'] . ' ' . $table2data['field'];
}

So, which one is better and is there a way using findDependentRowset to build complexes queries that could span over 5 tables which would run as fast as a hand made query?

Thanks


问:
How to maximize a window on a specific monitor with Excel VBA?
I want to maximize a window on a specific screen using Excel VBA.

I used this code:

```<code>With ActiveWindow
    .WindowState = xlNormal
    .Left = 1200
    .WindowState = xlMaximized
End With
</code>```

The code works if monitor 2 is right-hand to monitor 1. If it's the other way around, the approach fails (then I have to use -1200).

This macro should work on different PCs, where I don't know how the systems are configured. Is there any possibility to detect how many monitors are attached and to directly address the respective monitor on which I want to maximize the window?

答:
As mentioned in the comments you need to use Windows APIs; this is another (relatively simple to use) API that helped me determine if a user form was moved off the visible area of the screen(s): GetSystemMetrics Lib "User32"

to declare the function based on the version of Office:

```<code>#If Win64 Then  'Win64=true, Win32=true, Win16= false
    Private Declare PtrSafe Function apiGetSystemMetrics Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
    Private Declare PtrSafe Function apiGetSystemMetrics32 Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
#ElseIf Win32 Then  'Win32=true, Win16=false
    Private Declare Function apiGetSystemMetrics Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
#Else   ' Win16=true
#End If
</code>```

generic functions:

```<code>Public Function dllGetMonitors() As Long
    Const SM_CMONITORS = 80
    dllGetMonitors = apiGetSystemMetrics(SM_CMONITORS)
End Function

'The width of the virtual screen, in pixels.
'The virtual screen is the bounding rectangle of all display monitors

Public Function dllGetHorizontalResolution() As Long
    Const SM_CXVIRTUALSCREEN = 78
    dllGetHorizontalResolution = apiGetSystemMetrics(SM_CXVIRTUALSCREEN)
End Function

Public Function dllGetVerticalResolution() As Long
    Const SM_CYVIRTUALSCREEN = 79
    dllGetVerticalResolution = apiGetSystemMetrics(SM_CYVIRTUALSCREEN)
End Function
</code>```

.

more info: http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx

The function I used to determine if the form is off screen:

```<code>Private Sub checkOffScreen(ByRef frm)
    Dim maxTop As Long, minLeft As Long, maxLeft As Long
    Dim defaultOffset As Byte, monitors As Byte

    monitors = celTotalMonitors.Value
    defaultOffset = 11
    minLeft = 0 - (frm.Width - defaultOffset)
    If monitors = 1 And celScreenResolutionX.Value > 1280 Then
        maxTop = 1180 - defaultOffset
        maxLeft = 1900 - defaultOffset
    Else
        maxTop = 750 - defaultOffset
        maxLeft = (960 * monitors) - defaultOffset
    End If
    With frm
        'If (celFormTop.Value < 0 Or celFormTop.Value > maxTop) Or _
            (celFormLeft.Value < minLeft Or celFormLeft.Value > maxLeft) Then
        'If .top < 0 Or .top > maxTop Or .Left < minLeft Or .Left > maxLeft Then
        If celFormTop.Value > maxTop Or celFormLeft.Value > maxLeft Then
            celFormTop = defaultOffset
            celFormLeft = defaultOffset
        End If
        If .Top > maxTop Or .left > maxLeft Then
            .Top = defaultOffset
            .left = defaultOffset
        End If
    End With
End Sub
</code>```

Body:
I want to maximize a window on a specific screen using Excel VBA.

I used this code:

With ActiveWindow
    .WindowState = xlNormal
    .Left = 1200
    .WindowState = xlMaximized
End With

The code works if monitor 2 is right-hand to monitor 1. If it's the other way around, the approach fails (then I have to use -1200).

This macro should work on different PCs, where I don't know how the systems are configured. Is there any possibility to detect how many monitors are attached and to directly address the respective monitor on which I want to maximize the window?

Body:
As mentioned in the comments you need to use Windows APIs; this is another (relatively simple to use) API that helped me determine if a user form was moved off the visible area of the screen(s): GetSystemMetrics Lib "User32"

to declare the function based on the version of Office:

#If Win64 Then  'Win64=true, Win32=true, Win16= false
    Private Declare PtrSafe Function apiGetSystemMetrics Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
    Private Declare PtrSafe Function apiGetSystemMetrics32 Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
#ElseIf Win32 Then  'Win32=true, Win16=false
    Private Declare Function apiGetSystemMetrics Lib "User32" Alias "GetSystemMetrics" (ByVal nIndex As Long) As Long
#Else   ' Win16=true
#End If

generic functions:

Public Function dllGetMonitors() As Long
    Const SM_CMONITORS = 80
    dllGetMonitors = apiGetSystemMetrics(SM_CMONITORS)
End Function

'The width of the virtual screen, in pixels.
'The virtual screen is the bounding rectangle of all display monitors

Public Function dllGetHorizontalResolution() As Long
    Const SM_CXVIRTUALSCREEN = 78
    dllGetHorizontalResolution = apiGetSystemMetrics(SM_CXVIRTUALSCREEN)
End Function

Public Function dllGetVerticalResolution() As Long
    Const SM_CYVIRTUALSCREEN = 79
    dllGetVerticalResolution = apiGetSystemMetrics(SM_CYVIRTUALSCREEN)
End Function

.

more info: http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx

The function I used to determine if the form is off screen:

Private Sub checkOffScreen(ByRef frm)
    Dim maxTop As Long, minLeft As Long, maxLeft As Long
    Dim defaultOffset As Byte, monitors As Byte

    monitors = celTotalMonitors.Value
    defaultOffset = 11
    minLeft = 0 - (frm.Width - defaultOffset)
    If monitors = 1 And celScreenResolutionX.Value > 1280 Then
        maxTop = 1180 - defaultOffset
        maxLeft = 1900 - defaultOffset
    Else
        maxTop = 750 - defaultOffset
        maxLeft = (960 * monitors) - defaultOffset
    End If
    With frm
        'If (celFormTop.Value < 0 Or celFormTop.Value > maxTop) Or _
            (celFormLeft.Value < minLeft Or celFormLeft.Value > maxLeft) Then
        'If .top < 0 Or .top > maxTop Or .Left < minLeft Or .Left > maxLeft Then
        If celFormTop.Value > maxTop Or celFormLeft.Value > maxLeft Then
            celFormTop = defaultOffset
            celFormLeft = defaultOffset
        End If
        If .Top > maxTop Or .left > maxLeft Then
            .Top = defaultOffset
            .left = defaultOffset
        End If
    End With
End Sub


问:
jQuery draggable: distance and delay at same time does not work
I want to use the distance and delay parameter of a draggable at the same time. The goal is, that I do not need to move the mouse to start the drag effect, but it should start after 500ms to prevent unintentional moves.

This seems not to work. Here is an example for you to test:

```<code>$('.cube').draggable(
{
   distance: 0,
   delay: 500,
   start : function()
   {
    $('.cube').css('background', 'green');
   },
   stop: function()
   {
    $('.cube').css('background', 'red');
   }
});
</code>```

http://jsfiddle.net/MfegM/2392/

As it is, if you click without moving, it will not drag. When you remove the delay option, it will drag without moving but immediatly.

So is this a bug or a feature and is there any workaround?

Regards

Claus

答:
This is a feature, you can refer to this link http://api.jqueryui.com/draggable/#option-delay

```<code>$( ".selector" ).draggable({
  delay: 300
});
</code>```

Setting delay to 0 will avoid the lag..

Body:
I want to use the distance and delay parameter of a draggable at the same time. The goal is, that I do not need to move the mouse to start the drag effect, but it should start after 500ms to prevent unintentional moves.

This seems not to work. Here is an example for you to test:

$('.cube').draggable(
{
   distance: 0,
   delay: 500,
   start : function()
   {
    $('.cube').css('background', 'green');
   },
   stop: function()
   {
    $('.cube').css('background', 'red');
   }
});

http://jsfiddle.net/MfegM/2392/

As it is, if you click without moving, it will not drag. When you remove the delay option, it will drag without moving but immediatly.

So is this a bug or a feature and is there any workaround?

Regards

Claus

Body:
This is a feature, you can refer to this link http://api.jqueryui.com/draggable/#option-delay

$( ".selector" ).draggable({
  delay: 300
});

Setting delay to 0 will avoid the lag..


问:
hangfire Could not load file or assembly 'DynamicProxyGenAssembly2
I have setup Hangfire as below:

```<code> var t = IocManager.Resolve<TestJob>();

 RecurringJob.AddOrUpdate("sendDailyEmail",() => t.sendEmail(), Cron.Daily);
</code>```

When I access the Hangfire dashboard, I can see the Recurring Jobs 1, but the job is not executed and I get this error:

Could not load file or assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

What is wrong with my setup?

答:
Might not be the same context as yours but I think it's still worth adding it here:

-Hangfire server was running as a Windows service;

-Hangfire dashboard running on top of a ASP.NET MVC 5 app;

-jobs were actually running but dashboard kept displaying a FileNotFoundException;

Solution: added a reference to the missing assembly (ie: 'DynamicProxyGenAssembly2') in the dashboard web app.

Same problem was reported and solved in the same way by @reggieboyYEAH.

Details here: https://github.com/HangfireIO/Hangfire/issues/558

Body:
I have setup Hangfire as below:

 var t = IocManager.Resolve<TestJob>();

 RecurringJob.AddOrUpdate("sendDailyEmail",() => t.sendEmail(), Cron.Daily);

When I access the Hangfire dashboard, I can see the Recurring Jobs 1, but the job is not executed and I get this error:

Could not load file or assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

What is wrong with my setup?


问:
Generate a new random number on button click
I have a number guessing app and when the user finds out the random number, a new button appears which is a play again button. When the user clicks it, it should generate a new random number so the user can find it out but it doesn't, it generates the same old random number</p>

```<code>import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
Button button;
Button btnReplay;
int randomNumber;

public void checkGuess(View view){

    button = (Button)findViewById(R.id.button);

    EditText editText = (EditText)findViewById(R.id.editText);
    ImageView imgCheck = (ImageView)findViewById(R.id.imageViewCheck);
    ImageView imgWrong = (ImageView)findViewById(R.id.imageViewWrong);
    String edittextString = editText.getText().toString()
    Integer edittextInt = Integer.parseInt(edittextString);
    MediaPlayer mediaPlayer = MediaPlayer.create(this,
          R.raw.correctanswer);
    btnReplay.setVisibility(View.INVISIBLE);
    if (edittextInt > randomNumber){
        imgWrong.setVisibility(View.VISIBLE);
        imgCheck.setVisibility(View.INVISIBLE);
        button.setVisibility(View.VISIBLE);
        btnReplay.setVisibility(View.INVISIBLE);
        Toast.makeText(getApplicationContext(), "لەم ژمارەیە نزمترە!" ,
           Toast.LENGTH_LONG).show();
               } else if (edittextInt < randomNumber){
         imgWrong.setVisibility(View.VISIBLE);
        imgCheck.setVisibility(View.INVISIBLE);
        Toast.makeText(getApplicationContext(), "لەم ژمارەیە زیاترە",
               Toast.LENGTH_LONG).show();
        button.setVisibility(View.VISIBLE);
        btnReplay.setVisibility(View.INVISIBLE);
    }
    else if (edittextInt == randomNumber){
        Toast.makeText(getApplicationContext(), "زۆر باشە ! ژمارەکەت
               زانی", Toast.LENGTH_LONG).show();
        imgWrong.setVisibility(View.INVISIBLE);
        imgCheck.setVisibility(View.VISIBLE);
        mediaPlayer.start();
        btnReplay.setVisibility(View.VISIBLE);
        button.setVisibility(View.INVISIBLE);
    }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Random random = new Random();
    randomNumber= random.nextInt(51);
    new AlertDialog.Builder(this).setTitle("بیخوێنەوە").setMessage("ژمارە
      ٠٥٠").setNeutralButton("OK", null).show();
    btnReplay = (Button)findViewById(R.id.btnReplay);
    btnReplay.setOnClickListener(new View.OnClickListener() {
        @Override
                public void onClick(View v) {
                    Math.random();
                    checkGuess(findViewById(R.id.btnReplay));
                 }
            });
        }
     }
</code>```

答:
You generate a random number with

```<code>randomNumber= random.nextInt(51);
</code>```

I assume this line is in onCreate()  your activity class. (You should edit your question to clarify this.) In other words you only generate one random number when your app is created. If you want to generate a random number each time the user clicks a button then you must do so in the correct method, an onClick().

Body:
I have a number guessing app and when the user finds out the random number, a new button appears which is a play again button. When the user clicks it, it should generate a new random number so the user can find it out but it doesn't, it generates the same old random number

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
Button button;
Button btnReplay;
int randomNumber;

public void checkGuess(View view){

    button = (Button)findViewById(R.id.button);

    EditText editText = (EditText)findViewById(R.id.editText);
    ImageView imgCheck = (ImageView)findViewById(R.id.imageViewCheck);
    ImageView imgWrong = (ImageView)findViewById(R.id.imageViewWrong);
    String edittextString = editText.getText().toString()
    Integer edittextInt = Integer.parseInt(edittextString);
    MediaPlayer mediaPlayer = MediaPlayer.create(this,
          R.raw.correctanswer);
    btnReplay.setVisibility(View.INVISIBLE);
    if (edittextInt > randomNumber){
        imgWrong.setVisibility(View.VISIBLE);
        imgCheck.setVisibility(View.INVISIBLE);
        button.setVisibility(View.VISIBLE);
        btnReplay.setVisibility(View.INVISIBLE);
        Toast.makeText(getApplicationContext(), "لەم ژمارەیە نزمترە!" ,
           Toast.LENGTH_LONG).show();
               } else if (edittextInt < randomNumber){
         imgWrong.setVisibility(View.VISIBLE);
        imgCheck.setVisibility(View.INVISIBLE);
        Toast.makeText(getApplicationContext(), "لەم ژمارەیە زیاترە",
               Toast.LENGTH_LONG).show();
        button.setVisibility(View.VISIBLE);
        btnReplay.setVisibility(View.INVISIBLE);
    }
    else if (edittextInt == randomNumber){
        Toast.makeText(getApplicationContext(), "زۆر باشە ! ژمارەکەت
               زانی", Toast.LENGTH_LONG).show();
        imgWrong.setVisibility(View.INVISIBLE);
        imgCheck.setVisibility(View.VISIBLE);
        mediaPlayer.start();
        btnReplay.setVisibility(View.VISIBLE);
        button.setVisibility(View.INVISIBLE);
    }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Random random = new Random();
    randomNumber= random.nextInt(51);
    new AlertDialog.Builder(this).setTitle("بیخوێنەوە").setMessage("ژمارە
      ٠٥٠").setNeutralButton("OK", null).show();
    btnReplay = (Button)findViewById(R.id.btnReplay);
    btnReplay.setOnClickListener(new View.OnClickListener() {
        @Override
                public void onClick(View v) {
                    Math.random();
                    checkGuess(findViewById(R.id.btnReplay));
                 }
            });
        }
     }

Body:
You generate a random number with

randomNumber= random.nextInt(51);

I assume this line is in onCreate()  your activity class. (You should edit your question to clarify this.) In other words you only generate one random number when your app is created. If you want to generate a random number each time the user clicks a button then you must do so in the correct method, an onClick().


问:
How to compile a simple Qt and c++ application using g++ on mac os x?
I am trying to use Qt for a project in school but am running into problems. I started following the tutorials and I am running into Makefile problems. Most of the tutorials say to run qmake -project, then qmake and finally make. But when I try this I run into the error make: *** No targets specified and no makefile found.  Stop. I dont know much about Makefiles really. Could someone help point me in the right direction?

答: It's been a little while, but I think your problem is that qmake on Mac OS X creates xcode project files by default, instead of makefiles.  That's why no makefile was found when you ran make.  Instead, look in the command lines for qmake to specify how to target makefiles.  Also, there might be an option you can add to the .pro file to force a makefile output every time.</p>

OwnerDisplayName: cjhuitt


问:
plot 3d in python using three lists
I followed this link to plot the 3D figure.
My problem is I have already 3 lists for X, Y, Z

X.shape (n,) ,  Y.shape (n,) ,  Z.shape (n,)

How to pass these lists into surf = ax.plot_surface(X, Y, Z) as link show each of these variables have the following shape

X.shape (n,n) ,  Y.shape (n,n) ,  Z.shape (n,n)

If I passed these coordinate as them each one shape is (n,) then the 3d figure will appear as empty there is no points will be plotted!

I tried to use the np.meshgrid as following but this way will show only one surface in one plane instead of 3d points!

```<code>X,Y,Z = np.meshgrid(X,Y,Z)

X = X[0]
Y = Y[0]
Z = Z[0]

fig = plt.figure()

ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z)
plt.show()
</code>```

答:
The solution will depend on how the data is organized.

Data on regular grid

If the X and Y data already define a grid, they can be easily reshaped to a quadrilateral grid. E.g.

```<code>#x  y  z
 4  1  3
 6  1  8
 8  1 -9
 4  2 10
 6  2 -1
 8  2 -8
 4  3  8
 6  3 -9
 8  3  0
 4  4 -1
 6  4 -8
 8  4  8
</code>```

can plotted as a plot_surface using

```<code>ax = fig.gca(projection='3d')
ax.plot_surface(X.reshape(4,3), Y.reshape(4,3), Z.reshape(4,3))
</code>```

Arbitrary data

(a) In case the data is not living on a quadrilateral grid, one can interpolate the data on a grid. One method to do so is provided by matplotlib itself, using matplotlib.mlab.griddata.

```<code>import matplotlib.mlab
xi = np.linspace(4, 8, num=10)
yi = np.linspace(1, 4, num=10)
zi = matplotlib.mlab.griddata(X, Y, Z, xi, yi, interp='linear')
ax.plot_surface(xi, yi, zi)
</code>```

(b) Finally, one can plot a surface completely without the use of a quadrilateral grid. This can be done using plot_trisurf.

```<code>plt.plot_trisurf(X,Y,Z)
</code>```

This answer is an adapted version of my answer for contour plots.

Title: plot 3d in python using three lists

Body:
I followed this link to plot the 3D figure.
My problem is I have already 3 lists for X, Y, Z

X.shape (n,) ,  Y.shape (n,) ,  Z.shape (n,)

How to pass these lists into surf = ax.plot_surface(X, Y, Z) as link show each of these variables have the following shape

X.shape (n,n) ,  Y.shape (n,n) ,  Z.shape (n,n)

If I passed these coordinate as them each one shape is (n,) then the 3d figure will appear as empty there is no points will be plotted!

I tried to use the np.meshgrid as following but this way will show only one surface in one plane instead of 3d points!

X,Y,Z = np.meshgrid(X,Y,Z)

X = X[0]
Y = Y[0]
Z = Z[0]

fig = plt.figure()

ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z)
plt.show()

Body:
The solution will depend on how the data is organized.

Data on regular grid

If the X and Y data already define a grid, they can be easily reshaped to a quadrilateral grid. E.g.

#x  y  z
 4  1  3
 6  1  8
 8  1 -9
 4  2 10
 6  2 -1
 8  2 -8
 4  3  8
 6  3 -9
 8  3  0
 4  4 -1
 6  4 -8
 8  4  8

can plotted as a plot_surface using

ax = fig.gca(projection='3d')
ax.plot_surface(X.reshape(4,3), Y.reshape(4,3), Z.reshape(4,3))

Arbitrary data

(a) In case the data is not living on a quadrilateral grid, one can interpolate the data on a grid. One method to do so is provided by matplotlib itself, using matplotlib.mlab.griddata.

import matplotlib.mlab
xi = np.linspace(4, 8, num=10)
yi = np.linspace(1, 4, num=10)
zi = matplotlib.mlab.griddata(X, Y, Z, xi, yi, interp='linear')
ax.plot_surface(xi, yi, zi)

(b) Finally, one can plot a surface completely without the use of a quadrilateral grid. This can be done using plot_trisurf.

plt.plot_trisurf(X,Y,Z)

This answer is an adapted version of my answer for contour plots.


问:
url with % doesn't get to api
Hi trying to get a signUrl from S3, for some reason making the call with % isn't parse correctly by my code. I get a 404 not found.

This is the ajax request:

https://stage.musicmarkers.com/website/api/admin/get-signed-url/thumbnail/magazine%2F2BE.gif/image%2Fgif

My API:

```<code>app.get('/website/api/admin/get-signed-url/thumbnail/:key/:type', auth.getMember, directives.noCache, getThumbnailSingedUrl);
</code>```

My function:

```<code>function getThumbnailSingedUrl(req, res) {

    if (!isAdmin(req, res)) {
        return;
    }

    var key = req.params.key || '';
    var type = req.params.type || '';

    ThumbnailBucketFacade.getSignedUrl(
        'putObject',
        key,
        type,
        function onGotSignedUrl(error, result) {
            if (error) {
                RestResponse.serverError(res, error);
            } else {
                RestResponse.ok(res, result);
            }
        }
    );
}
</code>```

Making the call in a dev environment works.

Making the call without % environment works.

Same code exactly in a different project works.

Any ideas?

答:
I believe what you have is encoded URI. So you need to decode it before using it:

```<code>const key = req.params.key && decodeURIComponent(req.params.key) || '';
const type = req.params.type && decodeURIComponent(req.params.type) || '';
</code>```

More on decoreURIComponent here.

This is also backward compatible, so you don't have to worry that a plain string will get mangled.

Title: url with % doesn't get to api

Body:
Hi trying to get a signUrl from S3, for some reason making the call with % isn't parse correctly by my code. I get a 404 not found.

This is the ajax request:

https://stage.musicmarkers.com/website/api/admin/get-signed-url/thumbnail/magazine%2F2BE.gif/image%2Fgif

My API:

app.get('/website/api/admin/get-signed-url/thumbnail/:key/:type', auth.getMember, directives.noCache, getThumbnailSingedUrl);

My function:

function getThumbnailSingedUrl(req, res) {

    if (!isAdmin(req, res)) {
        return;
    }

    var key = req.params.key || '';
    var type = req.params.type || '';

    ThumbnailBucketFacade.getSignedUrl(
        'putObject',
        key,
        type,
        function onGotSignedUrl(error, result) {
            if (error) {
                RestResponse.serverError(res, error);
            } else {
                RestResponse.ok(res, result);
            }
        }
    );
}

Making the call in a dev environment works.

Making the call without % environment works.

Same code exactly in a different project works.

Any ideas?

Body:
I believe what you have is encoded URI. So you need to decode it before using it:

const key = req.params.key && decodeURIComponent(req.params.key) || '';
const type = req.params.type && decodeURIComponent(req.params.type) || '';

More on decoreURIComponent here.

This is also backward compatible, so you don't have to worry that a plain string will get mangled.


问:
EF: Login exception when binding custom object to User Identity

Unable to determine the principal end of an association between the types 'EntityFrameworkDatabase.Person' and 'EntityFrameworkDatabase.ApplicationUser'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

I know this questions is answered many times but I think I experience a different problem. ref

I have a relation (0-1 0-1) between User in Identity class and my own class Person. ref, ref

```<code>            modelBuilder.Entity<ApplicationUser>()
            .HasOptional(s => s.Person)
            .WithOptionalPrincipal()
            .Map(s => s.MapKey("ApplicationUserId"));

        modelBuilder.Entity<Person>()
            .HasOptional(s => s.ApplicationUser)
            .WithOptionalPrincipal()
            .Map(s => s.MapKey("PersonId"));
</code>```

It works fine to migrate and I get two FK. But when I try to login a user I get an exception at

```<code>ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
</code>```

Why I get the exception when trying to login but not Updating the db and how to solve the problem?

答: The solution is to use the same context for the OwinContext as for the DataContext. </p>

Body:
Unable to determine the principal end of an association between the types 'EntityFrameworkDatabase.Person' and 'EntityFrameworkDatabase.ApplicationUser'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

I know this questions is answered many times but I think I experience a different problem. ref

I have a relation (0-1 0-1) between User in Identity class and my own class Person. ref, ref

            modelBuilder.Entity<ApplicationUser>()
            .HasOptional(s => s.Person)
            .WithOptionalPrincipal()
            .Map(s => s.MapKey("ApplicationUserId"));

        modelBuilder.Entity<Person>()
            .HasOptional(s => s.ApplicationUser)
            .WithOptionalPrincipal()
            .Map(s => s.MapKey("PersonId"));

It works fine to migrate and I get two FK. But when I try to login a user I get an exception at

ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

Why I get the exception when trying to login but not Updating the db and how to solve the problem?


问:
Noob in Ruby - is there diff between " " and ' ' after puts
I have one beginner question for Ruby. I have been practicing Ruby with Chris Pine book and I see that he sometimes uses ' ' and sometimes " " after puts method.

Now, I have realized that I cant put any variable with # { } if I use ' ' since I have tried that , and also, if I use for example " " I don't have to discount ' with backslash like this \' (and other way around) but other than that I don't know are there any major differences between these to things or in other words should I sometimes use exclusively ' ' and sometimes " " ?

Tnx

答:
There are two differences:

String interpolation: Double quotes allow it, single quotes won't.

For example:

```<code>name = "SrdjaNo1"

puts "Hi #{name}!"
#=> Hi SrdjaNo1!

puts 'Hi #{name}!'
#=> Hi #{name}!
</code>```

Escaping sequences: Single quotes will print them as text.

For example:

```<code>puts "Hello \nworld!"
#=> Hello
#=> world!

puts 'Hello \nworld!'
#=> Hello \nworld!
</code>```

Other than that, you could use any of them, just be consistent with its use throughout your code.

Body:
There are two differences:

String interpolation: Double quotes allow it, single quotes won't.

For example:

name = "SrdjaNo1"

puts "Hi #{name}!"
#=> Hi SrdjaNo1!

puts 'Hi #{name}!'
#=> Hi #{name}!

Escaping sequences: Single quotes will print them as text.

For example:

puts "Hello \nworld!"
#=> Hello
#=> world!

puts 'Hello \nworld!'
#=> Hello \nworld!

Other than that, you could use any of them, just be consistent with its use throughout your code.


问:
Why is this bool value not saving?
I am trying to save a simple piece of information using NSUserdefaults. I am trying to save a SKSprite to have an alpha of 1 using a bool value. Here is how I am doing it.

First scene: Level select (sprite alpha is 0.2)
When user completes Level: (edit sprite in Level Select to equal one)

GameViewController:

```<code>//
//  GameViewController.swift
//  Maze
//
//  Created by PixelatedAngel on 4/24/17.
//  Copyright © 2017 PixelatedAngel. All rights reserved.
//

import UIKit
import SpriteKit
import GameplayKit

public let levelselect = SKScene(fileNamed: "LevelSelect")

class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    if let view = self.view as! SKView? {
        // Load the SKScene from 'GameScene.sks'
        if let scene = levelselect {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .fill
            // Present the scene
            view.presentScene(scene)
        }
        view.ignoresSiblingOrder = true
        view.showsFPS = true
        view.showsNodeCount = true
    }
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    if UIDevice.current.userInterfaceIdiom == .phone {
        return .allButUpsideDown
    } else {
        return .all
    }
}

override func viewWillAppear(_ animated: Bool) {
    //saved data here
    if let x = UserDefaults.standard.object(forKey: "LevelOne")
    {
        isLevelOneCompleted = x as! Bool
    }

    if let z = UserDefaults.standard.object(forKey: "LevelTwoButton")
    {
        unlockLevelTwoButton = z as! Bool
        print("Trying to Retrive the value of Level Two Button")
    }
}
}
</code>```

Level One:

```<code>//
//  GameScene.swift
//  Maze
//
//  Created by PixelatedAngel on 4/24/17.
//  Copyright © 2017 PixelatedAngel. All rights reserved.
//

import SpriteKit
import GameplayKit
import CoreMotion

public var isLevelOneCompleted = false
public var unlockLevelTwoButton = false

class LevelOne: SKScene, SKPhysicsContactDelegate {
    var levelonescene:SKScene!
    var player = SKSpriteNode()
    var endNode = SKSpriteNode()
    let manager = CMMotionManager()

override func didMove(to view: SKView) {
    self.physicsBody = SKPhysicsBody (edgeLoopFrom: self.frame)
    self.physicsWorld.contactDelegate = self

    player = self.childNode(withName: "player") as! SKSpriteNode
    player.physicsBody?.categoryBitMask = 1
    endNode = self.childNode(withName: "endNode") as! SKSpriteNode
    endNode.physicsBody?.categoryBitMask = 2
    manager.startAccelerometerUpdates()
    manager.accelerometerUpdateInterval = 0.1
    manager.startAccelerometerUpdates(to: OperationQueue.main){
        (data, error) in

        self.physicsWorld.gravity = CGVector(dx: ((data?.acceleration.x)! * 10), dy: ((data?.acceleration.y)! * 10))
    }
}

func didBegin(_ contact: SKPhysicsContact) {
    var bodyA = contact.bodyA
    var bodyB = contact.bodyB
    let threeStars = SKScene(fileNamed: "LevelCompleted3Star")

    let fadeAction = SKAction.fadeAlpha(by: 1, duration: 0.45)

    if bodyA.categoryBitMask == 1 && bodyB.categoryBitMask == 2 || bodyA.categoryBitMask == 2 && bodyB.categoryBitMask == 1{
        print("Level One complete")
        levelOneCompleted()
        unlockLevelTwo()
        //3 stars
        threeStars?.scaleMode = .fill
        self.view?.presentScene(threeStars!, transition: .fade(withDuration: 0.3))
 }
        }

func levelOneCompleted(){
    isLevelOneCompleted = true
}

func unlockLevelTwo(){
    unlockLevelTwoButton = true
    print("unlock level two = true")
}
}
</code>```

3 Star:

```<code>//
//  GameScene.swift
//  Maze
//
//  Created by PixelatedAngel on 4/24/17.
//  Copyright © 2017 PixelatedAngel. All rights reserved.
//

import SpriteKit
import GameplayKit
import CoreMotion

public let levelselectscene = SKScene(fileNamed: "LevelSelect")

class LevelCompletedThreeStar: SKScene, SKPhysicsContactDelegate {

    override func didMove(to view: SKView) {
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if isLevelOneCompleted == true{
            print("islevelonecompleted is true..")
            UserDefaults.standard.set(isLevelOneCompleted, forKey: "LevelOne")
            UserDefaults.standard.set(unlockLevelTwoButton, forKey: "LevelTwoButton")
            UserDefaults.standard.synchronize()
            levelselect?.scaleMode = .fill
            levelselect?.childNode(withName: "levelTwoButton")?.alpha = 1
            self.view?.presentScene(levelselect)
        }
}
}
</code>```

Level Select:

```<code>//
//  GameScene.swift
//  Maze
//
//  Created by PixelatedAngel on 4/24/17.
//  Copyright © 2017 PixelatedAngel. All rights reserved.
//

import SpriteKit
import GameplayKit

class LevelSelect: SKScene {

    override func didMove(to view: SKView) {

        if let z = UserDefaults.standard.object(forKey: "LevelTwoButton")
        {
            unlockLevelTwoButton = z as! Bool
            print("Trying to Retrive the value of Level Two Button in Level Select")
        }

        if unlockLevelTwoButton == true {
            levelselectscene?.childNode(withName: "LevelTwoButton")?.alpha = 1
               UserDefaults.standard.set(unlockLevelTwoButton, forKey: "LevelTwoUnlocked")
            print("I got this far")
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let levelOne = SKScene(fileNamed: "LevelOne")
        levelOne?.scaleMode = .fill

        let levelTwo = SKScene(fileNamed: "LevelTwo")
        levelTwo?.scaleMode = .fill

        for touch in touches {
            let location = touch.location(in: self)
            let node : SKNode = self.atPoint(location)
            if node.name == "levelOneButton" {
                self.view?.presentScene(levelOne!, transition: SKTransition.fade(withDuration: 0.2))
                }

            if isLevelOneCompleted == true && node.name == "levelTwoButton"{
                self.view?.presentScene(levelTwo!, transition: SKTransition.fade(withDuration: 0.2))

            }
        }
        }
    }
</code>```

答: In your view controller, GameViewController, you get the value you have stored.  Later in the app lifecycle, you instantiate your game scene: LevelOne.  When LevelOne is initialized, you set your global variable to false [without checking user defaults]. I wonder if it would make a difference if, instead of declaring your global in a different file, you define it at the top of your view controller, and set it in viewDidLoad after checking user defaults.  You could even make the global variable static.</p>

Title: Why is this bool value not saving?

Body:
I am trying to save a simple piece of information using NSUserdefaults. I am trying to save a SKSprite to have an alpha of 1 using a bool value. Here is how I am doing it.

First scene: Level select (sprite alpha is 0.2)
When user completes Level: (edit sprite in Level Select to equal one)

GameViewController:

//
//  GameViewController.swift
//  Maze
//
//  Created by PixelatedAngel on 4/24/17.
//  Copyright © 2017 PixelatedAngel. All rights reserved.
//

import UIKit
import SpriteKit
import GameplayKit

public let levelselect = SKScene(fileNamed: "LevelSelect")

class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    if let view = self.view as! SKView? {
        // Load the SKScene from 'GameScene.sks'
        if let scene = levelselect {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .fill
            // Present the scene
            view.presentScene(scene)
        }
        view.ignoresSiblingOrder = true
        view.showsFPS = true
        view.showsNodeCount = true
    }
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    if UIDevice.current.userInterfaceIdiom == .phone {
        return .allButUpsideDown
    } else {
        return .all
    }
}

override func viewWillAppear(_ animated: Bool) {
    //saved data here
    if let x = UserDefaults.standard.object(forKey: "LevelOne")
    {
        isLevelOneCompleted = x as! Bool
    }

    if let z = UserDefaults.standard.object(forKey: "LevelTwoButton")
    {
        unlockLevelTwoButton = z as! Bool
        print("Trying to Retrive the value of Level Two Button")
    }
}
}

Level One:

//
//  GameScene.swift
//  Maze
//
//  Created by PixelatedAngel on 4/24/17.
//  Copyright © 2017 PixelatedAngel. All rights reserved.
//

import SpriteKit
import GameplayKit
import CoreMotion

public var isLevelOneCompleted = false
public var unlockLevelTwoButton = false

class LevelOne: SKScene, SKPhysicsContactDelegate {
    var levelonescene:SKScene!
    var player = SKSpriteNode()
    var endNode = SKSpriteNode()
    let manager = CMMotionManager()

override func didMove(to view: SKView) {
    self.physicsBody = SKPhysicsBody (edgeLoopFrom: self.frame)
    self.physicsWorld.contactDelegate = self

    player = self.childNode(withName: "player") as! SKSpriteNode
    player.physicsBody?.categoryBitMask = 1
    endNode = self.childNode(withName: "endNode") as! SKSpriteNode
    endNode.physicsBody?.categoryBitMask = 2
    manager.startAccelerometerUpdates()
    manager.accelerometerUpdateInterval = 0.1
    manager.startAccelerometerUpdates(to: OperationQueue.main){
        (data, error) in

        self.physicsWorld.gravity = CGVector(dx: ((data?.acceleration.x)! * 10), dy: ((data?.acceleration.y)! * 10))
    }
}

func didBegin(_ contact: SKPhysicsContact) {
    var bodyA = contact.bodyA
    var bodyB = contact.bodyB
    let threeStars = SKScene(fileNamed: "LevelCompleted3Star")

    let fadeAction = SKAction.fadeAlpha(by: 1, duration: 0.45)

    if bodyA.categoryBitMask == 1 && bodyB.categoryBitMask == 2 || bodyA.categoryBitMask == 2 && bodyB.categoryBitMask == 1{
        print("Level One complete")
        levelOneCompleted()
        unlockLevelTwo()
        //3 stars
        threeStars?.scaleMode = .fill
        self.view?.presentScene(threeStars!, transition: .fade(withDuration: 0.3))
 }
        }

func levelOneCompleted(){
    isLevelOneCompleted = true
}

func unlockLevelTwo(){
    unlockLevelTwoButton = true
    print("unlock level two = true")
}
}

3 Star:

//
//  GameScene.swift
//  Maze
//
//  Created by PixelatedAngel on 4/24/17.
//  Copyright © 2017 PixelatedAngel. All rights reserved.
//

import SpriteKit
import GameplayKit
import CoreMotion

public let levelselectscene = SKScene(fileNamed: "LevelSelect")

class LevelCompletedThreeStar: SKScene, SKPhysicsContactDelegate {

    override func didMove(to view: SKView) {
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if isLevelOneCompleted == true{
            print("islevelonecompleted is true..")
            UserDefaults.standard.set(isLevelOneCompleted, forKey: "LevelOne")
            UserDefaults.standard.set(unlockLevelTwoButton, forKey: "LevelTwoButton")
            UserDefaults.standard.synchronize()
            levelselect?.scaleMode = .fill
            levelselect?.childNode(withName: "levelTwoButton")?.alpha = 1
            self.view?.presentScene(levelselect)
        }
}
}

Level Select:

//
//  GameScene.swift
//  Maze
//
//  Created by PixelatedAngel on 4/24/17.
//  Copyright © 2017 PixelatedAngel. All rights reserved.
//

import SpriteKit
import GameplayKit

class LevelSelect: SKScene {

    override func didMove(to view: SKView) {

        if let z = UserDefaults.standard.object(forKey: "LevelTwoButton")
        {
            unlockLevelTwoButton = z as! Bool
            print("Trying to Retrive the value of Level Two Button in Level Select")
        }

        if unlockLevelTwoButton == true {
            levelselectscene?.childNode(withName: "LevelTwoButton")?.alpha = 1
               UserDefaults.standard.set(unlockLevelTwoButton, forKey: "LevelTwoUnlocked")
            print("I got this far")
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let levelOne = SKScene(fileNamed: "LevelOne")
        levelOne?.scaleMode = .fill

        let levelTwo = SKScene(fileNamed: "LevelTwo")
        levelTwo?.scaleMode = .fill

        for touch in touches {
            let location = touch.location(in: self)
            let node : SKNode = self.atPoint(location)
            if node.name == "levelOneButton" {
                self.view?.presentScene(levelOne!, transition: SKTransition.fade(withDuration: 0.2))
                }

            if isLevelOneCompleted == true && node.name == "levelTwoButton"{
                self.view?.presentScene(levelTwo!, transition: SKTransition.fade(withDuration: 0.2))

            }
        }
        }
    }


问:
Python subprocess call in linux os not working as expected
I am trying below code in linux and trying to run linux commands in python script.

Below is the script:

```<code>import os
import sys
from subprocess import call
a = "Team0"
b = "Team0"
c = "\'{\"runner:{\"name\": \"lacp\"}}\'"
cmd = 'nmcli con add type team con-name {} ifname {} config {}'.format(a, b, c)
print cmd
call(cmd.split(), shell=False)
</code>```

I am getting below error.

```<code>nmcli con add type team con-name Team0 ifname Team0 config '{"runner:{"name": "lacp"}}'
Error: ''{"runner:{"name":' is not a valid team configuration or file name.
</code>```

I have copy pasted above print command on linux command prompt it is working fine.

Could any one help me to fix this in my code

答:
Several issues:

1) you're splitting on a space.  So the arguments become:

```<code>cmd[0] = nmcli
cmd[1] = con
cmd[2] = add
cmd[3] = type
cmd[4] = team
cmd[5] = con-name
cmd[6] = Team0
cmd[7] = ifname
cmd[8] = Team0
cmd[9] = config
cmd[10] = '{"runner:{"name":
cmd[11] = "lacp"}}'
</code>```

which is why you get the Error message. Note that it's reporting everything right before the "lacp"...

2) Since you are setting shell=False the single quotes wrapping  the team config will NOT be parsed as you think.

So you can either set shell=True and NOT split the command or fix the parsing.

I suggest:

```<code> call(cmd, shell=True)
</code>```

as the easiest approach (note the split is missing)

Body:
I am trying below code in linux and trying to run linux commands in python script.

Below is the script:

import os
import sys
from subprocess import call
a = "Team0"
b = "Team0"
c = "\'{\"runner:{\"name\": \"lacp\"}}\'"
cmd = 'nmcli con add type team con-name {} ifname {} config {}'.format(a, b, c)
print cmd
call(cmd.split(), shell=False)

I am getting below error.

nmcli con add type team con-name Team0 ifname Team0 config '{"runner:{"name": "lacp"}}'
Error: ''{"runner:{"name":' is not a valid team configuration or file name.

I have copy pasted above print command on linux command prompt it is working fine.

Could any one help me to fix this in my code

Body:
Several issues:

1) you're splitting on a space.  So the arguments become:

cmd[0] = nmcli
cmd[1] = con
cmd[2] = add
cmd[3] = type
cmd[4] = team
cmd[5] = con-name
cmd[6] = Team0
cmd[7] = ifname
cmd[8] = Team0
cmd[9] = config
cmd[10] = '{"runner:{"name":
cmd[11] = "lacp"}}'

which is why you get the Error message. Note that it's reporting everything right before the "lacp"...

2) Since you are setting shell=False the single quotes wrapping  the team config will NOT be parsed as you think.

So you can either set shell=True and NOT split the command or fix the parsing.

I suggest:

 call(cmd, shell=True)

as the easiest approach (note the split is missing)


问:
How do I make this Fibonacci sequence generator more elegant?
```<code>package main

import "fmt"

func fib_seq() func() int {
    n0, n1 := 0, 1

    return func() int {
        result := n0
        n0, n1 = n1, n0 + n1
        return result
    }
}

func main() {
    f := fib_seq()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}
</code>```

This is my Fibonacci sequence generator. The definition of result is unwanted (but necessary).

I wonder is there a way to execute x, y = y, x + y after return?

答:
"Elegant" means different things to different people. To some it may mean "conciseness," and to others it may mean "simplicity," or "readability."

Here is my take on it:

```<code>public class Fibonacci {

    private static int x;
    private static int y;
    private static int z;

    public static void main(String[] args) {
        x = 0;
        y = 1;
        z = 0;

        System.out.println(x);
        System.out.println(y);
        while (z < 100) {
            z = x + y;
            System.out.println(z);
            x = y;
            y = z;
        }

    }
}
</code>```

As you can see, I favor readability over sophistication :)

Body:
package main

import "fmt"

func fib_seq() func() int {
    n0, n1 := 0, 1

    return func() int {
        result := n0
        n0, n1 = n1, n0 + n1
        return result
    }
}

func main() {
    f := fib_seq()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}

This is my Fibonacci sequence generator. The definition of result is unwanted (but necessary).

I wonder is there a way to execute x, y = y, x + y after return?

Body:
"Elegant" means different things to different people. To some it may mean "conciseness," and to others it may mean "simplicity," or "readability."

Here is my take on it:

public class Fibonacci {

    private static int x;
    private static int y;
    private static int z;

    public static void main(String[] args) {
        x = 0;
        y = 1;
        z = 0;

        System.out.println(x);
        System.out.println(y);
        while (z < 100) {
            z = x + y;
            System.out.println(z);
            x = y;
            y = z;
        }

    }
}

As you can see, I favor readability over sophistication :)


问:
I can't sign in with another account in visual studio community 2015
I had visual studio community 2015 and I want to delete the older account and use my new one.

I log out my older account and I try my new one, visual studio close automatically.

答:
For your issue, Please check the following steps:

Check the connection of your network. And then open the Internet Explorer, open one website, if it could be opened successfully, indicating your network is well.

Maybe your IE doesn’t trust the Visual Studio web page or the sign in page, try to add the https://www.visualstudio.com/ , https://login.microsoftonline.com/  and https://login.live.com/ to your trusted zone.

If the above doesn’t help, try to enable the JavaScript in Internet Explorer because if the JavaScript is disabled, you will not able to sign in.

Go to Tools -> Internet Options -> Security Tab, and then click the Internet zone, depending on whether you have to customize your Internet security settings, select one of the following options:

If you do not have to customize your Internet security settings, click Default Level.

If you have to customize your Internet security settings, click Custom level, scroll down to the Active scripting section, and then click Enable.

If none of the above helps, please try to create a new account to see whether you could sign in.