问:
How can I set this program to match the MVC design pattern
I believe I have got most of the MVC part down for this program - Game Of Life. However I can't get the MouseListener to work properly. How can I change this match the MVC design pattern?

View

```<code>package lifepreparation;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
import javax.swing.*;
import java.awt.event.MouseListener;

public class LifeView extends JFrame {
    //Label used to house cells
    private LifeModel[][] cellHouse;
    private LifeModel model;

    //Timer used to fire the next generation
    private Timer timer;

    //Generation counter - used to count the number of generations
    private int generationCount = 0;
    private JLabel generationLabel = new JLabel("Generation: 0");

    //Declare action buttons
    private JButton startB = new JButton("Start");
    private JButton pauseB = new JButton("Pause");
    private JButton clearB = new JButton("Clear");

    //Slider to adjust the time interval between generations
    private static final int minSpeed = 0;
    private static final int maxSpeed = 1000;
    private static final int speedMajorTicks = (maxSpeed-minSpeed)/5;
    private static final int speedMinorTicks = (maxSpeed-minSpeed)/20;
    JSlider generationS = new JSlider(minSpeed,maxSpeed);

    //Identifies game status: false=pause, true=running
    private boolean runStatus = false;

    //Panel for the city
    private JPanel panel;

    public LifeView(int boardRow, int boardCol, LifeModel model) {
        super("Game Of Life");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //**START Create labels to house cells, +2 more
        cellHouse = new LifeModel[boardRow+2][boardCol+2];
        for(int r = 0; r < boardRow+2; r++) {
            for(int c = 0; c < boardCol+2; c++) {
                cellHouse[r][c] = new LifeModel();
            }
    }
        //--END Create Labels

        //Panel to hold cell houses
        panel = new JPanel(new GridLayout(boardRow, boardCol, 1, 1));
        panel.setBackground(Color.BLACK);
        panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        //Add cellHouses to the panel
        for(int r = 1; r < boardRow+1; r++) {
                for(int c = 1; c < boardCol+1; c++) {
                        panel.add(cellHouse[r][c]);
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c]);    //Add to TOP ^
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c]);    //Add to BOTTOM _
                        cellHouse[r][c].addNeighbor(cellHouse[r][c-1]);    //Add to left <-
                        cellHouse[r][c].addNeighbor(cellHouse[r][c+1]);    //Add to right ->
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c-1]);  //Add to top left ^<-
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c+1]);  //Add to top right ^->
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c-1]);  //Add to bottom left _<-
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c+1]);  //Add to bottom right _->
                }
        }

        //Panel with cellHouses added to the container
        add(panel, BorderLayout.CENTER);

        //South Panel to hold buttons and widgets with extra features
        JPanel panelBottom = new JPanel();

        //buttonPanel to hold start, pause, clear features
        JPanel buttonPanel = new JPanel();

        buttonPanel.add(clearB);
        pauseB.setEnabled(false);
        buttonPanel.add(pauseB);
        buttonPanel.add(startB);

        //speedPanel to hold slider to adjust the time interval
        JPanel speedPanel = new JPanel();
        JLabel speedText = new JLabel("Set Speed:");
        generationS.setMajorTickSpacing(speedMajorTicks);
        generationS.setMinorTickSpacing(speedMinorTicks);
        generationS.setPaintTicks(true);
        // the labels for the Slider
        Hashtable<Integer, JLabel> speedLabel = new Hashtable<Integer, JLabel>();
        for(int i = 0; i <= maxSpeed; i++) {
                speedLabel.put( new Integer( i * speedMajorTicks ), new JLabel("" + i) );
        }
        generationS.setLabelTable(speedLabel);
        generationS.setPaintLabels(true);

        generationLabel.setHorizontalAlignment(SwingConstants.CENTER);

        speedPanel.add(speedText);
        speedPanel.add(generationS);

        panelBottom.add(buttonPanel);
        panelBottom.add(speedPanel);
        panelBottom.add(generationLabel);

        // add bottom panel to the JFrame
        add(panelBottom, BorderLayout.SOUTH);

        // put the frame on
        setLocation(20, 20);
        pack();
        setVisible(true);
    }

        //Action to take dependent on the action referenced by the JButton and Timer
        public void startPauseClear(ActionEvent e) {
                //Get action reference
                Object o = e.getSource();

                //Action reference is to clear
                if(o == clearB) {
                        timer.stop();   //Stop the timer
                        runStatus = false;  //Set game as not running
                        pauseB.setEnabled(false);   //Disable the pause button
                        startB.setEnabled(true);    //Enable the start button
                        //Remove/Clear all cells from the cellHouse
                        for(int r = 1; r < cellHouse.length -1; r++) {
                                for(int c = 1; c < cellHouse[r].length -1; c++) {
                                        cellHouse[r][c].clear();
                                }
                        }
                        //Reset the generation count
                        generationCount = 0;
                        generationLabel.setText("Generation: 0");
                        return;
                }
                //Action reference is to pause
                if(o == pauseB) {
                        timer.stop();   //Stop the timer
                        runStatus = false;  //Set game as not running
                        pauseB.setEnabled(false);   //Disable the pause button
                        startB.setEnabled(true);    //Enable the start button
                        return;
                }
                //Action reference is to start
                if(o == startB) {
                        pauseB.setEnabled(true);    //Enable the pause button
                        startB.setEnabled(false);   //Disable the start button
                        runStatus = true;   //Set game as running
                        timer.setDelay(maxSpeed - generationS.getValue());  //Adjust the speed
                        timer.start();
                        return;
                }

                //If the action is set by timer, set speed
                timer.setDelay(maxSpeed - generationS.getValue());

                //If the game is not running, exit and do nothing more
                if(!runStatus) return;

                //Update generation count and display
                ++generationCount;
                generationLabel.setText("Generation: " + generationCount);

                //Check to see if the cell should be buried
                for(int r = 0; r < cellHouse.length; r++) {
                        for(int c = 0; c < cellHouse[r].length; c++) {
                                cellHouse[r][c].checkGeneration();
                        }
                }

                //Update to the next generation
                for(int r = 0; r < cellHouse.length; r++) {
                        for(int c = 0; c < cellHouse[r].length; c++) {
                                cellHouse[r][c].updateGeneration();
                        }
                }
    }
    public void addActionListener(ActionListener e) {
        clearB.addActionListener(e);
        pauseB.addActionListener(e);
        startB.addActionListener(e);
        timer = new Timer(maxSpeed - generationS.getValue(), e);
    }

}
</code>```

Controller

```<code>package lifepreparation;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class LifeController {
    //Run App
    LifeModel model;
    LifeView view;

    //Constructor
    public LifeController(LifeModel model, LifeView view) {
        this.model = model;
        this.view = view;

        //Add Listeners
        view.addActionListener(new LifeActionListener());
        view.addMouseListener(new LifeMouseListener());
    }

    class LifeActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            view.startPauseClear(e);
        }
    }

    class LifeMouseListener implements MouseListener {
        public void mouseClicked(MouseEvent arg0) {
            model.unselectCell();
        }

        //If the mouse is in a cellHouse while being pressed, cell becomes alive
        public void mouseEntered(MouseEvent arg0) {
            model.selectCells();
        }

        public void mouseExited(MouseEvent arg0) {

        }

        //If the mouse is clicked on a cellHouse, cell comes to life
        public void mousePressed(MouseEvent arg0) {
            model.selectACell();
        }

        //Set mouse as not being held anymore
        public void mouseReleased(MouseEvent arg0) {
            model.setMouseHold();
        }
    }
}
</code>```

Model

```<code>package lifepreparation;

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

//LifeModel to handle cell life and death algorithm
public class LifeModel extends JLabel {
    //Cell Color: cell[0] = dead cell, cell[1] = live cell.
    private static final Color[] color = {Color.LIGHT_GRAY, Color.GREEN};

    //Size of cells
    private static final int cellSize = 15;
    private static final Dimension citySize = new Dimension(cellSize, cellSize);

    //checks if the mouse is still pressed or not
    private boolean mouseHold = false;

    private int currentStatus, newStatus;
    private int nbNeighbor;
    private LifeModel[] Neighbor = new LifeModel[8];

    LifeModel() {
            currentStatus = newStatus = 0;   //Currently Dead
            setOpaque(true);    //Show color
            setBackground(color[0]);    //Light Gray color
            this.setPreferredSize(citySize);   //Set the dimension of the board
    }
    //Add a neighbor
    void addNeighbor(LifeModel n) {
            Neighbor[nbNeighbor++] = n;
    }

    //Check to see if a cell should live or not
    void checkGeneration() {
            //Number of neighbors that are alive
            int nbAlive = 0;

            //Check the status of the neighbors
            for(int i = 0; i < nbNeighbor; i++)
                    nbAlive += Neighbor[i].currentStatus;

            //If status of cell is alive
            if(currentStatus == 1) {
                    //Bury cell if it has less than two neighbors
                    if(nbAlive < 2)
                            newStatus = 0;
                    //Bury cell if it has more than three live neighbors
                    if(nbAlive > 3)
                            newStatus = 0;
            }
            else {
                    //Dead cells with three live neighbors get reborn
                    if(nbAlive == 3)
                            newStatus = 1;
            }
    }
    //Switch to next generation
    void updateGeneration() {
            if(currentStatus != newStatus) {    //Adjust color for the new generation
                    currentStatus = newStatus;
                    setBackground(color[currentStatus]);
            }
    }

    //Bury all cells in the city
    void clear() {
            if(currentStatus == 1 || newStatus == 1) {
                    currentStatus = newStatus = 0;
                    setBackground(color[currentStatus]);
            }
    }

    public void unselectCell() {
            if(currentStatus == 1 || newStatus == 1) {
                    currentStatus = newStatus = 0;
                    setBackground(color[currentStatus]);
            }
    }

    //If the mouse is in a cellHouse while being pressed, cell becomes alive
    public void selectCells() {
            if(mouseHold) {
                    currentStatus = newStatus = 1;
                    setBackground(color[1]);
            }
    }

    //If the mouse is clicked on a cellHouse, cell comes to life
    public void selectACell() {
            mouseHold = true;
            currentStatus = newStatus = 1;
            setBackground(color[1]);
    }

    //Set mouse as not being held anymore
    public void setMouseHold() {
            mouseHold = false;
    }

}
</code>```

