text:
Q: Java - I need to update JTextFields in a Swing GUI program I have a program that looks into a single Notepad file which contains information similar to:
Cardiff : 3245658

Bristol : 4726485

Manchester : 4728945

These places and numbers are coming out of a automatic system, and the numbers change every 20 seconds or so.
I need to create a loop(I'm guessing) so that when the numbers change, my program will look back into the notepad file and update the number in the JTextField
P.s
I have already created the program so that it looks into the file, gets the information needs and puts it in the correct place, using an ArrayList,
All I need help with is how to make the code automatically update when there is a change in the file, and I need to do this without using any sort of Jbuttons, it just needs to do it by itself.
My whole code as it stands:
package window;

import java.awt.Color;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MapTest {

    private JFrame frame;
    static JTextField txtCardiff;
    static JTextField txtBristol;
    static JTextField txtSheffield;
    static JTextField txtDerby;
    static JTextField txtGlasgow;
    static JTextField txtFalkirk;
    static JTextField txtNewcastle;
    static JTextField txtLeeds;
    static JTextField txtPreston;
    static JTextField txtManchester;
    static JTextField txtWolverhampton;
    static JTextField txtBirmingham;
    static JTextField txtMiltonKeynes;
    static JTextField txtPeterborough;
    static JTextField txtColindale;
    static JTextField txtStepneyGreen;
    static JTextField txtSlough;
    static JTextField txtFaraday;
    static JTextField txtGuildford;
    static JTextField txtSouthbank;

    static BufferedReader CSVFile = new BufferedReader(new FileReader
        ("C:/Users/606854007/workspace/NetworkAppTest/jar/window/Cardiff.txt"));
// putting static infront of this Br ' CSVFile' gives:
//Unhandled exception type FileNotFoundException.
//but when i take away the 'static' it causes a problem in the 'FileCheckerWorker' class.
// (Will comment where and what)

    ArrayList<String> csv = new ArrayList<String>();

    /**
    private String output = "";
    private String output1 = "";
    private String output2 = "";
    private String output3 = "";
    private String output4 = "";
    private String output5 = "";
    private String output6 = "";
    private String output7 = "";
    private String output8 = "";
    private String output9 = "";
    private String output10 = "";
    private String output11 = "";
    private String output12 = "";
    private String output13 = "";
    private String output14 = "";
    private String output15 = "";
    private String output16 = "";
    private String output17 = "";
    private String output18 = "";
    private String output19 = "";
    **/
    /** * Launch the application. */
    public static void main(String[] args) {
         try {
                UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());

            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();

            } catch (InstantiationException e1) {
                e1.printStackTrace();

            } catch (IllegalAccessException e1) {
                e1.printStackTrace();

            } catch (UnsupportedLookAndFeelException e1) {
                e1.printStackTrace();
            }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MapTest window = new MapTest();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * Create the application.
     *
     * @throws IOException
     */
    public MapTest() throws IOException {
        try {
            initialize();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * Initialise the contents of the frame.
     *
     * @param output
     * @throws IOException
     */

    private void initialize() throws IOException {

                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());
                csv.add(CSVFile.readLine());

                System.out.println(csv.get(0));
                System.out.println(csv.get(1));
                System.out.println(csv.get(2));
                System.out.println(csv.get(3));
                System.out.println(csv.get(4));
                System.out.println(csv.get(5));
                System.out.println(csv.get(6));
                System.out.println(csv.get(7));
                System.out.println(csv.get(8));
                System.out.println(csv.get(9));
                System.out.println(csv.get(10));
                System.out.println(csv.get(11));
                System.out.println(csv.get(12));
                System.out.println(csv.get(13));
                System.out.println(csv.get(14));
                System.out.println(csv.get(15));
                System.out.println(csv.get(16));
                System.out.println(csv.get(17));
                System.out.println(csv.get(18));
                System.out.println(csv.get(19));

        /**
         * JPanel container = new JPanel(); container.add(txtBirmingham);
         * container.add(txtBristol); container.add(txtCardiff);
         * container.add(txtColindale); container.add(txtDerby);
         * container.add(txtFalkirk); container.add(txtGlasgow);
         * container.add(txtGuildford); container.add(txtLeeds);
         * container.add(txtManchester); container.add(txtMiltonKeynes);
         * container.add(txtNewcastle); container.add(txtPeterborough);
         * container.add(txtPreston); container.add(txtSheffield);
         * container.add(txtSlough); container.add(txtSouthbank);
         * container.add(txtStepneyGreen); container.add(txtWolverhampton);
         * //container.add(); JScrollPane jsp = new JScrollPane(container);
         * frame.add(jsp);
         **/

        frame = new JFrame();
        frame.setBounds(0, 0, 1000, 1086);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        frame.setBackground(Color.CYAN);

        txtCardiff = new JTextField();
        txtCardiff.setText(csv.get(0));
        txtCardiff.setBackground(Color.GREEN);
        txtCardiff.setBounds(305, 699, 102, 20);
        frame.getContentPane().add(txtCardiff);
        txtCardiff.setColumns(10);

        txtBristol = new JTextField();
        txtBristol.setText(csv.get(1));
        txtBristol.setBackground(Color.GREEN);
        txtBristol.setBounds(416, 780, 102, 20);
        frame.getContentPane().add(txtBristol);
        txtBristol.setColumns(10);

        txtSheffield = new JTextField();
        txtSheffield.setText(csv.get(2));
        txtSheffield.setBackground(Color.GREEN);
        txtSheffield.setBounds(517, 356, 110, 20);
        frame.getContentPane().add(txtSheffield);
        txtSheffield.setColumns(10);

        txtDerby = new JTextField();
        txtDerby.setText(csv.get(3));
        txtDerby.setBackground(Color.GREEN);
        txtDerby.setBounds(582, 451, 90, 20);
        frame.getContentPane().add(txtDerby);
        txtDerby.setColumns(10);

        txtGlasgow = new JTextField();
        txtGlasgow.setText(csv.get(4));
        txtGlasgow.setBackground(Color.GREEN);
        txtGlasgow.setBounds(250, 94, 102, 20);
        frame.getContentPane().add(txtGlasgow);
        txtGlasgow.setColumns(10);

        txtFalkirk = new JTextField();
        txtFalkirk.setText(csv.get(5));
        txtFalkirk.setColumns(10);
        txtFalkirk.setBackground(Color.GREEN);
        txtFalkirk.setBounds(331, 41, 102, 20);
        frame.getContentPane().add(txtFalkirk);

        txtNewcastle = new JTextField();
        txtNewcastle.setText(csv.get(6));
        txtNewcastle.setColumns(10);
        txtNewcastle.setBackground(Color.GREEN);
        txtNewcastle.setBounds(424, 141, 111, 20);
        frame.getContentPane().add(txtNewcastle);

        txtLeeds = new JTextField();
        txtLeeds.setText(csv.get(7));
        txtLeeds.setColumns(10);
        txtLeeds.setBackground(Color.GREEN);
        txtLeeds.setBounds(481, 244, 102, 20);
        frame.getContentPane().add(txtLeeds);

        txtPreston = new JTextField();
        txtPreston.setText(csv.get(8));
        txtPreston.setColumns(10);
        txtPreston.setBackground(Color.GREEN);
        txtPreston.setBounds(356, 221, 102, 20);
        frame.getContentPane().add(txtPreston);

        txtManchester = new JTextField();
        txtManchester.setText(csv.get(9));
        txtManchester.setColumns(10);
        txtManchester.setBackground(Color.GREEN);
        txtManchester.setBounds(394, 394, 124, 20);
        frame.getContentPane().add(txtManchester);

        txtWolverhampton = new JTextField();
        txtWolverhampton.setText(csv.get(10));
        txtWolverhampton.setColumns(10);
        txtWolverhampton.setBackground(Color.GREEN);
        txtWolverhampton.setBounds(360, 486, 153, 20);
        frame.getContentPane().add(txtWolverhampton);

        txtBirmingham = new JTextField();
        txtBirmingham.setText(csv.get(11));
        txtBirmingham.setColumns(10);
        txtBirmingham.setBackground(Color.GREEN);
        txtBirmingham.setBounds(424, 553, 128, 20);
        frame.getContentPane().add(txtBirmingham);

        txtMiltonKeynes = new JTextField();
        txtMiltonKeynes.setText(csv.get(12));
        txtMiltonKeynes.setColumns(10);
        txtMiltonKeynes.setBackground(Color.GREEN);
        txtMiltonKeynes.setBounds(474, 604, 135, 20);
        frame.getContentPane().add(txtMiltonKeynes);

        txtPeterborough = new JTextField();
        txtPeterborough.setText(csv.get(13));
        txtPeterborough.setColumns(10);
        txtPeterborough.setBackground(Color.GREEN);
        txtPeterborough.setBounds(655, 576, 135, 20);
        frame.getContentPane().add(txtPeterborough);

        txtColindale = new JTextField();
        txtColindale.setText(csv.get(14));
        txtColindale.setColumns(10);
        txtColindale.setBackground(Color.GREEN);
        txtColindale.setBounds(541, 699, 107, 20);
        frame.getContentPane().add(txtColindale);

        txtStepneyGreen = new JTextField();
        txtStepneyGreen.setText(csv.get(15));
        txtStepneyGreen.setColumns(10);
        txtStepneyGreen.setBackground(Color.GREEN);
        txtStepneyGreen.setBounds(667, 699, 137, 20);
        frame.getContentPane().add(txtStepneyGreen);

        txtSlough = new JTextField();
        txtSlough.setText(csv.get(16));
        txtSlough.setColumns(10);
        txtSlough.setBackground(Color.GREEN);
        txtSlough.setBounds(525, 756, 102, 20);
        frame.getContentPane().add(txtSlough);

        txtFaraday = new JTextField();
        txtFaraday.setText(csv.get(17));
        txtFaraday.setColumns(10);
        txtFaraday.setBackground(Color.GREEN);
        txtFaraday.setBounds(650, 756, 102, 20);
        frame.getContentPane().add(txtFaraday);

        txtGuildford = new JTextField();
        txtGuildford.setText(csv.get(18));
        txtGuildford.setColumns(10);
        txtGuildford.setBackground(Color.GREEN);
        txtGuildford.setBounds(525, 822, 102, 20);
        frame.getContentPane().add(txtGuildford);

        txtSouthbank = new JTextField();
        txtSouthbank.setText(csv.get(19));
        txtSouthbank.setColumns(10);
        txtSouthbank.setBackground(Color.GREEN);
        txtSouthbank.setBounds(655, 807, 115, 20);
        frame.getContentPane().add(txtSouthbank);

        JLabel lblNewLabel = new JLabel("New label");
        lblNewLabel.setForeground(Color.BLACK);
        lblNewLabel.setBackground(Color.BLACK);
        lblNewLabel
                .setIcon(new ImageIcon(
                        "C:\\Users\\606854007\\workspace\\NetworkAppTest\\Test\\window\\England_Wales.gif"));
        lblNewLabel.setBounds(33, 11, 890, 1086);
        frame.getContentPane().add(lblNewLabel);

        new FileCheckerWorker(null).execute();
\\ if i dont but null in the '()' then it comes up with an error,
\\and this just makes it execute:
    /**
public FileCheckerWorker(MapTest mapTest) {
        this.mapTest = mapTest;
    }
**/
\\ which is not what I want, I have tried to add commands
\\to run the methods from within:
\\ ' public FileCheckerWorker(MapTest mapTest)' method
\\ but it gives me a null pointer exception,

}

    }

Below is the 'FileCheckerWorker' class hoping I've done it right :p
package window;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.SwingWorker;

public class FileCheckerWorker extends SwingWorker<Object, List<String>> {

    private MapTest mapTest;

    public FileCheckerWorker(MapTest mapTest) {
        this.mapTest = mapTest;
    }

        @Override
        protected void process(List<List<String>> chunks) {
           List<String> values = chunks.get(chunks.size() - 1);

           mapTest.txtCardiff.setText(values.get(0));
           mapTest.txtBristol.setText(values.get(1));
           mapTest.txtSheffield.setText(values.get(2));
           mapTest.txtDerby.setText(values.get(3));
           mapTest.txtGlasgow.setText(values.get(4));
           mapTest.txtFalkirk.setText(values.get(5));
           mapTest.txtNewcastle.setText(values.get(6));
           mapTest.txtLeeds.setText(values.get(7));
           mapTest.txtPreston.setText(values.get(8));
           mapTest.txtManchester.setText(values.get(9));
           mapTest.txtWolverhampton.setText(values.get(10));
           mapTest.txtBirmingham.setText(values.get(11));
           mapTest.txtMiltonKeynes.setText(values.get(12));
           mapTest.txtPeterborough.setText(values.get(13));
           mapTest.txtColindale.setText(values.get(14));
           mapTest.txtStepneyGreen.setText(values.get(15));
           mapTest.txtSlough.setText(values.get(16));
           mapTest.txtFaraday.setText(values.get(17));
           mapTest.txtGuildford.setText(values.get(18));
           mapTest.txtSouthbank.setText(values.get(19));
        }

        @Override
        protected Object doInBackground() throws Exception {
            long lastUpdated = -1;
            File csvFile = new File("C:/Users/606854007/workspace/NetworkAppTest/Jar/window/Cardiff.txt");
            while (true) {
                if (csvFile.lastModified() != lastUpdated) {
                    BufferedReader csvReader = null;
                    List<String> values = new ArrayList<String>(20);
                    try {
                        csvReader = new BufferedReader(new FileReader("C:/Users/606854007/workspace/NetworkAppTest/Jar/window/Cardiff.txt"));
                        for (int index = 0; index < 20; index++) {
                            values.add(mapTest.CSVFile.readLine());
                        }
                        publish(values);
                        lastUpdated = csvFile.lastModified();
                    } finally {
                        try {
                            csvReader.close();
                        } catch (Exception e) {
                        }
                    }

                    Thread.sleep(5000);
                    System.out.println("Check For Change");
                }
            }
        }

}

UPDATED Both codes to what they are now.
Also when I thought I had the 'doInBackground' working if gave me a NullPointerException on line
     values.add(mapTest.CSVFile.readLine());

A: Take a look at ScheduledExecutorService. Using this you can schedule some periodic tasks. (in your case will be reading from file at every 20 seconds).

A: Wrap the "look up" code in a SwingWorker, use Thread.sleep to allow the background thread to idle for a given period (say 20 seconds).
Load the contents of the file, determine if it's changed and use the pusblish method to send the results to the process method, which allows you to process the results withing the Event Dispatching Thread
Take a look at SwingWorker for more details
Simple Example
public class PeriodicalWorker extends SwingWorker<Object, String> {
    private boolean running = true;

    public Object doInBackground() throws Exception {
        while (running) {
            try {
                Thread.sleep(20000);
            } catch (Exception exp) {}
            // Load the values...
            // Check to see if anything needs to updated...
            publish(values); // List of String array values
        }
        return null;
    }

    public void process(List<String> values) {
        // Assign the values to the UI...
    }
}

I'm sure you can a "stop" method to set running to false ;)
Updated
The basic concept is very simple.  You need to keep track of the last time the file was updated, if the value changes between sleeps, you need to reread the file and update the values on the screen.
This process has been made considerably easier in Java 7, but before that, you could use File#lastModified to check the last modified date/time of the file.
Below is simple example.
public class FileCheckerWorker extends SwingWorker<Object, List<String>> {

    @Override
    protected void process(List<List<String>> chunks) {
        List<String> values = chunks.get(chunks.size() - 1);

        txtCardiff.setText(values.get(0));
        txtBristol.setText(values.get(1));
        txtSheffield.setText(values.get(2));
        txtDerby.setText(values.get(3));
        txtGlasgow.setText(values.get(4));
        txtFalkirk.setText(values.get(5));
        txtNewcastle.setText(values.get(6));
        txtLeeds.setText(values.get(7));
        txtPreston.setText(values.get(8));
        txtManchester.setText(values.get(9));
        txtWolverhampton.setText(values.get(10));
        txtBirmingham.setText(values.get(11));
        txtMiltonKeynes.setText(values.get(12));
        txtPeterborough.setText(values.get(13));
        txtColindale.setText(values.get(14));
        txtStepneyGreen.setText(values.get(15));
        txtSlough.setText(values.get(16));
        txtFaraday.setText(values.get(17));
        txtGuildford.setText(values.get(18));
        txtSouthbank.setText(values.get(19));
    }

    @Override
    protected Object doInBackground() throws Exception {
        long lastUpdated = -1;
        File csvFile = new File("...");
        while (true) {
            if (csvFile.lastModified() != lastUpdated) {
                BufferedReader csvReader = null;
                List<String> values = new ArrayList<String>(20);
                try {
                    csvReader = new BufferedReader(new FileReader("..."));
                    for (int index = 0; index < 20; index++) {
                        values.add(CSVFile.readLine());
                    }
                    publish(values);
                    lastUpdated = csvFile.lastModified();
                } finally {
                    try {
                        csvReader.close();
                    } catch (Exception e) {
                    }
                }

                Thread.sleep(20000);

            }
        }
    }
}

You would place this at the end of your initialise method with new FileCheckerWorker.execute().
Updated
Instead of making your fields static, pass a reference to of the MapTest to the worker...
import java.awt.Color;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MapTest {

    private JFrame frame;
    protected JTextField txtCardiff;
    protected JTextField txtBristol;
    protected JTextField txtSheffield;
    protected JTextField txtDerby;
    protected JTextField txtGlasgow;
    protected JTextField txtFalkirk;
    protected JTextField txtNewcastle;
    protected JTextField txtLeeds;
    protected JTextField txtPreston;
    protected JTextField txtManchester;
    protected JTextField txtWolverhampton;
    protected JTextField txtBirmingham;
    protected JTextField txtMiltonKeynes;
    protected JTextField txtPeterborough;
    protected JTextField txtColindale;
    protected JTextField txtStepneyGreen;
    protected JTextField txtSlough;
    protected JTextField txtFaraday;
    protected JTextField txtGuildford;
    protected JTextField txtSouthbank;
    private BufferedReader CSVFile = new BufferedReader(new FileReader("C:/Users/606854007/workspace/NetworkAppTest/jar/window/Cardiff.txt"));

    ArrayList<String> csv = new ArrayList<String>();

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MapTest window = new MapTest();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     *
     * @throws IOException
     */
    public MapTest() throws IOException {
        try {
            initialize();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * Initialise the contents of the frame.
     *
     * @param output
     * @throws IOException
     */
    private void initialize() throws IOException {
        frame = new JFrame();
        frame.setBounds(0, 0, 1000, 1086);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        frame.setBackground(Color.CYAN);

        txtCardiff = new JTextField();
        txtCardiff.setBackground(Color.GREEN);
        txtCardiff.setBounds(305, 699, 102, 20);
        frame.getContentPane().add(txtCardiff);
        txtCardiff.setColumns(10);

        txtBristol = new JTextField();
        txtBristol.setBackground(Color.GREEN);
        txtBristol.setBounds(416, 780, 102, 20);
        frame.getContentPane().add(txtBristol);
        txtBristol.setColumns(10);

        txtSheffield = new JTextField();
        txtSheffield.setBackground(Color.GREEN);
        txtSheffield.setBounds(517, 356, 110, 20);
        frame.getContentPane().add(txtSheffield);
        txtSheffield.setColumns(10);

        txtDerby = new JTextField();
        txtDerby.setBackground(Color.GREEN);
        txtDerby.setBounds(582, 451, 90, 20);
        frame.getContentPane().add(txtDerby);
        txtDerby.setColumns(10);

        txtGlasgow = new JTextField();
        txtGlasgow.setBackground(Color.GREEN);
        txtGlasgow.setBounds(250, 94, 102, 20);
        frame.getContentPane().add(txtGlasgow);
        txtGlasgow.setColumns(10);

        txtFalkirk = new JTextField();
        txtFalkirk.setColumns(10);
        txtFalkirk.setBackground(Color.GREEN);
        txtFalkirk.setBounds(331, 41, 102, 20);
        frame.getContentPane().add(txtFalkirk);

        txtNewcastle = new JTextField();
        txtNewcastle.setColumns(10);
        txtNewcastle.setBackground(Color.GREEN);
        txtNewcastle.setBounds(424, 141, 111, 20);
        frame.getContentPane().add(txtNewcastle);

        txtLeeds = new JTextField();
        txtLeeds.setColumns(10);
        txtLeeds.setBackground(Color.GREEN);
        txtLeeds.setBounds(481, 244, 102, 20);
        frame.getContentPane().add(txtLeeds);

        txtPreston = new JTextField();
        txtPreston.setColumns(10);
        txtPreston.setBackground(Color.GREEN);
        txtPreston.setBounds(356, 221, 102, 20);
        frame.getContentPane().add(txtPreston);

        txtManchester = new JTextField();
        txtManchester.setColumns(10);
        txtManchester.setBackground(Color.GREEN);
        txtManchester.setBounds(394, 394, 124, 20);
        frame.getContentPane().add(txtManchester);

        txtWolverhampton = new JTextField();
        txtWolverhampton.setColumns(10);
        txtWolverhampton.setBackground(Color.GREEN);
        txtWolverhampton.setBounds(360, 486, 153, 20);
        frame.getContentPane().add(txtWolverhampton);

        txtBirmingham = new JTextField();
        txtBirmingham.setColumns(10);
        txtBirmingham.setBackground(Color.GREEN);
        txtBirmingham.setBounds(424, 553, 128, 20);
        frame.getContentPane().add(txtBirmingham);

        txtMiltonKeynes = new JTextField();
        txtMiltonKeynes.setColumns(10);
        txtMiltonKeynes.setBackground(Color.GREEN);
        txtMiltonKeynes.setBounds(474, 604, 135, 20);
        frame.getContentPane().add(txtMiltonKeynes);

        txtPeterborough = new JTextField();
        txtPeterborough.setColumns(10);
        txtPeterborough.setBackground(Color.GREEN);
        txtPeterborough.setBounds(655, 576, 135, 20);
        frame.getContentPane().add(txtPeterborough);

        txtColindale = new JTextField();
        txtColindale.setColumns(10);
        txtColindale.setBackground(Color.GREEN);
        txtColindale.setBounds(541, 699, 107, 20);
        frame.getContentPane().add(txtColindale);

        txtStepneyGreen = new JTextField();
        txtStepneyGreen.setColumns(10);
        txtStepneyGreen.setBackground(Color.GREEN);
        txtStepneyGreen.setBounds(667, 699, 137, 20);
        frame.getContentPane().add(txtStepneyGreen);

        txtSlough = new JTextField();
        txtSlough.setColumns(10);
        txtSlough.setBackground(Color.GREEN);
        txtSlough.setBounds(525, 756, 102, 20);
        frame.getContentPane().add(txtSlough);

        txtFaraday = new JTextField();
        txtFaraday.setColumns(10);
        txtFaraday.setBackground(Color.GREEN);
        txtFaraday.setBounds(650, 756, 102, 20);
        frame.getContentPane().add(txtFaraday);

        txtGuildford = new JTextField();
        txtGuildford.setColumns(10);
        txtGuildford.setBackground(Color.GREEN);
        txtGuildford.setBounds(525, 822, 102, 20);
        frame.getContentPane().add(txtGuildford);

        txtSouthbank = new JTextField();
        txtSouthbank.setColumns(10);
        txtSouthbank.setBackground(Color.GREEN);
        txtSouthbank.setBounds(655, 807, 115, 20);
        frame.getContentPane().add(txtSouthbank);

        JLabel lblNewLabel = new JLabel("New label");
        lblNewLabel.setForeground(Color.BLACK);
        lblNewLabel.setBackground(Color.BLACK);
        lblNewLabel.setIcon(new ImageIcon(
                        "C:\\Users\\606854007\\workspace\\NetworkAppTest\\Test\\window\\England_Wales.gif"));
        lblNewLabel.setBounds(33, 11, 890, 1086);
        frame.getContentPane().add(lblNewLabel);

        new FileCheckerWorker(this).execute();

    }

    public class FileCheckerWorker extends SwingWorker<Object, List<String>> {

        private MapTest mapTest;

        public FileCheckerWorker(MapTest mapTest) {
            this.mapTest = mapTest;
        }

        @Override
        protected void process(List<List<String>> chunks) {
            List<String> values = chunks.get(chunks.size() - 1);

            mapTest.txtCardiff.setText(values.get(0));
            mapTest.txtBristol.setText(values.get(1));
            mapTest.txtSheffield.setText(values.get(2));
            mapTest.txtDerby.setText(values.get(3));
            mapTest.txtGlasgow.setText(values.get(4));
            mapTest.txtFalkirk.setText(values.get(5));
            mapTest.txtNewcastle.setText(values.get(6));
            mapTest.txtLeeds.setText(values.get(7));
            mapTest.txtPreston.setText(values.get(8));
            mapTest.txtManchester.setText(values.get(9));
            mapTest.txtWolverhampton.setText(values.get(10));
            mapTest.txtBirmingham.setText(values.get(11));
            mapTest.txtMiltonKeynes.setText(values.get(12));
            mapTest.txtPeterborough.setText(values.get(13));
            mapTest.txtColindale.setText(values.get(14));
            mapTest.txtStepneyGreen.setText(values.get(15));
            mapTest.txtSlough.setText(values.get(16));
            mapTest.txtFaraday.setText(values.get(17));
            mapTest.txtGuildford.setText(values.get(18));
            mapTest.txtSouthbank.setText(values.get(19));
        }

        @Override
        protected Object doInBackground() throws Exception {
            long lastUpdated = -1;
            File csvFile = new File("C:/Users/606854007/workspace/NetworkAppTest/Jar/window/Cardiff.txt");
            while (true) {
                if (csvFile.lastModified() != lastUpdated) {
                    BufferedReader csvReader = null;
                    List<String> values = new ArrayList<String>(20);
                    try {
                        csvReader = new BufferedReader(new FileReader("C:/Users/606854007/workspace/NetworkAppTest/Jar/window/Cardiff.txt"));
                        for (int index = 0; index < 20; index++) {
                            values.add(mapTest.CSVFile.readLine());
                        }
                        publish(values);
                        lastUpdated = csvFile.lastModified();
                    } finally {
                        try {
                            csvReader.close();
                        } catch (Exception e) {
                        }
                    }

                    Thread.sleep(5000);
                    System.out.println("Check For Change");
                }
            }
        }
    }
}


text:
Q: How to add where on count() in joined table? How do I add the where clause only on the count()? Using ->where('point',1) will affect the end result of the whole table and that's not what I want. I want to calculate the count of points where it's  grouped by the child_id and the point column equals 1.
 $chore_contents = DB::table('chores_content')
        ->join('children', 'children.id', '=', 'chores_content.child_id')
        ->select('chores_content.id as content_id','chores_content.*', 'children.*', DB::raw("COUNT(point) as points"))
        ->where('chores_content.user_id', Auth::id())
        ->where('chores_content.chores_id', $id)
        ->groupBy('chores_content.child_id')
        ->get();
        return $chore_contents;

A: Use havingRaw to implement this:
$chore_contents = DB::table('chores_content')
    ->join('children', 'children.id', '=', 'chores_content.child_id')
    ->select('chores_content.id as content_id','chores_content.*', 'children.*',  DB::raw("COUNT(point) as points"))
    ->where('chores_content.user_id', Auth::id())
    ->where('chores_content.chores_id', $id)
    ->groupBy('chores_content.child_id')
    ->havingRaw('COUNT(point) =1')
    ->get();
    return $chore_contents;

I hope it helps.

A: This question lacks some clarity, so this is simply an educated guess at this point.
First to clarify that when you do this: count(point) you already exclude rows where point is null.  You should not be count(point) if you want to include rows where point is null.
Given your comments you seem to be contradicting your statement that you only want rows where point=1.  It now appears you want rows where point = 1 or point is null.
To do this with eloquent, you would need to have parens around the (point=1 OR point IS NULL) which you can do by passing an anonymous function:
$chore_contents = DB::table('chores_content')
    ->join('children', 'children.id', '=', 'chores_content.child_id')
    ->select('chores_content.id as content_id','chores_content.*', 'children.*',  DB::raw("COUNT(*) as points"))
    ->where('chores_content.user_id', Auth::id())
    ->where('chores_content.chores_id', $id)
    ->where(function ($chore_contents) {
        $chore_contents->where('point',1)
            ->orWhereNull('point');
    })
    ->groupBy('chores_content.child_id')
    ->havingRaw('COUNT(point) =1')
    ->get();
return $chore_contents;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Select only one in dynamic radio button It is possible to select only one radio button using a same name? I want to select only one radio button in every question.
The problem is it only selects one radio button in all appended html elements.
DEFAULT HMTL:
//question 1
<input type="radio" name="fields[my_cb][]" value="1">
<input type="radio" name="fields[my_cb][]" value="2">

ADDED HTML ELEMENTS USING JAVASCRIPT APPEND:
//question 2
<input type="radio" name="fields[my_cb][]" value="1">
<input type="radio" name="fields[my_cb][]" value="2">
<input type="radio" name="fields[my_cb][]" value="3">

A: You can only select one radio button in a group, and all the buttons with the same name are part of the same group. You should use a different name for the answers to each question. In your example, you can put the question number in the array index.
//question 1
<input type="radio" name="fields[my_cb][1]" value="1">
<input type="radio" name="fields[my_cb][1]" value="2">

//question 2
<input type="radio" name="fields[my_cb][2]" value="1">
<input type="radio" name="fields[my_cb][2]" value="2">
<input type="radio" name="fields[my_cb][2]" value="3">

A: To set a radio button in a button group to checked by default you use: checked="checked"
In order to have multiple button groups you need to name each group differently:
//question 1
<input type="radio" name="grp1" value="1" checked="checked">
<input type="radio" name="grp1" value="2">

//question 2
<input type="radio" name="grp2" value="1">
<input type="radio" name="grp2" value="2">
<input type="radio" name="grp2" value="3">


text:
Q: How to use programs with MPI? Is it possible to use programs with MPI for example blender?
Is it a mpi program by only adding the source file "mpi.h" or is there any way to simply convert an existing program for the use with mpi?
Also virtualbox would be really nice to use it with mpi..

A: MPI is a library that you compile with your program just like any other programming library. Unless you specifically make calls into the library to use the features of MPI, nothing special will happen.
In addition, MPI programs are launched differently than regular programs. Instead of just running the program normally from the command line
./a.out <arguments>

you use the MPI launcher which starts the appropriate number of processes (in this example, 4)
mpiexec -n 4 ./a.out

If you want to learn more about MPI, you should probably go find some tutorial websites and/or books. Explaining the whole thing doesn't really fit into this format.


text:
Q: Intellij, target JRE vesion doesn't match project jdk version I am using Intellij Community version 2019.3 on my MacBook. I have a simple springboot (java) project. Whenever I run my unit test I get the following warning:

Where should I check on Intellij to get rid of this error? (I heard on internet "Project Settings", but I can't find where this option is)

A: The target JRE version for Gradle can be configured from within Intellij via the Gradle JVM setting at Preferences (cmd + ,) > Build, Execution, Deployment > Gradle:

The project JDK version can be configured from the Project SDK setting in Project Structure (cmd + ;):

(Screenshots taken from IntelliJ IDEA 2020.1.4)

A: This is because you are building for target version of Java 1.8
Depending what you are using, Maven or Gradle, you set the target version of java with:
Gradle
  sourceCompatibility = '1.8'
  targetCompatibility = '1.8'

Docs:

*

*https://docs.gradle.org/current/userguide/java_plugin.html#sec:java-extension

*https://docs.gradle.org/current/javadoc/org/gradle/api/JavaVersion.html
Maven
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>

Docs:

*

*http://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html
You can change this version to 12 or JavaVersion.VERSION_12 to use your build JDK, but then you would lose the compatibility and won't be able to run the application jar with Java 1.8.
You can also change the build SDK version, on macOS press command + ; and go to Project Settings -> Project and change the Project SDK to the one you want to build it with.

A: Intellij + Gradle also refers to the Gradle JVM setup within Intellij.
Ensure to change that as shown below:


text:
Q: Set background for FMX popup window I have an FMX Android project compiled with Delphi 10.1 Berlin.  The user needs to select from 19 values to run it and I use a TPopupBox component to display 19 TRadioButtons that show in 3 columns of 7+7+5 buttons for that selection.
The default is for a transparent popup window which is useless, so I edited the style to add a white TRectangle to the background of the popup window which works, but only if I size the rectangle to match the size of the popup.  Aligning the rectangle to client or contents only sets an opaque background to the first row of radio buttons. I have 2 questions:

*

*How can I auto size the rectangle rather than fixing it at design time to match what I calculate will be set for popup.bounds?

*Is adding a TRectangle to the style background the best way to get an opaque control?

I have tried all obvious align options and searched the internet.  Somebody suggested deleting 'background' from the style list but that did not work. Somebody else suggested editing the manifest but my manifest just gets overwritten when I compile.

A: I believe you wrote erroneously TPopupBox and probably meant to write TPopup. That is anyway what you should use for popup windows.
You may want to create a new project, for testing purposes. Add a button near top left. This will show and hide the popup window.
Add a TPopup and size it as you wish, and set Visible := True.
Add a rectangle inside the popup and set its Align property to Contents. Set its Fill.Color property as you wish. Add TRadiobuttons as you wish, on the rectangle.
Finally, the code to toggle the popup visibility (but see notes in Help):
Popup1.IsOpen := not Popup1.IsOpen;

Please note! There are many properties that jointly affect the placement of the TPopup: Placement, PlacementRectangle, PlacementTarget. As I don't know your needs, I leave it to you to decide what to use.
A sample test case:

Here PlacementTarget is Button1 and Placement is Bottom.


text:
Q: Get pointer to Python int (in iteration) I'm binding to a C API that takes an array of structs (as ATTRIBUTE *attributes).
ctypedef struct ATTRIBUTE:
    unsigned long type
    void *pValue
    unsigned long ulValueLen

The C API assumes you're creating the struct array and its values on the stack before you call the function.
I can assign pValue as a one-off using:
cdef unsigned long value = True
attr.pValue = &value

However in this case we're taking values from Python (as an iterable). It appears to work okay for bytes.
data = PyMem_Malloc(len(attrs) * sizeof(ATTRIBUTE))

for index, (key, value) in enumerate(attrs.items()):
    data[index].type = key
    data[index].pValue = <unsigned char *> value
    data[index].ulValueLen = len(value)

However I have no stack definition to pass an integer type. What's the correct way to handle this? Do I need to also allocate arrays for other types I need to store and copy values into them, or can I access the underlying Python storage somehow?

A: You can do both.
If you want to get the address of a Python object you use id() function. Then it is a matter of hackery how to cast it to a reference or pointer. But it should be doable. Note that Python's id() doesn't have to be exact with C stack, although it probably is. I do not know, you should check.  If not, some operations should get you the C stack address from it.
I never needed such a stuff from cython's endpoint.
Or you can grab for the locals() dictionary and enter its C structure to snatch out the pointer to Python's instance of the int in question.
I.e. In the end it will be a structure in C.
If you need to grab a pointer to the int instance from Python's side. You can employ tricks like you suggested or use id() to get the address, then use ctypes to grab it.
Exactly how to get to whole C struct is  a matter of thinking. Whether to read mem block, then use struct.unpack() and then use some other stuff to convert it into Pythonic representation of original. Perhaps ctypes would let you do it directly and you would get ctypes.Structure().
I didn't play with it (yet) so these are only my ideas. I hope helpful ones. In theory, based on my knowledge, they should work fine.

A: My best solution so far is to store a set of results to struct.pack and pass those in.
try:
    attrs = dict(attrs)
    count = len(attrs)

    cdef ATTRIBUTE *data = <ATTRIBUTE *> PyMem_Malloc(count * sizeof(ATTRIBUTE))
    if not data:
        raise MemoryError()

    # Turn the values into bytes and store them so we have pointers
    # to them.
    _values = [
        # Real code is more interesting here
        value if isinstance(value, bytes) else struct.pack('L', value)
        for value in self.attrs.values()
    ]

    for index, (key, value) in enumerate(zip(attrs.keys(), self._values)):
        data[index].type = key
        data[index].pValue = <unsigned char *> value
        data[index].ulValueLen = len(value)

    doCall(data, count)

finally:
    PyMemFree(data)


text:
Q: wget script, but pipe it to bash only if SHA256 of script matches one-liner wget http://example.com/install.sh -O - | bash runs the script automatically but due to possible (TLS) MITM attacks etc, this is not safe. Is is possible to construct a one-liner that downloads the script, but executes it only if it's hash matches the one specified in the one-liner? It would be nice if the one-liner would print something like Warning! Hash mismatch if hash check fails.

A: So you want to download and run http://example.com/install.sh.
For now I assume that you have its SHA256 hash stored locally in a file called my-sha256.txt. The file contains only the hash itself and a Unix-style linebreak character, so its size must be exactly 65 bytes. You can create it by simply running this:
sha256sum ORIGINAL_FILE.SH | grep -Eo '^\w+' > my-sha256.txt

How you distribute this hash file from your development machine to the client is not part of this answer (yet, you might clarify your question and ask me to update this part based on your detailed specifications).

The actual command your client has to run to download, verify, and on success execute the script could look like this:
t=$(mktemp) && wget 'http://example.com/install.sh' -qO "$t" && if sha256sum "$t" | grep -Eo '^\w+' | cmp -s my-sha256.txt ; then bash "$t" ; else echo FAIL ; fi ; rm "$t"

Slightly shortened and ugly version without whitespace:
t=$(mktemp)&&wget 'http://example.com/install.sh' -qO"$t"&&if sha256sum "$t"|grep -Eo '^\w+'|cmp -s my-sha256.txt;then bash "$t";else echo FAIL;fi;rm "$t"

Placed on multiple lines for readability:
t=$(mktemp) &&
wget 'http://example.com/install.sh' -qO "$t" &&
if sha256sum "$t" | grep -Eo '^\w+' | cmp -s my-sha256.txt
    then bash "$t"
    else echo FAIL
fi
rm "$t"

If you want to directly provide the hash inside the command as string instead of reading from a file, simply use one of my original command versions above and replace the occurrence of my-sha256.txt with <(echo YOUR_HASH), inserting your real hash instead of the "YOUR_HASH" placeholder of course.
Explanation:
The script/one-liner first creates a temporary file using mktemp (uses the system's temp folder /tmp).
Then it uses wget to download your installation script from the specified URL and save it in the temp file.
Now we calculate its hash sum, filter only the hash value from the output of sha256sum and compare that to what we have stored in out my-sha256.txt.
If both hashes equal, we will invoke bash with our temporary script file as argument, else we echo FAIL or you could output a custom error message.
In the end we clean up by deleting our temporary file in both cases.

However, coming back to the problem of securely distributing the hash to verify the original script, this solution above will not help you much, as it solves one problem by creating another one of the same kind.
What you actually should do is to create a GPG key pair (and publish your public key to a keyserver), sign your script with it and offer the compressed signed binary for download. Then let the client verify and decrypt the script using gpg again and run it on success.

A: Since GPG fingerprints use insecure SHA-1 hash, here is a one-liner that allows authentication with unofficial SHA256 hash calculated from public key with
gpg --export <key ID> | sha256sum
command:
h="<SHA256 hash of exported public key>"; fp="<PGP key SHA1 fingerprint>"; f='key.pub'; gpg --keyserver pgp.mit.edu --recv $fp && gpg --export $fp > $f && if sha256sum $f | grep -Eo '^\w+' | cmp -s <(echo $h); then rm $f && wget https://example.com/install.sh{,.asc} -q && gpg --verify install.sh{.asc,} && bash install.sh; else rm $f; echo "ERROR: Signing key had invalid SHA256 hash"; fi;


text:
Q: MySQL delay in Relay Master log file We are facing a serious issue of time lagging in mysql database. We have two databases on different location which gets replicated (both are master and slave) there are 3 Relay log files(each 100 MB) which got transferred on Slave server but it is taking almost 5 hours to process each log file. What might be the reason? This is happening for the last one day only previously it was working fine.Any help/suggestion would be highly appreciated.
Top command:

Show slave status
Slave_IO_State:     [read blank]
Master_Host : Master IP address
Master_User: replication
Master_Port: 3306
Connect_Retry:  60
Master_Log_File: mysql-bin.000430
Read_Master_Log_Pos: 48495450
Relay_Log_File:mysqld-relay-bin.000008
Relay_Log_Pos:65771774
Relay_Master_Log_File:mysql-bin.000427
Slave_IO_Running:No
Slave_SQL_Running:Yes
Exec_Master_Log_Pos:65771611
Relay_Log_Space:363072212
Until_Condition:None
Seconds_Behind_Master:109300


text:
Q: Discontinuity of $\frac{1+\tan x}{1-\tan x}$
I have to find the discontinuity of the function $$y=\frac{1+\tan
 x}{1-\tan x}.$$

It reduces to $\tan(\pi/4+x)$. However the answer says that there is no value for which $y=-1$.
I can't understand. Please help!!

A: Hint: If you write $f(x) = \frac{1+x}{1-x}$ and $g(x) = \tan x$, then your function is $h(x)=(f\circ g)(x)$. This function can have a discontinuity wherever $g$ does, and also wherever $g$ takes a value which is a point of discontinuity of $f$.


text:
Q: calling a struct member declared in a class I am trying to place functions inside a struct which is part of a class (here named menu) so I can modify the struct inside of a dedicated setup cpp file (I am trying to do this so I can modify all of the functions I want in my application in a single source file instead of changing stuff in  all of my cpp files):
// Menu.h
class menu
{
public:
    menu();

    struct pages
    {
        void print_page_1();
        void print_page_2();
    };
};

// Setup.cpp
struct menu::pages
{
    void print_page_1()
    {
        // ...
    }
    void print_page_2()
    {
        // ...
    }
};

Then I get an error when trying to call a function within my struct:
int main()
{
    menu myMenu();
    myMenu.pages.print_page_1(); // error: type name is not allowed
}

What does this error mean and how can I avoid it?
Thank you!

A: pages is the name of the struct, it's not an object. You need an object of type pages inside menu.
Otherwise, you can have static methods inside pages and call those without creating objects.
Example (live):
#include <iostream>

struct S
{
    struct P
    {
        void print()
        {
            std::cout << "Hello from P!\n";
        }
    } p; // object of P

    struct Q
    {
        static void print()
        {
            std::cout << "Hello from Q!\n";
        }
    };
};

int main()
{
    S s;
    s.p.print();

    S::Q::print();

    return 0;
}

Output:
Hello from P!
Hello from Q!

A: You need to declare a pages object in menu.
  #include <iostream>

class menu
{
    std::string p1 = "1";
    std::string p2 = "2";
  public:

 struct pages
  {
      menu& m;
      pages(menu &m):m(m){

      }
   void print_page_1();
   void print_page_2();
  } pages;

  menu():pages(*this){
  }
};

    void menu::pages::print_page_1()
    {
     std::cout << m.p1;// ...
    }
    void menu::pages::print_page_2()
    {
      std::cout << m.p2;// ...
    }

int main() {
    menu myMenu;
    myMenu.pages.print_page_1();
    // your code goes here
    return 0;
}


text:
Q: Why is $2^{\mathbb{N}}$ Homeomorphic to $2^{\mathbb{N}^{< \mathbb{N}}}$? This question is based off a problem from Classical Descriptive Set Theory by Kechris. In this book, Kechris makes the claim that, when $\{0, 1\}$ is endowed with the discrete topology, then the Cantor space $\{0, 1\}^{\mathbb{N}}$ is homeomorphic to the set $\{0, 1\}^{\mathbb{N}^{<\mathbb{N}}}$ (both endowed with the product topology). I am struggling to see why this is true, and I cannot think of an explicit homeomorphism between the two spaces. Could someone explain why this is the case?

A: Let $I.J$ be infinite index sets. Then $\{0,1\}^I \simeq \{0,1\}^J$ (as spaces) iff the sets $I$ and $J$ have the same cardinality. A shuffle of
coordinates is a homeomorphism (if $f: I \to J$ is a bijection, $\hat{f}: \{0,1\}^J \to \{0,1\}^I$ defined by $\hat{f}(g)=g \circ f$ is a homeomorphism)
For the reverse note that the weight of $\{0,1\}^I$ equals $|I|$ and weight ( the minimal size of a base) is a topological invariant.


text:
Q: Forward cache for large storage provider I have a web server with an NFS mount to a large storage provider, and it serves content via HTTP.
I would like to have a 1-2 GB dynamic forward cache so that if my NFS mount goes down, I can still provide my most common accessed content without the user even knowing.
I either can't find the concept with Google, or I'm not using the correct search terms to find it.
The cache could be in Apache or NFS or a Virtual File System on top of the mount -- I don't care!  I just want to control what can be cached (inodes - file info and structure; and common files under 10 MB).
Any suggestions?
Terry.

A: You didn't mention what operating system you're using.
Linux: See the Wikipedia page for CacheFS, which has some information and links to a relevant mailing list. The project seems to be a bit moribund, and so I don't know how well the code works; I've never used it myself.
Solaris: Solaris had CacheFS for quite a while, but the feature was removed in 2008.
I don't think the BSDs have a filesystem-level solution available.
The better approach would probably be to put a reverse proxy in front of your webserver and set it up to cache content. The proxy and the actual webserver could live on the same machine, even. It is something of a kludgy architecture, but it will work, up to a point. The mod_proxy documentation talks about how to set up a reverse proxy.


text:
Q: Update the code for a Bitbucket pull request (Mercurial) I want to update a pull request created on a Mercurial (hg) Bitbucket repository with new code. Is this possible?
I tried hg push -f on the branch, but it created a new head and the old one still exists. The PR still points to the previous commit.
Is there any way from the web UI to point the existing PR to a new head?

A: This is abnormal, because it works without hg push -f.
Just doing hg push --branch name_of_pull_request_branch_of_harald should be enough.
Now, you could try to edit your pull request using the BitBucket website. Use the Edit button, between the Merge and Decline buttons, there you can select the updated branch.

A: To update a pull request in bitbucket, all you need to do is push an additional commit to the branch the pull request is for in your fork.
In your case, it sounds like you need to merge the new head with the one the pull request is pointing to and then push that to your fork. This should update the pull request with whatever you've changed.


text:
Q: NaN result calculating date diff I am trying to calculate the number of days between two dates.
I have the number of days calculated in Chrome, Mozilla FireFox, and IE, but not in Safari. Safari says NaN. I have used Date.js and gave Date.parse but no luck.
Here is the code. I am trying to get number of days between 2 Dates.
angular.forEach($scope.tickets ,
  function(ticket) {
    ticket['noOfOpenDays'] = Math.floor(((new Date() - new Date(ticket.CreationDate))/(1000*60*60*24))) + 1;
    ticket['display'] = false;

    if(ticket.ActualCloseDate) {
        ticket['noOfDelivDays'] = Math.floor(((new Date(ticket.ActualCloseDate)-new Date(ticket.CreationDate))/(1000*60*60*24))) + 1;
    }
    else {
        ticket['noOfDelivDays'] = "N/A";
    }
});


text:
Q: Maximum of two normal random variables The main purpose of the following question is to get some intuition and deeper understanding why the presented method works which would hopefully help me in trying to adapt it to the setting I am dealing with in my research.
Let $X,Y\sim N(0,1)$, not necessarily independent. Suppose we want to find an upper bound for $\mathbb{E}\max(X,Y)$.
The most obvious approach would be something like the following
$$\mathbb{E}\max(X,Y)\leq \mathbb{E}|X|+\mathbb{E}|Y|=2\sqrt{2/\pi}\approx 1.59$$
However, I've found the trick in the literature that uses Laplace transform to get something better. Although the idea is much less obvious, details are still easy. For any $\lambda >0$, Jensen's inequality gives us the following
$$\mathbb{E}\max(X,Y) \leq \frac1{\lambda}\log\left(\mathbb{E}e^{\lambda\max(X,Y)}\right)\leq \frac1{\lambda}\log\left(\mathbb{E}e^{\lambda X}+\mathbb{E}e^{\lambda Y}\right) = \frac{\log(2e^{\lambda^2/2})}{\lambda}.$$
Minimizing this gives us the upper bound $\log(4) \approx 1.17$, which is better than the previous approach.
Now, my question is, heuristically/intuitively, why is second method better? Or to put in a different way, is there some easy way to see that the second method should give a better bound even before doing the actual calculations that confirm this?
At this stage, I don't have any intuition for why this works, and I am certainly not fine with that's the standard trick researchers in the field use.

A: What should be really done is as follows. Suppose that $X_1,\dots,X_n$ are any real random variables for which individual distribution laws are known but no information is given on the joint distribution law. Choose $t$ such that $\sum_jP(X_j>t)\le 1\le \sum_jP(X_j\ge t)$. Then $E\max(X_j)\le t+\sum_jE(X_j-t)_+$ and the bound is the best possible.
I wonder when we will finally realize that if somebody has trouble finding the antiderivative of $\frac{x+1}{x^2\sqrt{x^2+4}}$, this will, most likely, never affect his work in mathematics, but if somebody doesn't see things like this one, his education has been thoroughly screwed up. When shall we stop teaching calculus and start teaching analysis at least at the most basic level?
I apologize for the rant, but there is a limit to everything. I do not blame the students, but I'd like everyone who comes to the class with a book by Stewart in hand think of this thread a bit before coming to the blackboard.

A:
Given: $X \sim N(0,1)$ and $Y \sim N(0,1)$ where $X$ and $Y$ may be correlated.

If we assume that the underlying Normals are jointly Normal, then (a) the exact answer is quite simple, and (b) we can do much better, conditioning the maximum bound on the correlation coefficient. In particular, if $(X,Y)$ are bivariate Normal with correlation $\rho$, then the joint pdf $f(x,y)$ is:

Then, $E\big[Max[X,Y]\big]$ is:

where I am using the Expect function from the mathStatica package for Mathematica to automate the nitty gritties. Plainly, the expected maximum is contingent on $\rho$, as a quick plot illustrates:

As @oferzeitouni noted, the maximum possible value is $\sqrt{\frac{2}{\pi}}$, which is attained when $\rho = -1$.

A: First, an upper bound that beats your second bound is the following: use the equality
$$\max(a,b)=(a+b+|a-b|)/2.$$
Then
$$E\max(X,Y)=E|X-Y|/2\leq \frac{1}{2} (E|X|+E|Y|)=E|X|=\sqrt{2/\pi}\sim 0.798$$
This bound cannot be improved as the case $Y=-X$ shows.
So you see that your second bound is better not because you used the exponential moments, but rather because your first bound controls the max function way too brutally - you lost a factor of $2$. The advantage of the second method over the little trick I showed above is that it generalizes better when you deal with the max of more than two variables.


text:
Q: $x^{2} \equiv-1\ \pmod p$ has a solution if and only if $p\equiv 1\ \pmod 4$ If $p$ is a prime. Then $x^{2} \equiv-1\ \pmod p$ has a solution if and only if $p\equiv 1\ \pmod 4$. Please explain in the easiest way.

A: I assume you mean odd primes.
If $$p \equiv 1 \pmod 4 \Rightarrow \left(\left(\frac{p-1}{2}\right)!\right)^2 \equiv -1 \pmod p (\because \text{Wilson's Theorem})$$ So we have shown that if $p \equiv 1 \pmod 4$, $x^2 \equiv -1 \pmod p$ exists.
Now let us show that if $x^2 \equiv -1 \pmod p$, then $p \equiv 1 \pmod 4$. If $$x^2 \equiv -1 \pmod p \Rightarrow (x^2)^{\frac{p-1}{2}} \equiv (-1)^{\frac{p-1}{2}} \equiv 1 \pmod p $$ By Fermat's Little Theorem.
Thus we have $\frac{p-1}{2} \equiv 0 \pmod 2$, and $p \equiv 1 \pmod 4$.

A: Here is a simple proof using group theory and the fact that $U(p)$ is cyclic. Assume $p$ is odd.
$x^{2} \equiv-1 \bmod p$ has a solution if and only if $U(p)$ has an element of order $4$.
Since $U(p)$ is a cyclic group, this happens iff $4$ divides the order of $U(p)$, which is $p-1$.


text:
Q: Taylor polynomials in Fourier Domain? Which types of functions admit Taylor polynomials in the Fourier domain?
Ok, this may sound cryptic. Therefore I will try to explain it more in depth.
We want to approximate function
$$x\to f(x) \text{ around } x_0 \to f(x_0)$$
We can look at normal Taylor polynomials first:
$$p_N(x) = \sum_{k=0}^{N}\frac{f^{(k)}(x_0)}{k!} (x-x_0)^k$$
Here all is fun and games and we see that we have well defined coefficients $$c_k=\frac{f^{(k)}(x_0)}{k!}$$
which probably are derived in your first Uni course on calculus.
But what if we instead use trigonometric polynomials?
$$p_N(x) = \sum_{k=0}^{N}a_k \sin(x-x_0)^k+ b_k\cos(x-x_0)^k$$
Can we derive which $a_k$, $b_k$ would do a best fit "close to" $x_0$?
Also, in what sense would this expansion be a "best fit" (for given number of terms $N+1$)?


text:
Q: Globbing fails in zsh, but works in bash I have an alias in bash, that I'm trying to port over to zsh. I thought it may have been the alias itself, but now it seems it's just the globbing.
grep -irl --exclude=\*.{log,class,fuegoclass,dat}* --exclude-dir={build,system,lib} data

What's the right way to exclude these file extensions and directories in zsh?

A: In:
grep -irl --exclude=\*.{log,class,fuegoclass,dat}* --exclude-dir={build,system,lib} data

In both zsh and bash, --exclude=\*.{log,class,fuegoclass,dat}* expands first to --exclude=\*.log* --exclude=\*.class* --exclude=\*.fuegoclass* --exclude=\*.dat* and then, because of the unquoted *, each is treated as a pattern to perform globbing on.
For instance, --exclude=\*.log* will expand to the list of files in the current directory whose name starts with --exclude=*.log.
If any of the globs has no match, in zsh, the command will be aborted. In bash, the globs will expand to themselves.
Here, you don't want globbing so you should quote all the globbing characters (in both zsh and bash, zsh is just kind enough to point your mistake to you).
grep -irl --exclude=\*.{log,class,fuegoclass,dat}\* --exclude-dir={build,system,lib} data


text:
Q: Combine a two dimensional array of items I have an set of array like this [ [1,2],  [2, 3],  [4,5],  [5, 6,],  [7, 8], [1,8,9]].if one item intersect with another then union those items.But I get duplicate items like [[1,2], [2,3], [1,8,9],[1,2,3,8,9][4,5],[5,6], [4,5,6],[7,8]], Where those set of items [1,2],[2,3][1,8,9],[4,5],[5,6],[7,8] are duplicate.
I tried to use reduce method but the output I expected still didn't get it.
   var newtotalOverlapingSet = Set<[UICollectionViewLayoutAttributes]>()

    if totoalOverLapArray.count > 0{
     let _ = totoalOverLapArray.reduce(totoalOverLapArray[0]){ firstSet, secondSet  in

            if firstSet.intersection(secondSet).count > 0{
                newtotalOverlapingSet.insert(Array(firstSet.union(secondSet)))
                return firstSet.union(secondSet)
            }
            return secondSet
        }}

Here is my expected output  [[1,2,3,7,8,9], [4, 5, 6] ] want to achieve.

A: Create an empty array result with type [[Int]]. If intersection of current Set with any element of result is not empty, update the Set with its union. Else append the Set in result array.
func group(arr: [[Int]]) -> [[Int]] {
    if (arr.reduce(0) { $0 + $1.count }) == Set(arr.reduce([Int](), +)).count {
        return arr
    }
    let result = arr.reduce(into: [[Int]]()) { (result, subArr) in
        if let index = result.firstIndex(where: { !Set($0).intersection(subArr).isEmpty }) {
            result[index] = Set(result[index]).union(subArr).sorted()
        } else {
            result.append(Array(subArr))
        }
    }
    return group(arr:result)
}

Call this method with the array
let arr1 = [[1,2], [2, 3], [4,5], [5, 6,], [7, 8], [1,8,9]]
print(group(arr: arr1))

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

let arr2 = [[1, 2], [2, 3], [4, 5], [5, 6], [7, 8], [1, 8, 9], [10, 9], [9, 6]]
print(group(arr: arr2))

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

A: Try this code:
func combine(input: [[Int]]) -> [[Int]] {
    return input
        .reduce([Set<Int>]()) { acc, elem in
            let set = Set(elem)
            return acc.firstIndex { !$0.isDisjoint(with: set) }
                .map { index in
                    acc.enumerated().compactMap {
                        if $0.offset == index {
                            return acc
                                .filter { !$0.isDisjoint(with: set) }
                                .reduce(Set()) { $0.union($1) }
                                .union(set)
                        }
                        return $0.element.isDisjoint(with: set) ? $0.element : nil
                    }
                } ?? acc + [set]
        }
        .map { Array($0).sorted() }
}

A: Just for fun, tried to stick with reduce:
func mergeIntersections(of arrays: [[Int]]) -> [Set<Int>] {
    return arrays.reduce([Set<Int>]()) { result, nextChunk in
        let partialResult = result.reduce(into: (mergedChunk: Set(nextChunk), unmergedChunks: [Set<Int>]())) { (result, existingChunk) in
            if !result.mergedChunk.intersection(existingChunk).isEmpty {
                result.mergedChunk.formUnion(existingChunk)
            } else {
                result.unmergedChunks.append(existingChunk)
            }
        }

        return partialResult.mergedChunk.isEmpty
            ? partialResult.unmergedChunks
            : partialResult.unmergedChunks + [partialResult.mergedChunk]
    }
}

let arraysOfInts = [[1,2], [2,3], [4,5], [5,6], [7,8], [1,8,9]]
mergeIntersections(of: arraysOfInts) // [{6, 4, 5}, {2, 1, 7, 8, 9, 3}]

But the part I'm really curious about is, how is it related to UICollectionViewLayoutAttributes? :-)


text:
Q: Command payload validation in event sourced micro-service architecture I am confused about how to realize the data validation in event sourced micro-service architecture.
Let sum up some aspects that related to the micro-services.
1. Micro-services must be low coupled.
2. Micro-services better to be domain oriented
Then due to tons of materials in the internet and the books in DDD (Domain Driven Design)
I create the next event sourced micro-service architecture.
Components
1. API getaway to receive the REST calls from the clients and transform them into the commands.
2 Command handler as a service. Receive the commands from API getaway make the validations. Save the events to the event store and publish events to the event bus.
3. Event store is the storage for all events in the system. Allows us to recreate the state of the app. The main state of truth.
4. Micro-services is small services responsible to handle the related to its domain event. Make some projections to the local private databases. Make some events too.
And I have questions that I could not answer both by myself and the internet.
1. What is actually aggregates. They are the class objects/records in databases as I think or what?
2. Who carry about aggregates. I found example that is some cases command handler use them. But in that way if aggregates stored in the private micro-services databases then we will have very high coupling between the command handler and the each of micro-services and it is wrong due to micro-service concept.
To sum up.
I am confused about how to implement aggregation in event source micro service architecture.
For example let focus on the user registration implementation in event source micro-service architecture.
We have the user domain so the architecture will be next.
API getaway
Command handler
Auth micro-service
User micro-service
Please explain me the realization of command validation due to example above.

A:
Command handler as a service

I think this is the main source of your confusion.
The command handler isn't normally a service in itself.  It is a pattern.  It will normally be running in the same process as the "microservice" itself.
IE: the command handler reads a message from so storage, and itself invokes the microservice logic that computes how to integrate the information in this message into its own view of the world.

What is actually aggregates

"Aggregate" is a lifecycle management pattern; an aggregate is a graph of one or more domain entities that together will establish and maintain some interesting invariant.  It's one of three patterns described in detail in the Domain Driven Design book written by Eric Evans.
The command handler plus your aggregate is, in a sense, your microservice.  The microservice will typically handle messages for several instances of a single aggregate - it will subscribe to all of the input messages for that kind of aggregate.  The "handler" part just reads the next message, loads the appropriate instance of the aggregate, then executes the domain logic (defined within the aggregate entities) and stores the results.


text:
Q: Title of UIContextualAction does not show full of text I create an UIContextualAction in table view cell which shows a long text but it works wrong. The title shows text with: The sample of text...
If I use UITableViewRowAction for swiping action in table view cell. The title shows full in ios 10 and gets wrong in ios 11+
I have broken down lines in the text with "\n"
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *warningMessage = @"This is the title of UITablViewRowAction \nin table view cell.";
UITableViewRowAction *warningAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                         title:warningMessage
                                                                       handler:
                                       ^(UITableViewRowAction *action, NSIndexPath *indexPath){
    //do nothing
}];

return @[warningAction];

}
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath  API_AVAILABLE(ios(11.0)) {
NSString *warningMessage = @"This is the title of UIContextualAction \nin table view cell.";

UIContextualAction *warningAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:warningMessage
                                                                          handler:
                                     ^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
    // action
}];

UISwipeActionsConfiguration *configuration = [UISwipeActionsConfiguration configurationWithActions:@[warningAction]];

configuration.performsFirstActionWithFullSwipe = NO;
return configuration;

}
Here are the pictures.
Could anybody help me on this issue?. Thank you so much.
ios10
ios11


text:
Q: CSS - break long list into columns by height I'm trying to create a multi-column list but the result I'm getting is not the desired.
In this example, I need to break the right list into a 2nd column at when the height reaches i.e. 400px and the same with the rest of the <li> elements (in the link above, I want to break the column into 2 after "BABY GIFTS" and put "MEN" in the second column.
I've tested many things such as this Is there a way to break a list into columns? and this but it doesn't create the column where I want.
Here's the result I'm after  and here's a JSFiddle
Any suggestions?

A: The solutions in both questions you've referenced that involve the columns property work as they should.  Your content can't split where you want it to because the 400px cutoff is too small.
http://jsfiddle.net/HVZkG/1/
#productsitemap {
    -webkit-columns: 3;
    -moz-columns: 3;
    columns: 3;
    height: 400px;
}


text:
Q: Cast type returned by a function in python When we have a function that returns an object that is an instance of a class. Are there any way to cast or tell the compiler that this object returned is an instance of MyClass so the warning is avoided?
Or are there any other pythonic way to do it?
def dict_to_class_instance (my_dict, type_class) -> object
    # some processing
    return type_class(**my_dict_converted)

def caller (my_dict) -> MyClass
    process_dict(my_dict, MyClass) # Warning: Expected type 'MyClass', got 'object' instead


text:
Q: style not working when browsing though domain When i brows website using its ip address the style loading fine. But when i try to do it using domain name then style not working. The interesting thing is that i have checked both output html, css source for code and they are 100% same. Then why browser not showing style in domain mode?
direct ip browse- view-source:http://22.199.66.33/
domain browse- view-source:https://www.ogibogi.com/
here i checked both source output code- https://www.diffchecker.com/diff
Any idea how to fix it?
Note: i am using cloudflare with domain.
Note: that this is happening after changing hosting server.

A: Check the output in your browser's console. There's mixed content error.

Refer to Cloudflare KB on how to troubleshoot mixed content error.
An easy fix is to enable "Always Use HTTPS" and "Automatic HTTPS Rewrite".

A: The answer from Faiz is correct. Go to the crypto tab and set Automatic HTTPS rewrites to on. But, that will not affect stylesheets or javascript files. And, you have two missing scripts and one missing css file.
To correct those, you'll need to use a relative reference. If you're calling an asset with a full URL, like , you would want to change this to . By removing the http:, the browser will use whichever protocol the visitor is already using. And, on the crypto tab, if you set Always use https to on, that protocol will be https.


text:
Q: Generar Totales de forma Vertical SQL SERVER 2014 Este es el select usando PIVOT
select codp, Anho, isnull([1],0) as Enero,
isnull([2],0) as Febrero,
isnull([3],0) as Marzo,
isnull([4],0) as Abril,
isnull([5],0) as Mayo,
isnull([6],0)as Junio,
isnull([7],0) as Julio,
isnull([8],0) as Agosto,
isnull([9],0)as Septiembre,
isnull([10],0)as Octubre,
isnull([11],0)as Noviembre,
isnull([12],0) as Diciembre,
isnull([1],0)+isnull([2],0)+isnull([3],0)+isnull([4],0)+isnull([5],0)+isnull([6],0)+isnull([7],0)+isnull([8],0)+isnull([9],0)+isnull([10],0)+isnull([11],0)+
isnull([12],0) as Totales
from (  select codp, year(t.fecha) as Anho, MONTH(t.fecha) as Mes, t.recaudacion as Recaudacion
    from TAQUILLA t
    where year(t.fecha) = 1991)
    as aux
pivot (sum(Recaudacion)
for Mes in ([1],[2], [3], [4], [5], [6], [7], [8], [9], [10],[11], [12])) as pvt

El cual me trae el resultado total por código (cod) de película de todos los meses
Ahora necesito que me sume toda la fila de Enero y me muestre la suma abajo
como en la siguiente imagen

A: Para lograr esa forma de calculo se tienen que seguir los siguientes pasos:

*

*Tu tabla tiene que estar como la siguiente imagen pueden ser una temporal como la que he creado TMP_RECAUDACION:

*Ejecutar el siguiente script:

DECLARE @COLUMNASISNULL NVARCHAR(MAX),@COLUMNAS NVARCHAR(MAX),@COLUMNASSUM NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @COLUMNASISNULL = STUFF(
(
    SELECT ',ISNULL(' + QUOTENAME(MES) + ','''') AS '+QUOTENAME(MES)
    FROM
    (
  SELECT DISTINCT
               MES,NRO_MES
        FROM TMP_RECAUDACION AS S
    ) AS x ORDER BY X.NRO_MES FOR XML PATH('')
), 1, 1, '');

SET @COLUMNAS = STUFF(
(
    SELECT ',' + QUOTENAME(MES)
    FROM
    (
  SELECT DISTINCT
               MES,NRO_MES
        FROM TMP_RECAUDACION AS S
    ) AS x ORDER BY X.NRO_MES FOR XML PATH('')
), 1, 1, '');

SET @COLUMNASSUM = STUFF(
(
    SELECT ',SUM(' + QUOTENAME(MES)+')AS '+QUOTENAME(MES)
    FROM
    (
  SELECT DISTINCT
               MES,NRO_MES
        FROM TMP_RECAUDACION AS S
    ) AS x ORDER BY X.NRO_MES FOR XML PATH('')
), 1, 1, '');

SET @sql = N'
SELECT ISNULL(CONVERT(VARCHAR(10), COATI), '''') AS COATI,
       ISNULL(CONVERT(VARCHAR(10), ANO), ''Totales'') ANO,
       ' + @COLUMNAS + '
FROM
(
    SELECT COATI,
           ANO,
           GROUPING(ANO) AS G_ANO,
            ' + @COLUMNASSUM + '
    FROM
    (
        SELECT PV.COATI,
               PV.ANO,
               ' + @COLUMNASISNULL + '
        FROM
        (
            SELECT *
            FROM TMP_RECAUDACION AS S
        ) AS TP PIVOT(SUM(RECAUDACION) FOR MES IN(' + @COLUMNAS + ')) AS PV
    ) AS X
    GROUP BY COATI,
             ANO WITH ROLLUP
) AS X2
WHERE(X2.G_ANO = 0
      OR X2.COATI IS NULL);
';
PRINT @sql;
EXEC sp_executesql @sql;

quedara de la siguiente manera:

A: Necesitas explotar tu consulta dos veces, una para el detalle y otra para los totales. Puedes aprovechar que a partir de SQL Server 2005 se introdujo lo que se conoce como COMMOM TABLE EXPRESSION.
;WITH CTE AS (
    Select  codp,
            Anho,
            isnull([1],0) as Enero,
            isnull([2],0) as Febrero,
            isnull([3],0) as Marzo,
            isnull([4],0) as Abril,
            isnull([5],0) as Mayo,
            isnull([6],0)as Junio,
            isnull([7],0) as Julio,
            isnull([8],0) as Agosto,
            isnull([9],0)as Septiembre,
            isnull([10],0)as Octubre,
            isnull([11],0)as Noviembre,
            isnull([12],0) as Diciembre,
            isnull([1],0)+isnull([2],0)+isnull([3],0)+isnull([4],0)+isnull([5],0)+isnull([6],0)+isnull([7],0)+isnull([8],0)+isnull([9],0)+isnull([10],0)+isnull([11],0)+
                isnull([12],0) as Totales
            from (select codp,
                        year(t.fecha) as Anho,
                        MONTH(t.fecha) as Mes,
                        t.recaudacion as Recaudacion
                    from TAQUILLA t
                    where year(t.fecha) = 1991
                ) as aux
            pivot (sum(Recaudacion) for Mes in ([1],[2], [3], [4], [5], [6], [7], [8], [9], [10],[11], [12])) as pvt
)
SELECT  codp,
        CONVERT(VARCHAR(10),Anho) AS 'Anho',
        Enero,
        Febrero,
        Marzo,
        Abril,
        Junio,
        Julio,
        Agosto,
        Septiembre,
        Octubre,
        Noviembre,
        Diciembre,
        1 as Orden
        FROM CTE

UNION

SELECT  NULL
        'totales'       AS 'detalle',
        SUM(Enero),
        SUM(Febrero),
        SUM(Marzo),
        SUM(Abril),
        SUM(Junio),
        SUM(Julio),
        SUM(Agosto),
        SUM(Septiembre),
        SUM(Octubre),
        SUM(Noviembre),
        SUM(Diciembre),
        2 as orden
        FROM CTE
        GROUP BY codp
        ORDER BY orden

Lo que hacemos, básicamente es darle un alias a tu consulta original y aprovecharlo para obtener el detalle original y luego mediante un UNION agregar los totales.
Sin este tipo de clausula, también se puede resolver, pero con algo más de trabajo, ya que deberíamos en primer lugar insertar los datos en una tabla temporal para luego si, aprovecharlos tanto para el detalle como para los totales

A: Una de las razones por las que evito usar la instrucción PIVOT es por la poca flexibilidad que ofrece comparado con la alternativa que tenemos disponible desde antes del 2000.
Una de las ventajas, es la capacidad de utilizar las opciones avanzadas de GROUP BY que permiten organizar mejor nuestros datos y evitar tener que leer la tabla más de una vez. Verás que he cambiado tu consulta pero los datos se mantienen constantes.
WITH ctePreAgregadoTaquilla AS(
    --Uso un preagregado porque suele incrementar el rendimiento durante el pivoteo de datos
    SELECT t.codp,
        YEAR( t.fecha) AS Anho,
        MONTH( t.fecha) AS Mes,
        SUM(t.recaudacion) AS Recaudacion
    FROM Taquilla t
    WHERE t.fecha >= '19910101' --Usar rangos en vez de funciones sobre columnas
    AND t.fecha < '19920101'    --Eso permite que se pueda utilizar un índice y estadísticas en caso de existir.
    GROUP BY t.codp,
        YEAR( t.fecha),
        MONTH( t.fecha)
)
SELECT ISNULL( CAST( codp AS varchar(10)), 'Total') AS codp,
    Anho,
    SUM( CASE WHEN Mes =  1 THEN Recaudacion ELSE 0 END) AS Enero,
    SUM( CASE WHEN Mes =  2 THEN Recaudacion ELSE 0 END) AS Febrero,
    SUM( CASE WHEN Mes =  3 THEN Recaudacion ELSE 0 END) AS Marzo,
    SUM( CASE WHEN Mes =  4 THEN Recaudacion ELSE 0 END) AS Abril,
    SUM( CASE WHEN Mes =  5 THEN Recaudacion ELSE 0 END) AS Mayo,
    SUM( CASE WHEN Mes =  6 THEN Recaudacion ELSE 0 END) AS Junio,
    SUM( CASE WHEN Mes =  7 THEN Recaudacion ELSE 0 END) AS Julio,
    SUM( CASE WHEN Mes =  8 THEN Recaudacion ELSE 0 END) AS Agosto,
    SUM( CASE WHEN Mes =  9 THEN Recaudacion ELSE 0 END) AS Septiembre,
    SUM( CASE WHEN Mes = 10 THEN Recaudacion ELSE 0 END) AS Octubre,
    SUM( CASE WHEN Mes = 11 THEN Recaudacion ELSE 0 END) AS Noviembre,
    SUM( CASE WHEN Mes = 12 THEN Recaudacion ELSE 0 END) AS Diciembre,
    SUM( Recaudacion) AS Totales
FROM ctePreAgregadoTaquilla
--En vez de tener una lectura adicional a la tabla, se especifica como se agruparán los datos.
GROUP BY GROUPING SETS(codp, Anho), (Anho);

Aquí abajo agrego el código de creación y llenado de la tabla con un millón de filas para quien quiera comprobar el rendimiento. Según mis pruebas, hay una mejora de casi 3 veces mayor rapidez con el método original y hasta entre 5 y 8 veces más rapidez con las otras soluciones.
CREATE TABLE Taquilla(
    codp        int,
    fecha       date,
    recaudacion float
)
GO
INSERT INTO Taquilla
SELECT TOP(1000000)
        ABS(CHECKSUM(NEWID())) % 5 + 1,
       DATEADD( DD, ABS(CHECKSUM(NEWID())) % 365, '1991'),
       ABS(CHECKSUM(NEWID())) % 100000
FROM sys.all_columns a, sys.all_columns b;
GO

A: Con esto resolví el problema
WITH
totales (codp,anho,Enero,Febrero,Marzo,Abril,Mayo,Junio,Julio,Agosto,Septimbre,Octubre,Noviembre,Diciembre,Totales) AS
 (Select  codp,
        Anho,
        isnull([1],0) as Enero,
        isnull([2],0) as Febrero,
        isnull([3],0) as Marzo,
        isnull([4],0) as Abril,
        isnull([5],0) as Mayo,
        isnull([6],0)as Junio,
        isnull([7],0) as Julio,
        isnull([8],0) as Agosto,
        isnull([9],0)as Septiembre,
        isnull([10],0)as Octubre,
        isnull([11],0)as Noviembre,
        isnull([12],0) as Diciembre,
        isnull([1],0)+isnull([2],0)+isnull([3],0)+isnull([4],0)+isnull([5],0)+isnull([6],0)+isnull([7],0)+isnull([8],0)+isnull([9],0)+isnull([10],0)+isnull([11],0)+
        isnull([12],0) as Totales
        from (select codp,
                    year(t.fecha) as Anho,
                    MONTH(t.fecha) as Mes,
                    t.recaudacion as Recaudacion
                from TAQUILLA t
                --where year(t.fecha) = 1991
            ) as aux
        pivot (sum(Recaudacion) for Mes in ([1],[2], [3], [4], [5], [6], [7], [8], [9], [10],[11], [12])) as pvt),

detalles (codp, anho,Enero,Febrero,Marzo,Abril,Mayo,Junio,Julio,Agosto,Septimbre,Octubre,Noviembre,Diciembre,totales) as
(select CODP, ANHO, ISNULL([1],0)ENERO,
ISNULL([2],0)FEBRERO,
ISNULL([3],0)MARZO,
ISNULL([4],0)ABRIL,
ISNULL([5],0)MAYO,
ISNULL([6],0)JUNIO,
ISNULL([7],0)JULIO,
ISNULL([8],0)AGOSTO,
ISNULL([9],0)SEPTIEMBRE,
ISNULL([10],0)OCTUBRE,
ISNULL([11],0)NOVIEMBRE,
ISNULL([12],0)DICIEMBRE,
/*TOTAL*/

ISNULL([1],0)+ISNULL([2],0)+ISNULL([3],0)+ISNULL([4],0)+ ISNULL([5],0)+ISNULL([6],0)+ISNULL([7],0)+ISNULL([8],0)+
ISNULL([9],0)+ISNULL([10],0)+ISNULL([11],0)+ISNULL([12],0) AS TOTAL

from (
    SELECT CODP,YEAR(FECHA) ANHO ,MONTH(FECHA) MES, SUM(RECAUDACION) as rec
    FROM TAQUILLA
    --where codp is not null
    GROUP BY grouping sets(CODP,YEAR(FECHA),MONTH(FECHA))
    having YEAR(FECHA) IS NULL --AND MONTH(FECHA) IS NULL
    and codp is null

    ) AS TABLA

PIVOT
(
    sum(REC)
    FOR MES IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) as P)

select convert(varchar(10),t.codp) as codp,convert(varchar(10),t.anho) as Anho,t.Enero,t.Febrero,t.Marzo,t.Abril,t.Mayo,t.Junio,t.Julio,t.Agosto,t.Septimbre,t.Octubre,t.Noviembre,t.Diciembre,t.Totales
from totales t

union

select ' ' as codp,'Totales',d.Enero,d.Febrero,d.Marzo,d.Abril,d.Mayo,d.Junio,d.Julio,d.Agosto,d.Septimbre,d.Octubre,d.Noviembre,d.Diciembre,d.Totales
from detalles d
order by totales
go


text:
Q: make request to get JSON without params in Android application tab activity I want to get JSON from this link in my android application. As you see ,the objects have no param or name as usual, how can i retreive data to post it in my application?
here is my JSONParser.class
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

and this is how i'm trying to retrieve and place data in my tab content
public class TabTwo extends Activity {
TextView txtType;
TextView txtFilename;
TextView txtOriginal;

// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile json object
JSONObject image;
// Profile JSON url

private static final String IMAGE_URL = "http://dbt.promote.az/getUserFiles.php?user_id=1&type=image";
// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_TYPE = "type";
private static final String TAG_FILENAME = "filename";
private static final String TAG_ORIGINAL = "original";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tab_two);

    txtType = (TextView) findViewById(R.id.type);
    txtFilename = (TextView) findViewById(R.id.filename);
    txtOriginal = (TextView) findViewById(R.id.original);

    // Loading Image in Background Thread
    new LoadImage().execute();
}

/**
 * Background Async Task to Load profile by making HTTP Request
 * */
class LoadImage extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(TabTwo.this);
        pDialog.setMessage("Loading profile ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Profile JSON
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // getting JSON string from URL
        JSONObject json = jsonParser.makeHttpRequest(IMAGE_URL, "GET",
                params);

        // Check your log cat for JSON reponse
        Log.d("Profile JSON: ", json.toString());

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                // Storing each json item in variable
                try {
                    String id = image.getString(TAG_ID);
                    String type = image.getString(TAG_TYPE);
                    String filename = image.getString(TAG_FILENAME);
                    String original = image.getString(TAG_ORIGINAL);

                    // displaying all data in textview
                    txtType.setText(type);
                    txtFilename.setText("Filename: " + filename);
                    txtOriginal.setText("Original: " + original);

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.tab_two, menu);
    return true;
}

Any suggestions?

A: You need to create a JSONArray from the string response
JSONArray jArray = new JSONArray(json);

Then retrieve the JSONObjects
for(int i=0;i<jArray.length();i++)
{
    JSONObject obj = jArray.getJSONObject(i);
}

A: Try this way,hope this will help you to solve your problem.
Instead of getting JSONArray or JSONObject from  makeHttpRequest return String response :
static String json = "";

public String makeHttpRequest(String url, String method,List<NameValuePair> params) {
   ......
   ......
   return json;
}

Pass String response to onPostExecute() which getting from makeHttpRequest.
protected String doInBackground(String... args) {
   // Building Parameters
   List<NameValuePair> params = new ArrayList<NameValuePair>();

   String response = jsonParser.makeHttpRequest(IMAGE_URL, "GET",params);

   return response;
}

Prepare data in onPostExecute() after from response;
protected void onPostExecute(String response) {
    if(pDialog!=null&&pDialog.isShowing()){
         pDialog.dismiss();
    }
    ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
    try{
            JSONArray jsonArray = new JSONArray(response);
            for (int i=0;i<jsonArray.length();i++){
                HashMap<String,String> rowData = new HashMap<String, String>();
                rowData.put("id",jsonArray.getJSONObject(i).getString("id"));
                rowData.put("type",jsonArray.getJSONObject(i).getString("type"));
                rowData.put("filename",jsonArray.getJSONObject(i).getString("filename"));
                rowData.put("extension",jsonArray.getJSONObject(i).getString("extension"));
                rowData.put("original",jsonArray.getJSONObject(i).getString("original"));
                data.add(rowData);
            }

     }catch (Throwable e){
        e.printStackTrace();
     }

     // Use data as per your requirement.
}


text:
Q: match.arg() does not see an object declared in the other file (package development) Given is a package with two files. In the first file I declare a variable (possible values), in the second I declare a function, which uses this variable as possible values for its argument.
# file1.R
pdfs <- c("norm", "t")

And the second file:
# file2.R
f <- function(pdf = pdfs) {
    pdf <- match.arg(pdf)
    print(pdf)
}

The function sees the pdfs object (I tried to print it, and it works fine), but match.arg() does not work as expected, and throws the following error:
Error in eval(expr, envir, enclos) :
  object 'pdfs' not found

At the same time this example below works, so I guess it is very likely an issue with environments.
a <- c("a", "b")
f <- function(x = a) {
    x <- match.arg(x)
    print(x)
}
f()

Session info:
> sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
Running under: OS X 10.7.5 (Lion)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] s4chart_0.1.1

loaded via a namespace (and not attached):
 [1] colorspace_1.2-6 scales_0.3.0     plyr_1.8.3       tools_3.2.1
 [5] withr_1.0.2      gtable_0.1.2     Rcpp_0.12.1      memoise_1.0.0
 [9] ggplot2_2.1.0    grid_3.2.1       digest_0.6.8     munsell_0.4.2
[13] devtools_1.12.0

A: Could be a collation issue. Place file1.R above file2.R in the Collate field in the DESCRIPTION file. You can do that by using #' @include file1.R inside file2.R if you are using roxygen.


text:
Q: Log apache camel seda queue depth every second via a timer How can I log actual seda queue depth every second on a timer.
E.g.
from("seda:messageParser?concurrentConsumers=5&size=5000)
.process(messageProcessor)

from("timer://sedaQueueDepthLogger?fixedRate=true")
.to(LOG_SEDA_QUEUE_DEPTH)

What should be LOG_SEDA_QUEUE_DEPTH above to achieve this?

A: You cannot log it that easily. From a custom processor, you can get the seda endpoint, and from there you have APIs to get the queue, and get the size, which you can then log.
There is also JMX API to find that information.


text:
Q: Ignoring a backreference in a rewrite I'm probably not wording my title correct, but here's my rule:
RewriteRule ^our-thinking/(.*)/(.*)$ /$2 [L,NC]
So I want http://hostname/our-thinking/scenarios/this-is-a-post to load http://hostname/this-is-a-post.
But with my current rule, it always becomes /scenarios. Even if I change $2 to anything else, it's always /scenarios.
What am I doing wrong?

A: You don't need to capture something that you don't want to use on RHS.
Try this rule with better regex:
RewriteRule ^our-thinking/[^/]+/([^/]+)/?$ /$1 [L,NC]

If you want an external redirect (i.e. to change URL in browser), use this rule:
RewriteRule ^our-thinking/[^/]+/([^/]+)/?$ /$1 [L,NC,R]


text:
Q: column hyperlink and pass data from master report to other report I have a requirement to display data from table1 on reports. For this, i have created two reports: Mainreport and IdDataReport
Table1: Id, fName,lname,isactive.
Mainreport: It displays all columns -  ID column should have hyperlink only if isactive=true else no hyperlink.
IdDataReport: This report should display other data based on ID value that comes / selected from this "Mainreport" report.
What i have done?
I went to Mainreport report "ID" textbox->Actions -> Goto report ->fx -> iif(IsNothing(Fields!isActive.value)=True,Nothing,"IdDataReport")
After performing above I'm getting data.
Problem: 1. Mainreport - 'ID' column records are having hyperlink (showing hand icon) irrespective "inactive=false".
2. Selected "ID" column value on "Mainreport" not going to "IdDataReport" report and not displayed selected value related data.


text:
Q: Complex Integration There are some sequential functions:
e[t_] :=(E^(-t^2)) Cos[0.1 t];
a[t_] := Integrate[e[x], {x, 0, t}];
p[t_, tau_]:=Integrate[a[x],{x,t-tau,t}];
s[t_, tau_] := Integrate[(a[x])^2,{x,t-tau,t}]+ (1-(p[t,tau])^2)tau;

Although there are numeric values for s[t,tau] for example s[2, 1] // Chop is equal to 1.0008 but its integration (as will be shown below) does not have an answer.
test[t_]:=I*Integrate[E^(-I s[t,x]),{x,0,1}];

I mean the test[2]//N does have an error which could not be removed

A: You are almost certainly going to need to evaluate test numerically, so let's just use NIntegrate from the start.
Clear[e, a, p, s, t]
e[t_] := (E^(-t^2)) Cos[0.1 t];
a[t_?NumericQ] := NIntegrate[e[x], {x, 0, t}];
p[t_?NumericQ, tau_?NumericQ] := NIntegrate[a[x], {x, t - tau, t}];
s[t_?NumericQ, tau_?NumericQ] :=
  NIntegrate[(a[x])^2, {x, t - tau, t}] + (1 - (p[t, tau])^2) tau;
test[t_?NumericQ] := I*NIntegrate[E^(-I s[t, x]), {x, 0, 1}];
test[2]

(* Out: 0.605924 + 0.731384 I *)

The use of _?NumericQ in this context is common enough to have an entry in our `common pitfalls question.


text:
Q: how manage the scrollToIndex method with angular's material virtual scroll Could you tell me how manage the scrollToIndex (virtuall scroll) if my list is not loaded during the ngAfterViewInit lifehook? I need to call the scroll to the index when I m redirect from an other page, so in the ts file. So my goal is to point to the right index when the page is loaded
@ViewChild(CdkVirtualScrollViewport) viewport: CdkVirtualScrollViewport;
ngOnInit() {
...
this.getData(index);
}

getData(index){
return this.service.get().subscribe(data => {
this.fullDatasource = data;
this.selectedIndex = this.fullDatasource.findIndex(value => value.id === index);
}

ngAfterViewInit() {
this.viewport.scrollToIndex(this.selectedIndex);
}

Nothing happens, if I call the method in the ngAfterViewInit. Many many thnaks in advance.

A: You could try running the scrollToIndex in a setTimeout function, i think this triggers another round of change detection, by then your list could be loaded. Another way to archive this is to use the ChangeDetectorRef, see the official docs for details on how this works.
Or trigger the scroll manually in the subscription of the getData method instead of AfterViewInit.

A: I wonder if virtual scroll makes sense in this case. Concerning the timeout, is it good to put it in knowing that the virtual scroll is designed to handle very large dataset ?


text: Q: How can I find out which package installed a particular executable? For example, on Debian or Ubuntu, which package has the /sbin/shutdown command in it? I want to read the source of that command (and possibly modify it to report notification on desktop) and I didn't know which package source to download.


text:
Q: Hive with Lucene Is it possible to use Hive for querying Lucene index which is distributed over Hadoop???

A: Hadapt is a startup whose software bridges Hadoop with a SQL front-end (like Hive) and hybrid storage engines.  They offer a archival text search capability that may meet your needs.
Disclaimer: I work for Hadapt.

A: As far as I know you can essentially write custom "row-extraction" code in Hive so I would guess that you could. I've never used Lucene and barely used Hive, so I can't be sure. If you find a more conclusive answer to your question, please post it!

A: I know this is a fairly old post, but thought I could offer a better alternative.
In your case, instead of going through the hassle of mapping your HDFS Lucene index to hive schema, it's better to push them into pig, because pig can read flat files. Unless you want a Relational way of storing your data, you could probably process them through Pig and use, Hbase as your DB.

A: You could write a custom input format for Hive to access lucene index in Hadoop.