Program without MVC implementation

```<code>package lifepreparation;

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

public class LifeView extends JFrame implements ActionListener {

    //Cell Color: cell[0] = dead cell, cell[1] = live cell.
    private static final Color[] color = {Color.LIGHT_GRAY, Color.GREEN};

    //Size of cells
    private static final int cellSize = 15;
    private static final Dimension citySize = new Dimension(cellSize, cellSize);

    //Label used to house cells
    private LifeLabel[][] cellHouse;

    //Timer used to fire the next generation
    private Timer timer;

    //Generation counter - used to count the number of generations
    private int generationCount = 0;
    private JLabel generationLabel = new JLabel("Generation: 0");

    //Declare default buttons
    private JButton startB = new JButton("Start");
    private JButton pauseB = new JButton("Pause");
    private JButton clearB = new JButton("Clear");

    //Slider to adjust the time interval between generations
    private static final int minSpeed = 0;
    private static final int maxSpeed = 1000;
    private static final int speedMajorTicks = (maxSpeed-minSpeed)/5;
    private static final int speedMinorTicks = (maxSpeed-minSpeed)/20;
    JSlider generationS = new JSlider(minSpeed,maxSpeed);

    //Identifies game status: false=pause, true=running
    private boolean runStatus = false;

    // if the mouse is down or not
    private boolean mouseHold = false;

    public LifeView(int boardRow, int boardCol) {
        super("Game Of Life");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //**START Create labels to house cells, +2 more to calculate cells that are out of bounds
        cellHouse = new LifeLabel[boardRow+2][boardCol+2];
        for(int r = 0; r < boardRow+2; r++) {
            for(int c = 0; c < boardCol+2; c++) {
                cellHouse[r][c] = new LifeLabel();
            }
    }
        //--END Create Labels

        //Panel to hold cell houses
        JPanel panel = new JPanel(new GridLayout(boardRow, boardCol, 1, 1));
        panel.setBackground(Color.BLACK);
        panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        //Add cellHouses to the panel
        for(int r = 1; r < boardRow+1; r++) {
                for(int c = 1; c < boardCol+1; c++) {
                        panel.add(cellHouse[r][c]);
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c]);    //Add to TOP ^
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c]);    //Add to BOTTOM _
                        cellHouse[r][c].addNeighbor(cellHouse[r][c-1]);    //Add to left <-
                        cellHouse[r][c].addNeighbor(cellHouse[r][c+1]);    //Add to right ->
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c-1]);  //Add to top left ^<-
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c+1]);  //Add to top right ^->
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c-1]);  //Add to bottom left _<-
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c+1]);  //Add to bottom right _->
                }
        }

        //Panel with cellHouses added to the container
        add(panel, BorderLayout.CENTER);

        //South Panel to hold buttons and widgets with extra features
        JPanel panelBottom = new JPanel();

        //buttonPanel to hold start, pause, clear features
        JPanel buttonPanel = new JPanel();
        clearB.addActionListener(this);
        buttonPanel.add(clearB);
        pauseB.addActionListener(this);
        pauseB.setEnabled(false);
        buttonPanel.add(pauseB);
        startB.addActionListener(this);
        buttonPanel.add(startB);

        //speedPanel to hold slider to adjust the time interval
        JPanel speedPanel = new JPanel();
        JLabel speedText = new JLabel("Set Speed:");
        generationS.setMajorTickSpacing(speedMajorTicks);
        generationS.setMinorTickSpacing(speedMinorTicks);
        generationS.setPaintTicks(true);
        // the labels for the Slider
        Hashtable<Integer, JLabel> speedLabel = new Hashtable<Integer, JLabel>();
        for(int i = 0; i <= maxSpeed; i++) {
                speedLabel.put( new Integer( i * speedMajorTicks ), new JLabel("" + i) );
        }
        generationS.setLabelTable(speedLabel);
        generationS.setPaintLabels(true);

        generationLabel.setHorizontalAlignment(SwingConstants.CENTER);

        speedPanel.add(speedText);
        speedPanel.add(generationS);

        panelBottom.add(buttonPanel);
        panelBottom.add(speedPanel);
        panelBottom.add(generationLabel);

        // add bottom panel to the JFrame
        add(panelBottom, BorderLayout.SOUTH);

        // put the frame on
        setLocation(20, 20);
        pack();
        setVisible(true);
        // start the thread that run the cycles of life
        timer = new Timer(maxSpeed - generationS.getValue(), this);
    }

    //Action to take dependent on the action referenced by the JButton and Timer
    public void actionPerformed(ActionEvent e) {
        //Get action reference
        Object o = e.getSource();

                //Action reference is to clear
        if(o == clearB) {
            timer.stop();   //Stop the timer
            runStatus = false;  //Set game as not running
            pauseB.setEnabled(false);   //Disable the pause button
            startB.setEnabled(true);    //Enable the start button
            //Remove/Clear all cells from the cellHouse
            for(int r = 1; r < cellHouse.length -1; r++) {
                for(int c = 1; c < cellHouse[r].length -1; c++) {
                    cellHouse[r][c].clear();
                }
            }
            //Reset the generation count
            generationCount = 0;
            generationLabel.setText("Generation: 0");
            return;
        }
        //Action reference is to pause
        if(o == pauseB) {
            timer.stop();   //Stop the timer
            runStatus = false;  //Set game as not running
            pauseB.setEnabled(false);   //Disable the pause button
            startB.setEnabled(true);    //Enable the start button
            return;
        }
        //Action reference is to start
        if(o == startB) {
            pauseB.setEnabled(true);    //Enable the pause button
            startB.setEnabled(false);   //Disable the start button
            runStatus = true;   //Set game as running
            timer.setDelay(maxSpeed - generationS.getValue());  //Adjust the speed
            timer.start();
            return;
        }

        //If the action is set by timer, set speed
        timer.setDelay(maxSpeed - generationS.getValue());

        //If the game is not running, exit and do nothing more
        if(!runStatus) return;

                //Update generation count and display
                ++generationCount;
        generationLabel.setText("Generation: " + generationCount);

                //Check to see if the cell should be buried
        for(int r = 0; r < cellHouse.length; r++) {
            for(int c = 0; c < cellHouse[r].length; c++) {
                cellHouse[r][c].checkGeneration();
            }
        }

                //Update to the next generation
        for(int r = 0; r < cellHouse.length; r++) {
            for(int c = 0; c < cellHouse[r].length; c++) {
                cellHouse[r][c].updateGeneration();
            }
        }
    }
     //Run App
    public static void main(String[] arg) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new LifeView(30, 50);
            }
        });
    }

    //LifeModel to handle cell life and death algorithm
    class LifeLabel extends JLabel implements MouseListener {
        private int currentGen, newGen;
        private int nbNeighbor;
        private LifeLabel[] Neighbor = new LifeLabel[8];

        LifeLabel() {
            currentGen = newGen = 0;   //Currently Dead
            setOpaque(true);    //Show color
            setBackground(color[0]);    //Light Gray color
            addMouseListener(this); //Add mouseListener
            this.setPreferredSize(citySize);   //Set the dimension of the board
        }
        //Add a neighbor
        void addNeighbor(LifeLabel n) {
            Neighbor[nbNeighbor++] = n;
        }

        //Check to see if a cell should live or not
        void checkGeneration() {
            //Number of neighbors that are alive
            int nbAlive = 0;

            //Check the status of the neighbors
            for(int i = 0; i < nbNeighbor; i++)
                nbAlive += Neighbor[i].currentGen;

                        //If status of cell is alive
            if(currentGen == 1) {
                                //Bury cell if it has less than two neighbors
                if(nbAlive < 2)
                    newGen = 0;
                                //Bury cell if it has more than three live neighbors
                if(nbAlive > 3)
                    newGen = 0;
            }
            else {
                                //Dead cells with three live neighbors get reborn
                if(nbAlive == 3)
                    newGen = 1;
            }
        }
        //Switch to next generation
        void updateGeneration() {
            if(currentGen != newGen) {  //Adjust color for the new generation
                currentGen = newGen;
                setBackground(color[currentGen]);
            }
        }

        //Bury all cells in the city
        void clear() {
            if(currentGen == 1 || newGen == 1) {
                currentGen = newGen = 0;
                setBackground(color[currentGen]);
            }
        }

        public void mouseClicked(MouseEvent arg0) {
                        if(currentGen == 1 || newGen == 1) {
                currentGen = newGen = 0;
                setBackground(color[currentGen]);
            }
        }

        //If the mouse is in a cellHouse while being pressed, cell becomes alive
        public void mouseEntered(MouseEvent arg0) {
            if(mouseHold) {
                currentGen = newGen = 1;
                setBackground(color[1]);
            }
        }

        public void mouseExited(MouseEvent arg0) {

        }

        //If the mouse is clicked on a cellHouse, cell comes to life
        public void mousePressed(MouseEvent arg0) {
            mouseHold = true;
            currentGen = newGen = 1;
            setBackground(color[1]);
        }

        //Set mouse as not being held anymore
        public void mouseReleased(MouseEvent arg0) {
            mouseHold = false;
        }
    }
}
</code>```

答:
Your code it too hard to follow, but I have done an application using mvc in swing.

My advice is to have something like this in a Main class:

```<code>    MainModel      model      = new MainModel();
    MainView       view       = new MainView(model);
    MainController controller = new MainController(model, view);
</code>```

Your controller is ok.

The view looks ok, but you should have separate addActionListener methods for clearB, startB, pauseB (perhaps that's the problem).

The model is where the brain should be. Do not extend JLabel, doesn't make sense at all.

Hope this helps.

ContentLicense: CC BY-SA 2.5

Body:
I believe I have got most of the MVC part down for this program - Game Of Life. However I can't get the MouseListener to work properly. How can I change this match the MVC design pattern?

View

package lifepreparation;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
import javax.swing.*;
import java.awt.event.MouseListener;

public class LifeView extends JFrame {
    //Label used to house cells
    private LifeModel[][] cellHouse;
    private LifeModel model;

    //Timer used to fire the next generation
    private Timer timer;

    //Generation counter - used to count the number of generations
    private int generationCount = 0;
    private JLabel generationLabel = new JLabel("Generation: 0");

    //Declare action buttons
    private JButton startB = new JButton("Start");
    private JButton pauseB = new JButton("Pause");
    private JButton clearB = new JButton("Clear");

    //Slider to adjust the time interval between generations
    private static final int minSpeed = 0;
    private static final int maxSpeed = 1000;
    private static final int speedMajorTicks = (maxSpeed-minSpeed)/5;
    private static final int speedMinorTicks = (maxSpeed-minSpeed)/20;
    JSlider generationS = new JSlider(minSpeed,maxSpeed);

    //Identifies game status: false=pause, true=running
    private boolean runStatus = false;

    //Panel for the city
    private JPanel panel;

    public LifeView(int boardRow, int boardCol, LifeModel model) {
        super("Game Of Life");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //**START Create labels to house cells, +2 more
        cellHouse = new LifeModel[boardRow+2][boardCol+2];
        for(int r = 0; r < boardRow+2; r++) {
            for(int c = 0; c < boardCol+2; c++) {
                cellHouse[r][c] = new LifeModel();
            }
    }
        //--END Create Labels

        //Panel to hold cell houses
        panel = new JPanel(new GridLayout(boardRow, boardCol, 1, 1));
        panel.setBackground(Color.BLACK);
        panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        //Add cellHouses to the panel
        for(int r = 1; r < boardRow+1; r++) {
                for(int c = 1; c < boardCol+1; c++) {
                        panel.add(cellHouse[r][c]);
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c]);    //Add to TOP ^
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c]);    //Add to BOTTOM _
                        cellHouse[r][c].addNeighbor(cellHouse[r][c-1]);    //Add to left <-
                        cellHouse[r][c].addNeighbor(cellHouse[r][c+1]);    //Add to right ->
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c-1]);  //Add to top left ^<-
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c+1]);  //Add to top right ^->
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c-1]);  //Add to bottom left _<-
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c+1]);  //Add to bottom right _->
                }
        }

        //Panel with cellHouses added to the container
        add(panel, BorderLayout.CENTER);

        //South Panel to hold buttons and widgets with extra features
        JPanel panelBottom = new JPanel();

        //buttonPanel to hold start, pause, clear features
        JPanel buttonPanel = new JPanel();

        buttonPanel.add(clearB);
        pauseB.setEnabled(false);
        buttonPanel.add(pauseB);
        buttonPanel.add(startB);

        //speedPanel to hold slider to adjust the time interval
        JPanel speedPanel = new JPanel();
        JLabel speedText = new JLabel("Set Speed:");
        generationS.setMajorTickSpacing(speedMajorTicks);
        generationS.setMinorTickSpacing(speedMinorTicks);
        generationS.setPaintTicks(true);
        // the labels for the Slider
        Hashtable<Integer, JLabel> speedLabel = new Hashtable<Integer, JLabel>();
        for(int i = 0; i <= maxSpeed; i++) {
                speedLabel.put( new Integer( i * speedMajorTicks ), new JLabel("" + i) );
        }
        generationS.setLabelTable(speedLabel);
        generationS.setPaintLabels(true);

        generationLabel.setHorizontalAlignment(SwingConstants.CENTER);

        speedPanel.add(speedText);
        speedPanel.add(generationS);

        panelBottom.add(buttonPanel);
        panelBottom.add(speedPanel);
        panelBottom.add(generationLabel);

        // add bottom panel to the JFrame
        add(panelBottom, BorderLayout.SOUTH);

        // put the frame on
        setLocation(20, 20);
        pack();
        setVisible(true);
    }

        //Action to take dependent on the action referenced by the JButton and Timer
        public void startPauseClear(ActionEvent e) {
                //Get action reference
                Object o = e.getSource();

                //Action reference is to clear
                if(o == clearB) {
                        timer.stop();   //Stop the timer
                        runStatus = false;  //Set game as not running
                        pauseB.setEnabled(false);   //Disable the pause button
                        startB.setEnabled(true);    //Enable the start button
                        //Remove/Clear all cells from the cellHouse
                        for(int r = 1; r < cellHouse.length -1; r++) {
                                for(int c = 1; c < cellHouse[r].length -1; c++) {
                                        cellHouse[r][c].clear();
                                }
                        }
                        //Reset the generation count
                        generationCount = 0;
                        generationLabel.setText("Generation: 0");
                        return;
                }
                //Action reference is to pause
                if(o == pauseB) {
                        timer.stop();   //Stop the timer
                        runStatus = false;  //Set game as not running
                        pauseB.setEnabled(false);   //Disable the pause button
                        startB.setEnabled(true);    //Enable the start button
                        return;
                }
                //Action reference is to start
                if(o == startB) {
                        pauseB.setEnabled(true);    //Enable the pause button
                        startB.setEnabled(false);   //Disable the start button
                        runStatus = true;   //Set game as running
                        timer.setDelay(maxSpeed - generationS.getValue());  //Adjust the speed
                        timer.start();
                        return;
                }

                //If the action is set by timer, set speed
                timer.setDelay(maxSpeed - generationS.getValue());

                //If the game is not running, exit and do nothing more
                if(!runStatus) return;

                //Update generation count and display
                ++generationCount;
                generationLabel.setText("Generation: " + generationCount);

                //Check to see if the cell should be buried
                for(int r = 0; r < cellHouse.length; r++) {
                        for(int c = 0; c < cellHouse[r].length; c++) {
                                cellHouse[r][c].checkGeneration();
                        }
                }

                //Update to the next generation
                for(int r = 0; r < cellHouse.length; r++) {
                        for(int c = 0; c < cellHouse[r].length; c++) {
                                cellHouse[r][c].updateGeneration();
                        }
                }
    }
    public void addActionListener(ActionListener e) {
        clearB.addActionListener(e);
        pauseB.addActionListener(e);
        startB.addActionListener(e);
        timer = new Timer(maxSpeed - generationS.getValue(), e);
    }

}

Controller

package lifepreparation;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class LifeController {
    //Run App
    LifeModel model;
    LifeView view;

    //Constructor
    public LifeController(LifeModel model, LifeView view) {
        this.model = model;
        this.view = view;

        //Add Listeners
        view.addActionListener(new LifeActionListener());
        view.addMouseListener(new LifeMouseListener());
    }

    class LifeActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            view.startPauseClear(e);
        }
    }

    class LifeMouseListener implements MouseListener {
        public void mouseClicked(MouseEvent arg0) {
            model.unselectCell();
        }

        //If the mouse is in a cellHouse while being pressed, cell becomes alive
        public void mouseEntered(MouseEvent arg0) {
            model.selectCells();
        }

        public void mouseExited(MouseEvent arg0) {

        }

        //If the mouse is clicked on a cellHouse, cell comes to life
        public void mousePressed(MouseEvent arg0) {
            model.selectACell();
        }

        //Set mouse as not being held anymore
        public void mouseReleased(MouseEvent arg0) {
            model.setMouseHold();
        }
    }
}

Model

package lifepreparation;

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

//LifeModel to handle cell life and death algorithm
public class LifeModel extends JLabel {
    //Cell Color: cell[0] = dead cell, cell[1] = live cell.
    private static final Color[] color = {Color.LIGHT_GRAY, Color.GREEN};

    //Size of cells
    private static final int cellSize = 15;
    private static final Dimension citySize = new Dimension(cellSize, cellSize);

    //checks if the mouse is still pressed or not
    private boolean mouseHold = false;

    private int currentStatus, newStatus;
    private int nbNeighbor;
    private LifeModel[] Neighbor = new LifeModel[8];

    LifeModel() {
            currentStatus = newStatus = 0;   //Currently Dead
            setOpaque(true);    //Show color
            setBackground(color[0]);    //Light Gray color
            this.setPreferredSize(citySize);   //Set the dimension of the board
    }
    //Add a neighbor
    void addNeighbor(LifeModel n) {
            Neighbor[nbNeighbor++] = n;
    }

    //Check to see if a cell should live or not
    void checkGeneration() {
            //Number of neighbors that are alive
            int nbAlive = 0;

            //Check the status of the neighbors
            for(int i = 0; i < nbNeighbor; i++)
                    nbAlive += Neighbor[i].currentStatus;

            //If status of cell is alive
            if(currentStatus == 1) {
                    //Bury cell if it has less than two neighbors
                    if(nbAlive < 2)
                            newStatus = 0;
                    //Bury cell if it has more than three live neighbors
                    if(nbAlive > 3)
                            newStatus = 0;
            }
            else {
                    //Dead cells with three live neighbors get reborn
                    if(nbAlive == 3)
                            newStatus = 1;
            }
    }
    //Switch to next generation
    void updateGeneration() {
            if(currentStatus != newStatus) {    //Adjust color for the new generation
                    currentStatus = newStatus;
                    setBackground(color[currentStatus]);
            }
    }

    //Bury all cells in the city
    void clear() {
            if(currentStatus == 1 || newStatus == 1) {
                    currentStatus = newStatus = 0;
                    setBackground(color[currentStatus]);
            }
    }

    public void unselectCell() {
            if(currentStatus == 1 || newStatus == 1) {
                    currentStatus = newStatus = 0;
                    setBackground(color[currentStatus]);
            }
    }

    //If the mouse is in a cellHouse while being pressed, cell becomes alive
    public void selectCells() {
            if(mouseHold) {
                    currentStatus = newStatus = 1;
                    setBackground(color[1]);
            }
    }

    //If the mouse is clicked on a cellHouse, cell comes to life
    public void selectACell() {
            mouseHold = true;
            currentStatus = newStatus = 1;
            setBackground(color[1]);
    }

    //Set mouse as not being held anymore
    public void setMouseHold() {
            mouseHold = false;
    }

}

Program without MVC implementation

package lifepreparation;

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

public class LifeView extends JFrame implements ActionListener {

    //Cell Color: cell[0] = dead cell, cell[1] = live cell.
    private static final Color[] color = {Color.LIGHT_GRAY, Color.GREEN};

    //Size of cells
    private static final int cellSize = 15;
    private static final Dimension citySize = new Dimension(cellSize, cellSize);

    //Label used to house cells
    private LifeLabel[][] cellHouse;

    //Timer used to fire the next generation
    private Timer timer;

    //Generation counter - used to count the number of generations
    private int generationCount = 0;
    private JLabel generationLabel = new JLabel("Generation: 0");

    //Declare default buttons
    private JButton startB = new JButton("Start");
    private JButton pauseB = new JButton("Pause");
    private JButton clearB = new JButton("Clear");

    //Slider to adjust the time interval between generations
    private static final int minSpeed = 0;
    private static final int maxSpeed = 1000;
    private static final int speedMajorTicks = (maxSpeed-minSpeed)/5;
    private static final int speedMinorTicks = (maxSpeed-minSpeed)/20;
    JSlider generationS = new JSlider(minSpeed,maxSpeed);

    //Identifies game status: false=pause, true=running
    private boolean runStatus = false;

    // if the mouse is down or not
    private boolean mouseHold = false;

    public LifeView(int boardRow, int boardCol) {
        super("Game Of Life");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //**START Create labels to house cells, +2 more to calculate cells that are out of bounds
        cellHouse = new LifeLabel[boardRow+2][boardCol+2];
        for(int r = 0; r < boardRow+2; r++) {
            for(int c = 0; c < boardCol+2; c++) {
                cellHouse[r][c] = new LifeLabel();
            }
    }
        //--END Create Labels

        //Panel to hold cell houses
        JPanel panel = new JPanel(new GridLayout(boardRow, boardCol, 1, 1));
        panel.setBackground(Color.BLACK);
        panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        //Add cellHouses to the panel
        for(int r = 1; r < boardRow+1; r++) {
                for(int c = 1; c < boardCol+1; c++) {
                        panel.add(cellHouse[r][c]);
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c]);    //Add to TOP ^
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c]);    //Add to BOTTOM _
                        cellHouse[r][c].addNeighbor(cellHouse[r][c-1]);    //Add to left <-
                        cellHouse[r][c].addNeighbor(cellHouse[r][c+1]);    //Add to right ->
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c-1]);  //Add to top left ^<-
                        cellHouse[r][c].addNeighbor(cellHouse[r-1][c+1]);  //Add to top right ^->
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c-1]);  //Add to bottom left _<-
                        cellHouse[r][c].addNeighbor(cellHouse[r+1][c+1]);  //Add to bottom right _->
                }
        }

        //Panel with cellHouses added to the container
        add(panel, BorderLayout.CENTER);

        //South Panel to hold buttons and widgets with extra features
        JPanel panelBottom = new JPanel();

        //buttonPanel to hold start, pause, clear features
        JPanel buttonPanel = new JPanel();
        clearB.addActionListener(this);
        buttonPanel.add(clearB);
        pauseB.addActionListener(this);
        pauseB.setEnabled(false);
        buttonPanel.add(pauseB);
        startB.addActionListener(this);
        buttonPanel.add(startB);

        //speedPanel to hold slider to adjust the time interval
        JPanel speedPanel = new JPanel();
        JLabel speedText = new JLabel("Set Speed:");
        generationS.setMajorTickSpacing(speedMajorTicks);
        generationS.setMinorTickSpacing(speedMinorTicks);
        generationS.setPaintTicks(true);
        // the labels for the Slider
        Hashtable<Integer, JLabel> speedLabel = new Hashtable<Integer, JLabel>();
        for(int i = 0; i <= maxSpeed; i++) {
                speedLabel.put( new Integer( i * speedMajorTicks ), new JLabel("" + i) );
        }
        generationS.setLabelTable(speedLabel);
        generationS.setPaintLabels(true);

        generationLabel.setHorizontalAlignment(SwingConstants.CENTER);

        speedPanel.add(speedText);
        speedPanel.add(generationS);

        panelBottom.add(buttonPanel);
        panelBottom.add(speedPanel);
        panelBottom.add(generationLabel);

        // add bottom panel to the JFrame
        add(panelBottom, BorderLayout.SOUTH);

        // put the frame on
        setLocation(20, 20);
        pack();
        setVisible(true);
        // start the thread that run the cycles of life
        timer = new Timer(maxSpeed - generationS.getValue(), this);
    }

    //Action to take dependent on the action referenced by the JButton and Timer
    public void actionPerformed(ActionEvent e) {
        //Get action reference
        Object o = e.getSource();

                //Action reference is to clear
        if(o == clearB) {
            timer.stop();   //Stop the timer
            runStatus = false;  //Set game as not running
            pauseB.setEnabled(false);   //Disable the pause button
            startB.setEnabled(true);    //Enable the start button
            //Remove/Clear all cells from the cellHouse
            for(int r = 1; r < cellHouse.length -1; r++) {
                for(int c = 1; c < cellHouse[r].length -1; c++) {
                    cellHouse[r][c].clear();
                }
            }
            //Reset the generation count
            generationCount = 0;
            generationLabel.setText("Generation: 0");
            return;
        }
        //Action reference is to pause
        if(o == pauseB) {
            timer.stop();   //Stop the timer
            runStatus = false;  //Set game as not running
            pauseB.setEnabled(false);   //Disable the pause button
            startB.setEnabled(true);    //Enable the start button
            return;
        }
        //Action reference is to start
        if(o == startB) {
            pauseB.setEnabled(true);    //Enable the pause button
            startB.setEnabled(false);   //Disable the start button
            runStatus = true;   //Set game as running
            timer.setDelay(maxSpeed - generationS.getValue());  //Adjust the speed
            timer.start();
            return;
        }

        //If the action is set by timer, set speed
        timer.setDelay(maxSpeed - generationS.getValue());

        //If the game is not running, exit and do nothing more
        if(!runStatus) return;

                //Update generation count and display
                ++generationCount;
        generationLabel.setText("Generation: " + generationCount);

                //Check to see if the cell should be buried
        for(int r = 0; r < cellHouse.length; r++) {
            for(int c = 0; c < cellHouse[r].length; c++) {
                cellHouse[r][c].checkGeneration();
            }
        }

                //Update to the next generation
        for(int r = 0; r < cellHouse.length; r++) {
            for(int c = 0; c < cellHouse[r].length; c++) {
                cellHouse[r][c].updateGeneration();
            }
        }
    }
     //Run App
    public static void main(String[] arg) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new LifeView(30, 50);
            }
        });
    }

    //LifeModel to handle cell life and death algorithm
    class LifeLabel extends JLabel implements MouseListener {
        private int currentGen, newGen;
        private int nbNeighbor;
        private LifeLabel[] Neighbor = new LifeLabel[8];

        LifeLabel() {
            currentGen = newGen = 0;   //Currently Dead
            setOpaque(true);    //Show color
            setBackground(color[0]);    //Light Gray color
            addMouseListener(this); //Add mouseListener
            this.setPreferredSize(citySize);   //Set the dimension of the board
        }
        //Add a neighbor
        void addNeighbor(LifeLabel n) {
            Neighbor[nbNeighbor++] = n;
        }

        //Check to see if a cell should live or not
        void checkGeneration() {
            //Number of neighbors that are alive
            int nbAlive = 0;

            //Check the status of the neighbors
            for(int i = 0; i < nbNeighbor; i++)
                nbAlive += Neighbor[i].currentGen;

                        //If status of cell is alive
            if(currentGen == 1) {
                                //Bury cell if it has less than two neighbors
                if(nbAlive < 2)
                    newGen = 0;
                                //Bury cell if it has more than three live neighbors
                if(nbAlive > 3)
                    newGen = 0;
            }
            else {
                                //Dead cells with three live neighbors get reborn
                if(nbAlive == 3)
                    newGen = 1;
            }
        }
        //Switch to next generation
        void updateGeneration() {
            if(currentGen != newGen) {  //Adjust color for the new generation
                currentGen = newGen;
                setBackground(color[currentGen]);
            }
        }

        //Bury all cells in the city
        void clear() {
            if(currentGen == 1 || newGen == 1) {
                currentGen = newGen = 0;
                setBackground(color[currentGen]);
            }
        }

        public void mouseClicked(MouseEvent arg0) {
                        if(currentGen == 1 || newGen == 1) {
                currentGen = newGen = 0;
                setBackground(color[currentGen]);
            }
        }

        //If the mouse is in a cellHouse while being pressed, cell becomes alive
        public void mouseEntered(MouseEvent arg0) {
            if(mouseHold) {
                currentGen = newGen = 1;
                setBackground(color[1]);
            }
        }

        public void mouseExited(MouseEvent arg0) {

        }

        //If the mouse is clicked on a cellHouse, cell comes to life
        public void mousePressed(MouseEvent arg0) {
            mouseHold = true;
            currentGen = newGen = 1;
            setBackground(color[1]);
        }

        //Set mouse as not being held anymore
        public void mouseReleased(MouseEvent arg0) {
            mouseHold = false;
        }
    }
}

Body:
Your code it too hard to follow, but I have done an application using mvc in swing.

My advice is to have something like this in a Main class:

    MainModel      model      = new MainModel();
    MainView       view       = new MainView(model);
    MainController controller = new MainController(model, view);

Your controller is ok.

The view looks ok, but you should have separate addActionListener methods for clearB, startB, pauseB (perhaps that's the problem).

The model is where the brain should be. Do not extend JLabel, doesn't make sense at all.

Hope this helps.


来源: stackexchange

问:
How do I restart an android emulator?
I'm basically trying to do this:
Changing the Android emulator locale automatically

Everything works up until 'start'.  the emulator starts to boot but keeps loading at the shimmering 'ANDROID' screen forever.  I must be missing something...  How can I restart the emulator from ADB?

Okay, I should be more specific.

I am trying to do this from the command line using adb.  I can use adb to setprop and I can stop the emulator. When I try doing 'start' in the adb shell, the emulator does begin to boot, but it never returns to the lock screen.

答:
In Android Studio go to:

Tools > Android > AVD Manager

Select your emulator device

Click "Cold boot now" to restart, or "Wipe data" to factory reset

ContentLicense: CC BY-SA 3.0

Title: How do I restart an android emulator?

ContentLicense: CC BY-SA 4.0


问:
First available date previous day/month/year from a datetime range
I have a datetime instance with dates (dfDates):

```<code>2017-03-01 00:00
2017-03-02 00:00
2017-03-04 00:00
...
</code>```

For the last day (here: 2017-03-04) I calculate the previous day/month/year/etc. as follows:

```<code>def previous_day(dtToday):
    return dtToday - pd.DateOffset(days=1)
</code>```

This returns 2017-03-03. However, this business day is not available in my range of dates (dfDates).

I am therefore looking for a robust way to find the date that is the closest to the previous day/month/year/etc.. In this case for the previous day it should return 2017-03-02.

Note, I understand that you can do something like index -1 to get the previous day. It becomes however complicated when taking the previous month (there are not always 30 days in a month) and even the previous year (there are not always 252 working days in a year). Is there therefore a robust method to get the closest available date?

Update

I understand also that you can use timedelta as follows:

```<code>from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)
</code>```

However, how does that relate to dtToday and how can I link it with dfDates? dtToday in my case is not always datetime.today(). Sometimes its a random date.

答:
Not the most efficient, but you can try:

```<code># From your function
day_minus_one = previous_day(dtToday)

# Return LAST element in INDEX of DF FROM START TO DAY_MINUS_ONE
actual = df.loc[:day_minus_one].index[-1]
</code>```

This essentially returns you the last index of a copy of your df, up to and including day_minus_one, if any of the dates exist. This should give you the closest date, or the date itself.

You can try:

```<code># Returns LAST element of INDEX of df from DAY_MINUS_ONE_HUNDRED to DAY_MINUS_ONE
actual_better = df.loc[day_minus_one_hundred:day_minus_one].index[-1]
</code>```

To only look back one_hundred days from minus_one if your dataset is huge, so you don't have to return a huge array just to find one date.

Body:
I have a datetime instance with dates (dfDates):

2017-03-01 00:00
2017-03-02 00:00
2017-03-04 00:00
...

For the last day (here: 2017-03-04) I calculate the previous day/month/year/etc. as follows:

def previous_day(dtToday):
    return dtToday - pd.DateOffset(days=1)

This returns 2017-03-03. However, this business day is not available in my range of dates (dfDates).

I am therefore looking for a robust way to find the date that is the closest to the previous day/month/year/etc.. In this case for the previous day it should return 2017-03-02.

Note, I understand that you can do something like index -1 to get the previous day. It becomes however complicated when taking the previous month (there are not always 30 days in a month) and even the previous year (there are not always 252 working days in a year). Is there therefore a robust method to get the closest available date?

Update

I understand also that you can use timedelta as follows:

from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=days_to_subtract)

However, how does that relate to dtToday and how can I link it with dfDates? dtToday in my case is not always datetime.today(). Sometimes its a random date.

Body:
Not the most efficient, but you can try:

# From your function
day_minus_one = previous_day(dtToday)

# Return LAST element in INDEX of DF FROM START TO DAY_MINUS_ONE
actual = df.loc[:day_minus_one].index[-1]

This essentially returns you the last index of a copy of your df, up to and including day_minus_one, if any of the dates exist. This should give you the closest date, or the date itself.

You can try:

# Returns LAST element of INDEX of df from DAY_MINUS_ONE_HUNDRED to DAY_MINUS_ONE
actual_better = df.loc[day_minus_one_hundred:day_minus_one].index[-1]

To only look back one_hundred days from minus_one if your dataset is huge, so you don't have to return a huge array just to find one date.


问:
what is the relationship of babel polyfill and runtime?

Babel includes a polyfill that includes a custom regenerator runtime
  and core-js.

Another purpose of this transformer is to create a sandboxed
  environment for your code. If you use babel-polyfill and the built-ins
  it provides such as Promise, Set and Map

According to the documentation,I have think about these information and get the follow points:

polyfill is included in babel,so if we use babel-loader,polyfill will be automatically contained in the transpiled result.

babel-plugin-transform-runtime will only alias the name of the important classes,itself does not contain any polyfill or runtime.

if you don't use babel-plugin-transform-runtime,the polifill will also be contained in the transpiled result,but without being aliased.

Am I right?

答:
babel-polyfill is not included when you use babel-loader:
  babel-loader's role is to tell webpack how to transform the source files.
  If you want to use babel-polyfill:
    first, install it by running npm install --save babel-polyfill
    second, require or import it in the top of your entry file import 'babel-polyfill'

babel-plugin-transform-runtime should be used only when developing a library because babel-polyfill modifies the globals: for example when you use babel-polyfill the global window.Object will contain properties like assign, and new APIs like Promise, Set, Map will be available as globals if your browser does not support them, otherwise you should use the babel-polyfill.


问:
Internet Explorer 6 - DIV problems
I have a website setup with DIV managed layout. The problem is that under IE 6 this layout breaks.

This is the CSS:

```<code>#bg{
        position:fixed;
        top:0;
        left:0;

        /* Preserve aspect ratio */
        min-width:100%;
        min-height:100%;
}
#basic {
    width: 902px; height:  auto; margin-left: auto; margin-right: auto; position:  relative; padding-bottom: 50px;
}
#logo{
    width: 902px; height: 400px; position: absolute; top: 17px;
}
#navbar{
    width: 902px; height: 23px; top: 280px; position:absolute;
}

#content{
    width: 802px; height: auto; top: 325px; position: absolute; background-color: white; padding-top: 50px;padding-left: 50px; padding-right: 50px; padding-bottom: 50px
}
#csob{
    width: 100px; height:100px; bottom:0px; right: 0px; position: absolute;
}
#titulni_strana {width:902; height:auto; top:325px; position:absolute}
</code>```

PHP:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="shortcut icon" href="http://protechp.cz/zimnihrycsob/images/favicon.ico">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<link href="default.css" rel="stylesheet" type="text/css" >
<title>Zimni Hry CSOB</title>
<!--[if lt IE 7]>
        <script type="text/javascript" src="unitpngfix.js"></script>
<![endif]-->
</head>

<body>
<img src="images/background-gradient-ok.jpg" id="bg" alt="pozadi">
<div id="basic">

<div id="logo">
<center><img src="images/logo3.png" alt="logo"></center>
</div>

<?php include ("./menu.php") ?>

<div id="titulni_strana">
<img src="images/titulni_strana.jpg" alt="titulni strana">
</div>

</div>

</body>
</html>
</code>```

答:
It seems the problem is with the image not loading and not the css.

Try removing the style sheet, all css, and the ie6 png fix javascript just to confirm your image is making it to the page as it doesnt look like a css problem to me. A live example would be nice.

Title: Internet Explorer 6 - DIV problems

Body:
I have a website setup with DIV managed layout. The problem is that under IE 6 this layout breaks.

This is the CSS:

#bg{
        position:fixed;
        top:0;
        left:0;

        /* Preserve aspect ratio */
        min-width:100%;
        min-height:100%;
}
#basic {
    width: 902px; height:  auto; margin-left: auto; margin-right: auto; position:  relative; padding-bottom: 50px;
}
#logo{
    width: 902px; height: 400px; position: absolute; top: 17px;
}
#navbar{
    width: 902px; height: 23px; top: 280px; position:absolute;
}

#content{
    width: 802px; height: auto; top: 325px; position: absolute; background-color: white; padding-top: 50px;padding-left: 50px; padding-right: 50px; padding-bottom: 50px
}
#csob{
    width: 100px; height:100px; bottom:0px; right: 0px; position: absolute;
}
#titulni_strana {width:902; height:auto; top:325px; position:absolute}

PHP:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<link rel="shortcut icon" href="http://protechp.cz/zimnihrycsob/images/favicon.ico">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<link href="default.css" rel="stylesheet" type="text/css" >
<title>Zimni Hry CSOB</title>

<?php include ("./menu.php") ?>


问:
Regex for substring of string in quotes
I want to match the word / substring CODE as part of string in quotes. Example:

```<code>text "bla CODE bla" text <- match 'CODE'
text "MYCODE" text <- match 'CODE'
"test_CODE_bla" text <- match 'CODE'
text CODE "text" <- no match
</code>```

But (?<=")(.*)CODE(.*)(?=") matches the whole string in quotes, not just the word CODE.
But something like (?<=".*)CODE(?=.*") does not work. Where's my mistake?
I'm using Notepad++ Search&Replace with Boost RegEx (kinda similar to Perl Syntax!?).

Link: https://regex101.com/r/zkfRMC/1

Any help is appreciated.

答:
It's one quoted string per line and no nested quotation marks.

You may use

```<code>"[^"\n]*\KCODE(?=[^"\n]*")
</code>```

or even

```<code>".*?\KCODE(?=.*")
</code>```

See the regex demo

Details:

" - a literal double quote

[^"\n]* - 0+ chars other than " and LF

\K - match reset operator discarding all the text matched so far

CODE - your required substring

(?=[^"\n]*") - there must be 0+ chars other than " and LF and then " immediately after the current position.

Title: Regex for substring of string in quotes

Body:
I want to match the word / substring CODE as part of string in quotes. Example:

text "bla CODE bla" text <- match 'CODE'
text "MYCODE" text <- match 'CODE'
"test_CODE_bla" text <- match 'CODE'
text CODE "text" <- no match

But (?<=")(.*)CODE(.*)(?=") matches the whole string in quotes, not just the word CODE.
But something like (?<=".*)CODE(?=.*") does not work. Where's my mistake?
I'm using Notepad++ Search&Replace with Boost RegEx (kinda similar to Perl Syntax!?).

Link: https://regex101.com/r/zkfRMC/1

Any help is appreciated.

Body:
It's one quoted string per line and no nested quotation marks.

You may use

"[^"\n]*\KCODE(?=[^"\n]*")

or even

".*?\KCODE(?=.*")

See the regex demo

Details:

" - a literal double quote

[^"\n]* - 0+ chars other than " and LF

\K - match reset operator discarding all the text matched so far

CODE - your required substring

(?=[^"\n]*") - there must be 0+ chars other than " and LF and then " immediately after the current position.


问:
if with AND Operator in java
I have a block of code which uses if statement with AND operator:

```<code>final String NODE_TYPE_LIST = "List";
final String NODE_TYPE_DETAIL = "Detail";
if ((!NODE_TYPE_LIST.equalsIgnoreCase(dataNodeBean.getType()))
                    && (!NODE_TYPE_DETAIL.equalsIgnoreCase(dataNodeBean.getType()))) {
                throw new InvalidNodeTypeException("Invalid Node type.");
            }
</code>```

For exampled, if dataNodeBean.getType() returns "List".
According to this link, above code should throw InvalidNodeTypeException only if both expressions in if statement returns true. But when i'm debugging the program( where dataNodeBean.getType() returns "List" ) i see both expressions being evaluated even though the first expression returns false, as a result the InvalidNodeTypeException(Custom Exception) is thrown.
What i expect from this code is to throw an exception when the dataNodeBean.getType() doesn't returns either List or Detail.
I don't understand what i'm doing wrong here.

答:
Your code is perfectly fine. I ran the following test:

```<code>public static void main(String[] args) {
    System.out.println(test("A"));
    System.out.println(test("B"));
    System.out.println(test("C"));
}

private static boolean test(String value) {
    return (!"a".equalsIgnoreCase(value)) && (!"b".equalsIgnoreCase(value));
}
</code>```

And it returned

```<code>false
false
true
</code>```

Just as you'd expect. I suspect the issue is in the getType method. An easy way to confirm is to move your check to a separate method that is passed the result of getType and then write some unit test confirming that it returns true for anything other than "list" or "detail".

Title: if with AND Operator in java

Body:
I have a block of code which uses if statement with AND operator:

final String NODE_TYPE_LIST = "List";
final String NODE_TYPE_DETAIL = "Detail";
if ((!NODE_TYPE_LIST.equalsIgnoreCase(dataNodeBean.getType()))
                    && (!NODE_TYPE_DETAIL.equalsIgnoreCase(dataNodeBean.getType()))) {
                throw new InvalidNodeTypeException("Invalid Node type.");
            }

For exampled, if dataNodeBean.getType() returns "List".
According to this link, above code should throw InvalidNodeTypeException only if both expressions in if statement returns true. But when i'm debugging the program( where dataNodeBean.getType() returns "List" ) i see both expressions being evaluated even though the first expression returns false, as a result the InvalidNodeTypeException(Custom Exception) is thrown.
What i expect from this code is to throw an exception when the dataNodeBean.getType() doesn't returns either List or Detail.
I don't understand what i'm doing wrong here.

Body:
Your code is perfectly fine. I ran the following test:

public static void main(String[] args) {
    System.out.println(test("A"));
    System.out.println(test("B"));
    System.out.println(test("C"));
}

private static boolean test(String value) {
    return (!"a".equalsIgnoreCase(value)) && (!"b".equalsIgnoreCase(value));
}

And it returned

false
false
true

Just as you'd expect. I suspect the issue is in the getType method. An easy way to confirm is to move your check to a separate method that is passed the result of getType and then write some unit test confirming that it returns true for anything other than "list" or "detail".


问:
how to call a php function when we open the page
```<code>/*the function which fetches data from database */public function allClients()
{
    try
    {
        $stmt = $this->conn->query("SELECT * FROM client");
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $results;
    }
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}
</code>```

This is the next page where the function is called.I have used a fetch button:'btn-signup' but I want to display this data in a table without using any button how do I do that.

```<code>$client2 = new client2();
if (isset($_POST['btn-signup']))
{
    try
    {
            $results=$client2->allClients();

            foreach(array ($results) as $row)
        {

            $id = $row['id'];
            $name = $row['name'];
            $email = $row['email'];
            echo $id."\t\t";
            echo $name."\t\t";
            echo $email;
            echo "\n\n";

        }

    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }

}
</code>```

The table in which i need to fetch the values.THANK you

```<code><table id="data-table-command" class="table table-striped table-vmiddle">
                            <thead>
                                <tr>
                                    <th data-column-id="id" data-type="numeric">ID</th>
                                    <th data-column-id="sender">Sender</th>
                                    <th data-column-id="received" data-order="desc">Received</th>
                                    <th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
                                </tr>
                            </thead>
                            <tbody>
                                                        <tr>
                                    <td>10238</td>
                                    <td>eduardo@pingpong.com</td>
                                    <td>14.10.2013</td>
                                </tr>
                                <tr>
                                    <td>10243</td>
                                    <td>eduardo@pingpong.com</td>
                                    <td>19.10.2013</td>
                                </tr></tr>
                            </tbody>
                        </table>
</code>```

答:
The problem was with the function,this is the correct code.It's now working perfectly

```<code>public function allClients()//function
    {
        try
        {
            $stmt = $this->conn->query("SELECT * FROM client");
            $stmt->execute();
            $results = $stmt->setFetchMode(PDO::FETCH_ASSOC);
            return $stmt;

        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }
</code>```

Function call

```<code> <table id="data-table-command" class="table table-striped table-vmiddle">
                         <thead>
                            <tr>
                                <th data-column-id="id" data-type="numeric">ID</th>
                                <th data-column-id="sender">Sender</th>
                                <th data-column-id="received" data-order="desc">Received</th>
                                <th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php

                            $results=$client2->allClients();

                            foreach($results as $row){
                                echo "<tr><td>".$row['id']."</td>";
                                echo "<td>".$row['name']."</td>";
                                echo "<td>".$row['username']."</td>";
                                echo "<td>".$row['whatphn']."</td>";
                            //  echo "<td>".$row['email']."</td></tr>";

                            }
                        ?>
                        </tbody>
                    </table>
</code>```

Body:
/*the function which fetches data from database */public function allClients()
{
    try
    {
        $stmt = $this->conn->query("SELECT * FROM client");
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $results;
    }
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}

This is the next page where the function is called.I have used a fetch button:'btn-signup' but I want to display this data in a table without using any button how do I do that.

$client2 = new client2();
if (isset($_POST['btn-signup']))
{
    try
    {
            $results=$client2->allClients();

            foreach(array ($results) as $row)
        {

            $id = $row['id'];
            $name = $row['name'];
            $email = $row['email'];
            echo $id."\t\t";
            echo $name."\t\t";
            echo $email;
            echo "\n\n";

        }

    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }

}

The table in which i need to fetch the values.THANK you

                                    ID
                                    Sender
                                    Received
                                    Commands

                                    10238
                                    eduardo@pingpong.com
                                    14.10.2013

                                    10243
                                    eduardo@pingpong.com
                                    19.10.2013

Body:
The problem was with the function,this is the correct code.It's now working perfectly

public function allClients()//function
    {
        try
        {
            $stmt = $this->conn->query("SELECT * FROM client");
            $stmt->execute();
            $results = $stmt->setFetchMode(PDO::FETCH_ASSOC);
            return $stmt;

        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }

Function call

 <table id="data-table-command" class="table table-striped table-vmiddle">
                         <thead>
                            <tr>
                                <th data-column-id="id" data-type="numeric">ID</th>
                                <th data-column-id="sender">Sender</th>
                                <th data-column-id="received" data-order="desc">Received</th>
                                <th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php

                            $results=$client2->allClients();

                            foreach($results as $row){
                                echo "<tr><td>".$row['id']."</td>";
                                echo "<td>".$row['name']."</td>";
                                echo "<td>".$row['username']."</td>";
                                echo "<td>".$row['whatphn']."</td>";
                            //  echo "<td>".$row['email']."</td></tr>";

                            }
                        ?>
                        </tbody>
                    </table>


问:
Bootstrap 3: Table inside a
, but rendered outside
I'm using Bootstrap 3 in a layout of an e-Commerce website. It happens that I put a

```<code><table class="table">
</code>```

inside a

```<code><div class="well">
</code>```

in my code, but it renders out of the well, according to this image.

Has someone here faced this problem? I looked Bootstrap 3 documentation, but there is not even a clue about it.

答:
You can also remove/change the css of the table: "table-layout: fixed;"

```

Title: Bootstrap 3: Table inside a <div class="well">, but rendered outside

Body:
I'm using Bootstrap 3 in a layout of an e-Commerce website. It happens that I put a

inside a

in my code, but it renders out of the well, according to this image.

Has someone here faced this problem? I looked Bootstrap 3 documentation, but there is not even a clue about it.

Body:
You can also remove/change the css of the table: "table-layout: fixed;"

<table class="table" style="table-layout: unset">


问:
Suggestion on File I/O opertion with 1024 bytes chunks
Hi I am a ruby on rails developer can any body help me in doing File I/O operation with 1024 bytes chunk at a time.</p>

答:
http://ruby-doc.org/core/classes/IO.html#M002270 :</p>

```<code>f = File.new("testfile")
f.read(1024)
</code>```

Body:
http://ruby-doc.org/core/classes/IO.html#M002270 :

f = File.new("testfile")
f.read(1024)


问:
Passing parameters with dropdown on AngularJS
I'm trying list data according with data choose on a drop down menu.

My service list data with a hardcode (id 6).

```<code>    var url = 'http://localhost:3854/listarServicosByEstab/' + '6'; // Hardcode!
</code>```

How do I pass the select item ID to the service?

Dropdown HTML (ng-click doesnt work):

```<code>         <!-- Combobox -->
        <div class="row">
            <div class="dropdown" ng-controller="EstabelecimentosPageCtrl">
                <button class="btn btn-default dropdown-toggle" type="button" id="dropdown_estabelecimentos" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                    Estabelecimentos
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu" aria-labelledby="dropdown_estabelecimentos" >
                    <li>
                        <a ng-repeat="estab in listaDeEstabelecimentos" href="#" ng-click="$parent.current = item">
                            {{estab.nomeEstab}}
                        </a>
                    </li>
                </ul>
                Choose Test: {{item}}
            </div>
        </div>
</code>```

Menu Controller:

```<code>.controller('ListServicoCtrl', function($scope, $state, ListServicoService) {
ListServicoService.listarServicos().then(function(dados){
    $scope.listaDeServicos = dados;
});  });
</code>```

Service:

```<code>.service('ListServicoService', function($http){

var url = 'http://localhost:3854/listarServicosByEstab/' + '6'; // Hardcode!

return{
  listarServicos : function (){
      return $http.get(url).then(function(response){
          return response.data;
        });
  }
}});
</code>```

答:
```<code> <div class="row">
            <div class="dropdown" ng-controller="EstabelecimentosPageCtrl">
                <button class="btn btn-default dropdown-toggle" type="button" id="dropdown_estabelecimentos" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                    Estabelecimentos
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu" aria-labelledby="dropdown_estabelecimentos" >
                    <li>
                        <a ng-repeat="estab in listaDeEstabelecimentos"   ng-click="passdata(estab.Id)">
                            {{estab.nomeEstab}}
                        </a>
                    </li>
                </ul>
                Choose Test: {{item}}
            </div>
        </div>
</code>```

Your Controller

```<code>.controller('ListServicoCtrl', function($scope, $state, ListServicoService) {

$scope.passdata = function(id){
ListServicoService.listarServicos(id).then(function(dados){
    $scope.listaDeServicos = dados;
});
} });
</code>```

Your Service

```<code>.service('ListServicoService', function($http){

return{
  listarServicos : function (id){
      return $http.get('http://localhost:3854/listarServicosByEstab/' + id).then(function(response){
          return response.data;
        });
  }
}});
</code>```

Remove href from anchor tag and make a function like I have shown in controller. By assuming that your json contains value like Id I have demonstrated it. Hope this code will work for you.

Body:
I'm trying list data according with data choose on a drop down menu.

My service list data with a hardcode (id 6).

    var url = 'http://localhost:3854/listarServicosByEstab/' + '6'; // Hardcode!

How do I pass the select item ID to the service?

Dropdown HTML (ng-click doesnt work):

                <button class="btn btn-default dropdown-toggle" type="button" id="dropdown_estabelecimentos" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                    Estabelecimentos

                </button>

                            {{estab.nomeEstab}}

                Choose Test: {{item}}

Menu Controller:

.controller('ListServicoCtrl', function($scope, $state, ListServicoService) {
ListServicoService.listarServicos().then(function(dados){
    $scope.listaDeServicos = dados;
});  });

Service:

.service('ListServicoService', function($http){

var url = 'http://localhost:3854/listarServicosByEstab/' + '6'; // Hardcode!

return{
  listarServicos : function (){
      return $http.get(url).then(function(response){
          return response.data;
        });
  }
}});

Body:
 <div class="row">
            <div class="dropdown" ng-controller="EstabelecimentosPageCtrl">
                <button class="btn btn-default dropdown-toggle" type="button" id="dropdown_estabelecimentos" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
                    Estabelecimentos
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu" aria-labelledby="dropdown_estabelecimentos" >
                    <li>
                        <a ng-repeat="estab in listaDeEstabelecimentos"   ng-click="passdata(estab.Id)">
                            {{estab.nomeEstab}}
                        </a>
                    </li>
                </ul>
                Choose Test: {{item}}
            </div>
        </div>

Your Controller

.controller('ListServicoCtrl', function($scope, $state, ListServicoService) {

$scope.passdata = function(id){
ListServicoService.listarServicos(id).then(function(dados){
    $scope.listaDeServicos = dados;
});
} });

Your Service

.service('ListServicoService', function($http){

return{
  listarServicos : function (id){
      return $http.get('http://localhost:3854/listarServicosByEstab/' + id).then(function(response){
          return response.data;
        });
  }
}});

Remove href from anchor tag and make a function like I have shown in controller. By assuming that your json contains value like Id I have demonstrated it. Hope this code will work for you.


问:
In Eclipse, the changes of my source code have no effect
I have a strange problem in Eclipse Helios. When I alter my source code, my changes have no effect. Even if I alter the code in a way that looks uncompilable, it still can be run.

It seems that Eclipse keeps its state somewhere in the background while I edit and save my sources and commit them to svn.

I don't know what setting to look up or what else to do. I'd be glad to receive any help.

答:
I was having the same problem while running a Maven project in Spring Tool Suit (which is based on Eclipse). I needed to clean and build the maven project every time to make the STS detect the new changes (what is obviously a slow and inefficient process).

So my solution was:

Pressing Alt+F5 and check Force update of Snapshots/Releases


问:
Django: How to return a user to correct pagination page after editing or updating?
I am editing a content from table which has pagination in it. If i update a user which is at the page no 9 and save that user, it will return me to page no 1.

I want it to return to a same page where user was previously there that is at page no 9.

Any help regarding the same would be appreciated!

答:
You need to pass to the editing page the page number you were on, in a query parameter. And keep track of it and when editing/updating is successful you redirect back to that page number.

In your form include a next field. Where to redirect in case of success.


问:
How to capture an event trigger when a flash movie successfully loaded?
I'm currently using jQuery, as well as swfObject to dynamically embed the swf movie into my web page.

I currently having a problem on embeding immem's music player into my web page, as their embed code doesn't have any loading screen. So, when I replace the element using swfObject, that area will generally blank. In worst case, it means that user won't know that the embed song is loading.

So, I'm trying to find out the way to bind an event after that flash got loaded. Since my plan would be placing image with huge z-index on the top and use this trigger to hide the image. I think I've tried to use $('#embed').load(function(){ ... });, with no luck.

Does somebody have any solution for this? I just wonder if that is possible, since I don't want to get hacking with the flash and try to add 'loader' to the flash file.

Some more note: To make it more clear, I want to embed imeem's music player into my webpage. So, I really don't have any control over the flash file, i.e. I can't create a flash file by myself.

答: You could do this from within the flash movie. However then you will need to have control over the movie (which you may not have).</p>

OwnerDisplayName: Sikachu

LastEditorDisplayName: Sikachu

OwnerDisplayName: Pim Jager


问:
Scroll WKInterfaceController back to top
I'm currently displaying a long label of text plus a button below it to go to the 'next' message.

When the next button is pressed the label adjusts it's height automagically thanks to watch kit's strange auto sizing mechanisms; however the screen does not change positions. I want to scroll the InterfaceController back to the top whenever the label updates. Is this possible with the current Watch Kit SDK?

答:
Currently, there is no API for the interface controller to scroll to top. But I did a workaround for the same.

Add a WKInterfaceTable to the top.

Set the Height of the Row Controllers Group to 2 and set the
background color to black.

Set the number of rows to 1.

Call the below method.

func scrollInterfaceToTop() {
        tableView.setHidden(false)
        tableView.scrollToRow(at: 0)
        tableView.setHidden(true)
}


问:
Use Ajax post call in codeigniter cause Internal Server Error
This is the error message found on google chrome:

POST http://localhost/display/register/registerUser 500 (Internal Server Error)

My project file name is "display".

One controller file named "register" ,it has a function called "registerUser". All it does is getting user's input, and compare it with database to see if the name is used or not, if valid store it into database and give them a success message, if not valid give a error message.

```<code>$username=$this->input->post('name');
    $password=$this->input->post('password');

    $result=$this->user->checkExistUser($username);

    if(!$result){

        $data=array(
            'username'=>$username,
            'password'=>md5($password)
            );

    $this->user->register($data);

    echo "<script>alert('You have success registered');</script>";
    $this->load->view('home_view');
    }
    else{

        echo "<script>alert('Sorry, this email address has been used!');</script>";
        $this->load->view('registerView');
    }
</code>```

This is my view file named registerView

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to Stock game</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
</script>

</head>
<body>

<div id="container">
<h1>Welcome to Stock game!</h1>

<div id="body">
    <p>This is the register page</p>

</div>

<div>

    <form  name="userform" id="userform" >
    <input type="text" name="name" placeholder="Name"/>
    <input type="text" name="password" placeholder="Password"/>

    <button name="submit" value="submit">Register</button>
    </form>
</div>
    <script type="text/javascript">
    $(document).ready(function(){
        $('form#userform').on('submit',function(e){
            e.preventDefault();

    var name=$("#name").val();
    var password=$("#password").val();
    $.ajax({

        type:'POST',
        url:'register/registerUser',
        data:
        {'name':JSON.stringify(name),'password':JSON.stringify(password)},
        dataType:'JSON',
        success: function(response){
            if(response=="success"){
                alert("Yes login");
            }
        },
       error: function (xhr, ajaxOptions, thrownError) {
       alert(xhr.status);
       alert(xhr.responseText);
       alert(thrownError);
   }
   });
        });
    });
    </script>
    </div>
    <br/>
    </body>
    </html>
</code>```

I have tested the controller and model class with a simple form post(form action=xxx, method=post) and it is no error.
I searched almost every stackoverflow questions about this, but i still cannot fix it, I hope someone can help me.

答: Spent around 5hrs on this question, I did a simple step and found the bug. What i do is modified name and password value by myself, so don't care what is the input, just to test if the data i modified will be sent to controller or not, the result is yes, it is stored in my database. So the bug should be the way how i read the input, after i put (id="name" before name="name") in the tag for name, and did the same thing for password tag, the server not give me 500 anymore. </p>

Body:
This is the error message found on google chrome:

POST http://localhost/display/register/registerUser 500 (Internal Server Error)

My project file name is "display".

One controller file named "register" ,it has a function called "registerUser". All it does is getting user's input, and compare it with database to see if the name is used or not, if valid store it into database and give them a success message, if not valid give a error message.

$username=$this->input->post('name');
    $password=$this->input->post('password');

    $result=$this->user->checkExistUser($username);

    if(!$result){

        $data=array(
            'username'=>$username,
            'password'=>md5($password)
            );

    $this->user->register($data);

    echo "";
    $this->load->view('home_view');
    }
    else{

        echo "";
        $this->load->view('registerView');
    }

This is my view file named registerView

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>

<meta charset="utf-8">
<title>Welcome to Stock game</title>

Welcome to Stock game!

This is the register page

    <form  name="userform" id="userform" >
    <input type="text" name="name" placeholder="Name"/>
    <input type="text" name="password" placeholder="Password"/>

    <button name="submit" value="submit">Register</button>
    </form>

I have tested the controller and model class with a simple form post(form action=xxx, method=post) and it is no error.
I searched almost every stackoverflow questions about this, but i still cannot fix it, I hope someone can help me.


问:
Symfony - Transform Data before sending to view
Hi !

i'd like to transform data before sending it to the view. The view is json response using FOSRestBundle.

For example, I have a Product entity with field Category, that is a reference to a Category Entity. On the output, i'd like to not to display json with the whole category, but rather only its ID field.

Of course, you can further process the entity in the Controller to return only specific field from the category, but..

I wanted to ask, if there's any "standard" solution how to do that, maybe using annotation?

Thank you

答:
I reckon the best practice or standard way to achieve what you want (filtering/processing entity data before return as JSON to view), is to make use of serializer. You can consider using the Symfony Serializer Bundle: http://symfony.com/doc/current/components/serializer.html or the JMS Serializer: http://jmsyst.com/libs/serializer.

I myself recommend the JMS one, it has really good documentation, the definition is completely controlled through annotation, and a well-thought events system  and a few feature I can list as follows:

-- Expose / Exclude specific entity attributes.

-- Create Virtual Property (attributes) for the entity once it converted to JSON. (So for example if you have Entity Product with attribute Price and you want to have a calculated field in the JSON object call taxPrice you can achieve it).

-- Access Control who can access which attributes/entities by categorising attributes to different groups.

-- Pre Serialization and Post Serialization events so you can tweak the data even further.

I can say the Serializer works so well with the Forest Bundle that once you get used to it, you can hardly write your project the different way :D.


问:
CodeIgniter - I want to define array like config array in config.php file
I want to define my array like config array in config.php file. So I can access this array any where in my view.

config.php

```<code>$config['base_url'] = '';
$my_array['app_admin_panel'] = '';
$my_array['app_admin_panel_assets'] = '';
</code>```

答:
Try below</p>

```<code>$config['base_url'] = '';
$my_array['app_admin_panel'] = '';
$my_array['app_admin_panel_assets'] = '';
$config['my_array'] = $my_array;
</code>```

Body:
I want to define my array like config array in config.php file. So I can access this array any where in my view.

config.php

$config['base_url'] = '';
$my_array['app_admin_panel'] = '';
$my_array['app_admin_panel_assets'] = '';

Body:
Try below

$config['base_url'] = '';
$my_array['app_admin_panel'] = '';
$my_array['app_admin_panel_assets'] = '';
$config['my_array'] = $my_array;


问:
Changing Android Device orientation with ADB
I'm using Android 4.4 on a real device and I want to set the device orientation via adb.  I don't want it done with uiautomator since it won't last after the termination of the uiautomator code.

How can I do this?

答:
Disable accelerometer_rotation and set the user_rotation

user_rotation Values:

```<code>0           # Protrait
1           # Landscape
2           # Protrait Reversed
3           # Landscape Reversed
</code>```

accelerometer_rotation Values:

```<code>0           # Stay in the current rotation
1           # Rotate the content of the screen
</code>```

Example using adb:

```<code>adb shell settings put system accelerometer_rotation 0
adb shell settings put system user_rotation 3
</code>```

Example programmatically:

```<code>import android.provider.Settings;

// You can get ContentResolver from the Context
Settings.System.putInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(getContentResolver(), Settings.System.USER_ROTATION, 3);
</code>```

Body:
Disable accelerometer_rotation and set the user_rotation

user_rotation Values:

0           # Protrait
1           # Landscape
2           # Protrait Reversed
3           # Landscape Reversed

accelerometer_rotation Values:

0           # Stay in the current rotation
1           # Rotate the content of the screen

Example using adb:

adb shell settings put system accelerometer_rotation 0
adb shell settings put system user_rotation 3

Example programmatically:

import android.provider.Settings;

// You can get ContentResolver from the Context
Settings.System.putInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
Settings.System.putInt(getContentResolver(), Settings.System.USER_ROTATION, 3);


问:
Wordpress - How to Display Posts Grouped by Category?
I want to display post titles grouped by category as such in WordPress:

Category: Apples
 - Post Title One
 - Post Title Two
 - Post Title ....

Category: Oranges
 - Post Title One
 - Post Title Two
 - Post Title ....

I need the code to accomplish this, not a plugin or category widget.

答:
This is similar to creating a "Archive by Category Page" and can be done with the following code:

```<code><?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <div class="post" id="post-<?php the_ID(); ?>">
    <h2><?php the_title(); ?></h2>
        <div class="entry">
            <?php the_content('<p class="serif">Read the rest of this page »</p>'); ?>

            <?php wp_link_pages(array('before' => '<p><strong>Pages:</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?>

        </div>
    </div>
    <?php endwhile; endif; ?>

    <!-- Category Archive Start -->
    <ul class="catArchive">
    <?php
    $catQuery = $wpdb->get_results("SELECT * FROM $wpdb->terms AS wterms INNER JOIN $wpdb->term_taxonomy AS wtaxonomy ON ( wterms.term_id = wtaxonomy.term_id ) WHERE wtaxonomy.taxonomy = 'category' AND wtaxonomy.parent = 0 AND wtaxonomy.count > 0");

    $catCounter = 0;

    foreach ($catQuery as $category) {

        $catCounter++;

        $catStyle = '';
        if (is_int($catCounter / 2)) $catStyle = ' class="catAlt"';

        $catLink = get_category_link($category->term_id);

        echo '<li'.$catStyle.'><h3><a href="'.$catLink.'" title="'.$category->name.'">'.$category->name.'</a></h3>';
            echo '<ul>';

            query_posts('cat='.$category->term_id.'&showposts=5');?>

            <?php while (have_posts()) : the_post(); ?>
                <li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
            <?php endwhile; ?>

                <li><a href="<?php echo $catLink; ?>" title="<?php echo $category->name; ?>">More <strong><?php echo $category->name; ?></strong></a></li>
            </ul>
        </li>
        <?php } ?>
    </ul>
    <!-- Category Archive End -->
</code>```

Note that the code above will only display categories that have posts associated with them, otherwise they will be skipped.

Also, it'll only show the last 5 posts under each category. You can change that by altering the number after the showposts variable. For example, you could change:

```<code>query_posts('cat='.$category->term_id.'&showposts=5');
</code>```

to one where you displayed 10 posts:

```<code>query_posts('cat='.$category->term_id.'&showposts=10');
</code>```

Substitute the line above into the loop at the very beginning and you should have a functioning "Archive by Category" page.

Body:
This is similar to creating a "Archive by Category Page" and can be done with the following code:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <div class="post" id="post-<?php the_ID(); ?>">
    <h2><?php the_title(); ?></h2>
        <div class="entry">
            <?php the_content('<p class="serif">Read the rest of this page &raquo;</p>'); ?>

            <?php wp_link_pages(array('before' => '<p><strong>Pages:</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?>

        </div>
    </div>
    <?php endwhile; endif; ?>

    <!-- Category Archive Start -->
    <ul class="catArchive">
    <?php
    $catQuery = $wpdb->get_results("SELECT * FROM $wpdb->terms AS wterms INNER JOIN $wpdb->term_taxonomy AS wtaxonomy ON ( wterms.term_id = wtaxonomy.term_id ) WHERE wtaxonomy.taxonomy = 'category' AND wtaxonomy.parent = 0 AND wtaxonomy.count > 0");

    $catCounter = 0;

    foreach ($catQuery as $category) {

        $catCounter++;

        $catStyle = '';
        if (is_int($catCounter / 2)) $catStyle = ' class="catAlt"';

        $catLink = get_category_link($category->term_id);

        echo '<li'.$catStyle.'><h3><a href="'.$catLink.'" title="'.$category->name.'">'.$category->name.'</a></h3>';
            echo '<ul>';

            query_posts('cat='.$category->term_id.'&showposts=5');?>

            <?php while (have_posts()) : the_post(); ?>
                <li><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
            <?php endwhile; ?>

                <li><a href="<?php echo $catLink; ?>" title="<?php echo $category->name; ?>">More <strong><?php echo $category->name; ?></strong></a></li>
            </ul>
        </li>
        <?php } ?>
    </ul>
    <!-- Category Archive End -->

Note that the code above will only display categories that have posts associated with them, otherwise they will be skipped.

Also, it'll only show the last 5 posts under each category. You can change that by altering the number after the showposts variable. For example, you could change:

query_posts('cat='.$category->term_id.'&showposts=5');

to one where you displayed 10 posts:

query_posts('cat='.$category->term_id.'&showposts=10');

Substitute the line above into the loop at the very beginning and you should have a functioning "Archive by Category" page.