问:
Jfreechart indexoutofbounds exception
This is my first time posting on StackOverFlow so please excuse any mistakes in my post.
Coming to the topic I have a program which is supposed to plot certain X and Y co-ordinates.
I am currently using JFREECHART for XYChart.
In order to meet high speed update requirements I have 2 series. Series1 accumulates 1000 datapoints and then gets added to the chart to display it.After this series2 accumaltes 1000 datapoints and once it is finised it clears series1 (to prepare it for new 1000 datapoints) and attaches series2 to the chart(which now has 1000 datapoints)...and this cycle goes on.
The issue is with the XYSeries.clear and XYSeries.add functions. Apparently they create their own threads and before they can finish execution I already spawn a new thread since my application is very fast. This I think is causing indexoutobounds error. I was able to guess this with:
http://www.jfree.org/phpBB2/viewtopic.php?p=68111
Similar error.
The solution seems to be:
Swing Thread Safe Programming

Here the solution is to use SwingUtilities.invokeLater. But I fail to understand how to use this in my application.
My code is:

```<code>import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.lang.Thread.sleep;
import org.jfree.chart.axis.ValueAxis;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class dataPlotter {

    private static int x = 0;
    private static boolean thread_start = false;
    private static final double PI = 3.1428571;
    private static boolean thread_run = true;
    private static double voltage = 0;
    private static boolean useSeries1 = true;

    public static void main(String[] args) {

        //create and configure window
        JFrame window = new JFrame();
        window.setTitle("Data Plotter GUI");
        window.setSize(600, 400);
        window.setLayout(new BorderLayout());
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //create a drop down box and connect button, then place that at the top of the window
        JButton connectButton = new JButton("Start");
        JPanel topPanel = new JPanel();
        topPanel.add(connectButton);
        window.add(topPanel, BorderLayout.NORTH);

        //create the line graph
        XYSeries series1 = new XYSeries("Voltage Characteristics");
        XYSeries series2 = new XYSeries("Voltage Characteristics");
        XYSeriesCollection dataset = new XYSeriesCollection(series1);
        JFreeChart chart = ChartFactory.createXYLineChart("Sine Wave", "Time", "Voltage", dataset);
        window.add(new ChartPanel(chart), BorderLayout.CENTER);

        //set range of x axis and range of series
        XYPlot xyPlot = chart.getXYPlot();
        ValueAxis domainAxis = xyPlot.getDomainAxis();
        ValueAxis rangeAxis = xyPlot.getRangeAxis();
        rangeAxis.setRange(-1.5, 1.5);
        domainAxis.setRange(0, 1000);

        //Declaring thread
        Thread thread;
        thread = new Thread() {
            @Override
            public void run() {
                thread_start = true;
                int count_y = 0;
                thread_run = true;
                int count = 0;
                while (thread_run) {
                    //create "Y" datapoint i.e. voltage
                    if (count_y < 800) {
                        count_y++;
                    } else {
                        count_y = 0;
                    }
                    voltage = Math.sin(2 * PI * count_y / 800);

                    //add datapoint to CHART
                    try {
                        //use series 1 to accumulate 1000 datapoints
                        if(useSeries1){
                            synchronized (series1) {
                                if (series1.getItemCount() > 1000) {
                                    domainAxis.setRange(x - 1001, x);
                                }
                                series1.add(x++, voltage);
                                sleep(1);
                            }
                            synchronized (series1) {
                                window.repaint();
                            }

                            synchronized (series1) {
                                if (series1.getItemCount() ==1001) {

                                    dataset.removeAllSeries();
                                    series2.clear();
                                    domainAxis.setRange(0, 1000);
                                    dataset.addSeries(series1);
                                    useSeries1 = false;
                                    sleep(5);
                                    x = 0;
                                    window.repaint();
                                }
                            }
                        } else{
                            synchronized (series2) {
                                if (series2.getItemCount() > 1000) {
                                    domainAxis.setRange(x - 1001, x);
                                }
                                series2.add(x++, voltage);
                                sleep(1);
                            }
                            synchronized (series2) {
                                window.repaint();
                            }
                            synchronized (series2) {
                                if (series2.getItemCount() == 1001) {
                                    dataset.removeAllSeries();
                                    series1.clear();
                                    domainAxis.setRange(0, 1000);
                                    dataset.addSeries(series2);
                                    useSeries1 = true;
                                    sleep(5);
                                    x = 0;
                                    window.repaint();
                                 }
                            }
                        }
                    } catch (Exception er) { }
                }
                thread_start = false;
             }
            };

        //configure the connect button and use another thread to listen for data
        connectButton.addActionListener(new ActionListener() {
            @Override
            @SuppressWarnings("empty-statement")
            public void actionPerformed(ActionEvent e) {
                if (connectButton.getText().equals("Start")) {

                    connectButton.setText("Stop");

                    thread.start();
                } else {
                    //disconnect from the serial port
                    thread_run = false;

                    //while (thread_start);
                    connectButton.setText("Start");
                    //synchronized (series) {
                    //series.clear();
                    //}
                    //x = 0;

                }
            }

        });

        //Display winow
        window.setVisible(true);

    }
}
</code>```

答:
Swing is not thread safe, by design. You have to use SwingUtilities.invokeLater( ... ) from another thread than Swing event pump thread as discussed here.

The tutorial about Swing may help.

Here is a proposal, object oriented. Hope this helps.

```<code>public class Plotter implements Runnable {

   private static final String BTN_START = "Start";
   private static final String BTN_STOP  = "Stop";

   private final JFrame             window        = new JFrame();
   private final JButton            connectButton = new JButton( BTN_START );
   private final XYSeries           series1       = new XYSeries("Voltage Characteristics");
   private final XYSeries           series2       = new XYSeries("Voltage Characteristics");
   private final XYSeriesCollection dataset       = new XYSeriesCollection( series1 );
   private final JFreeChart         chart         =
      ChartFactory.createXYLineChart("Sine Wave", "Time", "Voltage", dataset);
   private final XYPlot             xyPlot        = chart.getXYPlot();
   private final ValueAxis          domainAxis    = xyPlot.getDomainAxis();
   private final ValueAxis          rangeAxis     = xyPlot.getRangeAxis();
   private /* */ Thread             thread        = null;
   private /* */ boolean            thread_run    = true;
   private /* */ double             voltage       = 0;
   private /* */ boolean            useSeries1    = true;
   private /* */ int                x             = 0;

   public Plotter() {
      window.setTitle("Data Plotter GUI");
      window.setSize(600, 400);
      window.setLayout(new BorderLayout());
      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      final JPanel topPanel = new JPanel();
      topPanel.add(connectButton);
      window.add(topPanel, BorderLayout.NORTH);
      window.add(new ChartPanel(chart), BorderLayout.CENTER);
      rangeAxis.setRange(-1.5, 1.5);
      domainAxis.setRange(0, 1000);
      connectButton.addActionListener( e -> startOrStop());
      window.setVisible(true);
   }

   private void startOrStop() {
      if (connectButton.getText().equals( BTN_START )) {
         connectButton.setText( BTN_STOP );
         synchronized( series1 ) { series1.clear(); }
         synchronized( series2 ) { series2.clear(); }
         thread = new Thread( Plotter.this );
         thread.setName( "Plotter" );
         thread.setDaemon( true );
         thread.start();
      }
      else {
         thread_run = false;
         //disconnect from the serial port
         connectButton.setText( BTN_START );
         try {
            thread.join( 10_000L );
         }
         catch( final InterruptedException e ){
            e.printStackTrace();
         }
      }
   }

   private void updateSeries1() {
      if (series1.getItemCount() > 1000) {
         domainAxis.setRange(x - 1001, x);
      }
      series1.add( x++, voltage );
      window.repaint();
      if (series1.getItemCount() ==1001) {

         dataset.removeAllSeries();
         series2.clear();
         domainAxis.setRange(0, 1000);
         dataset.addSeries(series1);
         useSeries1 = false;
         window.repaint();
         x = 0;
      }
   }

   private void updateSeries2() {
      if (series2.getItemCount() > 1000) {
         domainAxis.setRange(x - 1001, x);
      }
      series2.add( x++, voltage );
      window.repaint();
      if( series2.getItemCount() == 1001 ) {
         dataset.removeAllSeries();
         series1.clear();
         domainAxis.setRange(0, 1000);
         dataset.addSeries(series2);
         useSeries1 = true;
         window.repaint();
         x = 0;
      }
   }

   @Override
   public void run() {
      x = 0;
      int count_y = 0;
      thread_run = true;
      while( thread_run ) {
         if (count_y < 800) {
            count_y++;
         }
         else {
            count_y = 0;
         }
         voltage = Math.sin(( 2 * Math.PI * count_y ) / 800);
         try {
            // Push a new job in the Swing queue
            if( useSeries1 ) {
               SwingUtilities.invokeLater(() -> updateSeries1());
            }
            else {
               SwingUtilities.invokeLater(() -> updateSeries2());
            }
         }
         catch (final Exception er) {
            er.printStackTrace();
         }
         try {
            Thread.sleep( 2L ); // Give time to Swing to execute the job
         }
         catch( final InterruptedException e ){
            e.printStackTrace();
         }
      }
   }

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

Title: Jfreechart indexoutofbounds exception

Body:
This is my first time posting on StackOverFlow so please excuse any mistakes in my post.
Coming to the topic I have a program which is supposed to plot certain X and Y co-ordinates.
I am currently using JFREECHART for XYChart.
In order to meet high speed update requirements I have 2 series. Series1 accumulates 1000 datapoints and then gets added to the chart to display it.After this series2 accumaltes 1000 datapoints and once it is finised it clears series1 (to prepare it for new 1000 datapoints) and attaches series2 to the chart(which now has 1000 datapoints)...and this cycle goes on.
The issue is with the XYSeries.clear and XYSeries.add functions. Apparently they create their own threads and before they can finish execution I already spawn a new thread since my application is very fast. This I think is causing indexoutobounds error. I was able to guess this with:
http://www.jfree.org/phpBB2/viewtopic.php?p=68111
Similar error.
The solution seems to be:
Swing Thread Safe Programming

Here the solution is to use SwingUtilities.invokeLater. But I fail to understand how to use this in my application.
My code is:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static java.lang.Thread.sleep;
import org.jfree.chart.axis.ValueAxis;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class dataPlotter {

    private static int x = 0;
    private static boolean thread_start = false;
    private static final double PI = 3.1428571;
    private static boolean thread_run = true;
    private static double voltage = 0;
    private static boolean useSeries1 = true;

    public static void main(String[] args) {

        //create and configure window
        JFrame window = new JFrame();
        window.setTitle("Data Plotter GUI");
        window.setSize(600, 400);
        window.setLayout(new BorderLayout());
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //create a drop down box and connect button, then place that at the top of the window
        JButton connectButton = new JButton("Start");
        JPanel topPanel = new JPanel();
        topPanel.add(connectButton);
        window.add(topPanel, BorderLayout.NORTH);

        //create the line graph
        XYSeries series1 = new XYSeries("Voltage Characteristics");
        XYSeries series2 = new XYSeries("Voltage Characteristics");
        XYSeriesCollection dataset = new XYSeriesCollection(series1);
        JFreeChart chart = ChartFactory.createXYLineChart("Sine Wave", "Time", "Voltage", dataset);
        window.add(new ChartPanel(chart), BorderLayout.CENTER);

        //set range of x axis and range of series
        XYPlot xyPlot = chart.getXYPlot();
        ValueAxis domainAxis = xyPlot.getDomainAxis();
        ValueAxis rangeAxis = xyPlot.getRangeAxis();
        rangeAxis.setRange(-1.5, 1.5);
        domainAxis.setRange(0, 1000);

        //Declaring thread
        Thread thread;
        thread = new Thread() {
            @Override
            public void run() {
                thread_start = true;
                int count_y = 0;
                thread_run = true;
                int count = 0;
                while (thread_run) {
                    //create "Y" datapoint i.e. voltage
                    if (count_y < 800) {
                        count_y++;
                    } else {
                        count_y = 0;
                    }
                    voltage = Math.sin(2 * PI * count_y / 800);

                    //add datapoint to CHART
                    try {
                        //use series 1 to accumulate 1000 datapoints
                        if(useSeries1){
                            synchronized (series1) {
                                if (series1.getItemCount() > 1000) {
                                    domainAxis.setRange(x - 1001, x);
                                }
                                series1.add(x++, voltage);
                                sleep(1);
                            }
                            synchronized (series1) {
                                window.repaint();
                            }

                            synchronized (series1) {
                                if (series1.getItemCount() ==1001) {

                                    dataset.removeAllSeries();
                                    series2.clear();
                                    domainAxis.setRange(0, 1000);
                                    dataset.addSeries(series1);
                                    useSeries1 = false;
                                    sleep(5);
                                    x = 0;
                                    window.repaint();
                                }
                            }
                        } else{
                            synchronized (series2) {
                                if (series2.getItemCount() > 1000) {
                                    domainAxis.setRange(x - 1001, x);
                                }
                                series2.add(x++, voltage);
                                sleep(1);
                            }
                            synchronized (series2) {
                                window.repaint();
                            }
                            synchronized (series2) {
                                if (series2.getItemCount() == 1001) {
                                    dataset.removeAllSeries();
                                    series1.clear();
                                    domainAxis.setRange(0, 1000);
                                    dataset.addSeries(series2);
                                    useSeries1 = true;
                                    sleep(5);
                                    x = 0;
                                    window.repaint();
                                 }
                            }
                        }
                    } catch (Exception er) { }
                }
                thread_start = false;
             }
            };

        //configure the connect button and use another thread to listen for data
        connectButton.addActionListener(new ActionListener() {
            @Override
            @SuppressWarnings("empty-statement")
            public void actionPerformed(ActionEvent e) {
                if (connectButton.getText().equals("Start")) {

                    connectButton.setText("Stop");

                    thread.start();
                } else {
                    //disconnect from the serial port
                    thread_run = false;

                    //while (thread_start);
                    connectButton.setText("Start");
                    //synchronized (series) {
                    //series.clear();
                    //}
                    //x = 0;

                }
            }

        });

        //Display winow
        window.setVisible(true);

    }
}

Body:
Swing is not thread safe, by design. You have to use SwingUtilities.invokeLater( ... ) from another thread than Swing event pump thread as discussed here.

The tutorial about Swing may help.

Here is a proposal, object oriented. Hope this helps.

public class Plotter implements Runnable {

   private static final String BTN_START = "Start";
   private static final String BTN_STOP  = "Stop";

   private final JFrame             window        = new JFrame();
   private final JButton            connectButton = new JButton( BTN_START );
   private final XYSeries           series1       = new XYSeries("Voltage Characteristics");
   private final XYSeries           series2       = new XYSeries("Voltage Characteristics");
   private final XYSeriesCollection dataset       = new XYSeriesCollection( series1 );
   private final JFreeChart         chart         =
      ChartFactory.createXYLineChart("Sine Wave", "Time", "Voltage", dataset);
   private final XYPlot             xyPlot        = chart.getXYPlot();
   private final ValueAxis          domainAxis    = xyPlot.getDomainAxis();
   private final ValueAxis          rangeAxis     = xyPlot.getRangeAxis();
   private /* */ Thread             thread        = null;
   private /* */ boolean            thread_run    = true;
   private /* */ double             voltage       = 0;
   private /* */ boolean            useSeries1    = true;
   private /* */ int                x             = 0;

   public Plotter() {
      window.setTitle("Data Plotter GUI");
      window.setSize(600, 400);
      window.setLayout(new BorderLayout());
      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      final JPanel topPanel = new JPanel();
      topPanel.add(connectButton);
      window.add(topPanel, BorderLayout.NORTH);
      window.add(new ChartPanel(chart), BorderLayout.CENTER);
      rangeAxis.setRange(-1.5, 1.5);
      domainAxis.setRange(0, 1000);
      connectButton.addActionListener( e -> startOrStop());
      window.setVisible(true);
   }

   private void startOrStop() {
      if (connectButton.getText().equals( BTN_START )) {
         connectButton.setText( BTN_STOP );
         synchronized( series1 ) { series1.clear(); }
         synchronized( series2 ) { series2.clear(); }
         thread = new Thread( Plotter.this );
         thread.setName( "Plotter" );
         thread.setDaemon( true );
         thread.start();
      }
      else {
         thread_run = false;
         //disconnect from the serial port
         connectButton.setText( BTN_START );
         try {
            thread.join( 10_000L );
         }
         catch( final InterruptedException e ){
            e.printStackTrace();
         }
      }
   }

   private void updateSeries1() {
      if (series1.getItemCount() > 1000) {
         domainAxis.setRange(x - 1001, x);
      }
      series1.add( x++, voltage );
      window.repaint();
      if (series1.getItemCount() ==1001) {

         dataset.removeAllSeries();
         series2.clear();
         domainAxis.setRange(0, 1000);
         dataset.addSeries(series1);
         useSeries1 = false;
         window.repaint();
         x = 0;
      }
   }

   private void updateSeries2() {
      if (series2.getItemCount() > 1000) {
         domainAxis.setRange(x - 1001, x);
      }
      series2.add( x++, voltage );
      window.repaint();
      if( series2.getItemCount() == 1001 ) {
         dataset.removeAllSeries();
         series1.clear();
         domainAxis.setRange(0, 1000);
         dataset.addSeries(series2);
         useSeries1 = true;
         window.repaint();
         x = 0;
      }
   }

   @Override
   public void run() {
      x = 0;
      int count_y = 0;
      thread_run = true;
      while( thread_run ) {
         if (count_y < 800) {
            count_y++;
         }
         else {
            count_y = 0;
         }
         voltage = Math.sin(( 2 * Math.PI * count_y ) / 800);
         try {
            // Push a new job in the Swing queue
            if( useSeries1 ) {
               SwingUtilities.invokeLater(() -> updateSeries1());
            }
            else {
               SwingUtilities.invokeLater(() -> updateSeries2());
            }
         }
         catch (final Exception er) {
            er.printStackTrace();
         }
         try {
            Thread.sleep( 2L ); // Give time to Swing to execute the job
         }
         catch( final InterruptedException e ){
            e.printStackTrace();
         }
      }
   }

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


来源: stackexchange

问:
On click of submit button I want to get an success alert and then clicking on OK I should get redirected to a new page for PHP
I am submitting data to the database. On successful submission, I want to display an alert stating the submission was successful and then clicking on OK I want to redirect to a new page displaying the data. I am doing this for PHP. I am not getting the success message I am being redirected to the display data page.</p>

```<code>if ($conn->query($sql) === TRUE) {
    //echo "New record created successfully";
    $message = "New record created successfully";
    echo "<script type='text/javascript'>alert('$message');</script>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
header("Location:displaydata.php");
exit;
</code>```

答:
You cant set the header() function under an HTML output.
Set your header Location over your output.
And for your click write it like this one:

```<code>if ($conn->query($sql) === TRUE) {
    //echo "New record created successfully";
    $message = '<a href="myNewPage.html">New record created successfully</a>';
    echo $message;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
// header("Location:displaydata.php");// remove this one
exit;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am submitting data to the database. On successful submission, I want to display an alert stating the submission was successful and then clicking on OK I want to redirect to a new page displaying the data. I am doing this for PHP. I am not getting the success message I am being redirected to the display data page.

if ($conn->query($sql) === TRUE) {
    //echo "New record created successfully";
    $message = "New record created successfully";
    echo "";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}
header("Location:displaydata.php");
exit;

Body:
You cant set the header() function under an HTML output.
Set your header Location over your output.
And for your click write it like this one:

if ($conn->query($sql) === TRUE) {
    //echo "New record created successfully";
    $message = '<a href="myNewPage.html">New record created successfully</a>';
    echo $message;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
// header("Location:displaydata.php");// remove this one
exit;


问:
Send Html as parameter from javascript to asp.net mvc controller
I need to pass some HTML markup to the controller (please see my detalle variable), using jquery, in the action is that I have the problem when I try to send the detalle, it said that is not found, somebody can help me?

```<code>           $('#BtnPrint').click(function() {

                var detalle = "<br><br>";

                detalle += " Yo: <b>" + '@Model.DoctorText' + "</b>";
                if ('@Model.Exequartur' != "") {
                    detalle += ", exequatur: <b>" + '@Model.Exequartur' + "</b>    <br>";
                }

                detalle += "   certifico haber examinado a: <b>" + '@Model.PatientName' + "</b> <br>";
                @*if (@Model.ide != "")
                {
                    detalle += " cedula: <b>" + txtcedula.Text + "</b>    <br>";
                }*@

                detalle += " quien presenta: <b>" + '@Model.Affections' + "</b>    <br>";
                detalle += " por lo que recomiendo: <b>" + '@Model.Recomendations' + "</b>    <br>";
                detalle += "<br> dado en: <b>" + ' @Model.Place' + "</b>, " + '@Model.MedicalCertificateDate' +
                    "    <br>";
                detalle += "<br><br><br><br>  ";
                $('#myVar').val(detalle);

            var win = window.open(
                "@Url.Action("DetailsPrint", "Reports", new {area = "Configurations", id = @Model.Patient.Person.AuthorId, body = detalle, description = "Certificado Medico"})" )  ;

                ////  var win = window.open('http://stackoverflow.com/', '_blank');
                if (win) {
                    //Browser has allowed it to be opened
                    win.focus();
                } else {
                    //Browser has blocked it
                    alert("Porfavor, debes permitir que se abran las ventanas emergentes o el reporte no va a salir :'( ");
                }

            });
</code>```

答:
Problem is that you passing JS variable into Url.Action
In your case, you should do like that:

```<code>$('#BtnPrint').click(function() {

    var detalle = "<br><br>";

    detalle += " Yo: <b>" + '@Model.DoctorText' + "</b>";
    if ('@Model.Exequartur' != "") {
        detalle += ", exequatur: <b>" + '@Model.Exequartur' + "</b>    <br>";
    }

    detalle += "   certifico haber examinado a: <b>" + '@Model.PatientName' + "</b> <br>";
    @*if (@Model.ide != "")
    {
        detalle += " cedula: <b>" + txtcedula.Text + "</b>    <br>";
    }*@

    detalle += " quien presenta: <b>" + '@Model.Affections' + "</b>    <br>";
    detalle += " por lo que recomiendo: <b>" + '@Model.Recomendations' + "</b>    <br>";
    detalle += "<br> dado en: <b>" + ' @Model.Place' + "</b>, " + '@Model.MedicalCertificateDate' +
        "    <br>";
    detalle += "<br><br><br><br>  ";
    $('#myVar').val(detalle);

    var url = '@Url.Action("DetailsPrint", "Reports", new {area = "Configurations", id = @Model.Patient.Person.AuthorId, description = "Certificado Medico"})';
    url = url + "&body="+encodeURIComponent(detalle);
    var win = window.open(url);

    ////  var win = window.open('http://stackoverflow.com/', '_blank');
    if (win) {
        //Browser has allowed it to be opened
        win.focus();
    } else {
        //Browser has blocked it
        alert("Porfavor, debes permitir que se abran las ventanas emergentes o el reporte no va a salir :'( ");
    }

});
</code>```

And your controller should be:

```<code>[ValidateInput(false)]
public ActionResult DetailsPrint(string body, int id, string description)
{
    //something
}
</code>```

Body:
I need to pass some HTML markup to the controller (please see my detalle variable), using jquery, in the action is that I have the problem when I try to send the detalle, it said that is not found, somebody can help me?

           $('#BtnPrint').click(function() {

                var detalle = "

";

                detalle += " Yo: " + '@Model.DoctorText' + "";
                if ('@Model.Exequartur' != "") {
                    detalle += ", exequatur: " + '@Model.Exequartur' + "
";
                }

                detalle += "   certifico haber examinado a: " + '@Model.PatientName' + "
";
                @*if (@Model.ide != "")
                {
                    detalle += " cedula: " + txtcedula.Text + "
";
                }*@

                detalle += " quien presenta: " + '@Model.Affections' + "
";
                detalle += " por lo que recomiendo: " + '@Model.Recomendations' + "
";
                detalle += "
 dado en: " + ' @Model.Place' + ", " + '@Model.MedicalCertificateDate' +
                    "
";
                detalle += "

  ";
                $('#myVar').val(detalle);

            var win = window.open(
                "@Url.Action("DetailsPrint", "Reports", new {area = "Configurations", id = @Model.Patient.Person.AuthorId, body = detalle, description = "Certificado Medico"})" )  ;

                ////  var win = window.open('http://stackoverflow.com/', '_blank');
                if (win) {
                    //Browser has allowed it to be opened
                    win.focus();
                } else {
                    //Browser has blocked it
                    alert("Porfavor, debes permitir que se abran las ventanas emergentes o el reporte no va a salir :'( ");
                }

            });

Body:
Problem is that you passing JS variable into Url.Action
In your case, you should do like that:

$('#BtnPrint').click(function() {

    var detalle = "<br><br>";

    detalle += " Yo: <b>" + '@Model.DoctorText' + "</b>";
    if ('@Model.Exequartur' != "") {
        detalle += ", exequatur: <b>" + '@Model.Exequartur' + "</b>    <br>";
    }

    detalle += "   certifico haber examinado a: <b>" + '@Model.PatientName' + "</b> <br>";
    @*if (@Model.ide != "")
    {
        detalle += " cedula: <b>" + txtcedula.Text + "</b>    <br>";
    }*@

    detalle += " quien presenta: <b>" + '@Model.Affections' + "</b>    <br>";
    detalle += " por lo que recomiendo: <b>" + '@Model.Recomendations' + "</b>    <br>";
    detalle += "<br> dado en: <b>" + ' @Model.Place' + "</b>, " + '@Model.MedicalCertificateDate' +
        "    <br>";
    detalle += "<br><br><br><br>  ";
    $('#myVar').val(detalle);

    var url = '@Url.Action("DetailsPrint", "Reports", new {area = "Configurations", id = @Model.Patient.Person.AuthorId, description = "Certificado Medico"})';
    url = url + "&body="+encodeURIComponent(detalle);
    var win = window.open(url);

    ////  var win = window.open('http://stackoverflow.com/', '_blank');
    if (win) {
        //Browser has allowed it to be opened
        win.focus();
    } else {
        //Browser has blocked it
        alert("Porfavor, debes permitir que se abran las ventanas emergentes o el reporte no va a salir :'( ");
    }

});

And your controller should be:

[ValidateInput(false)]
public ActionResult DetailsPrint(string body, int id, string description)
{
    //something
}


问:
What exactly are Static Constructor in C#?
I have couple of question regarding Static Constructor in C#.

What exactly are Static Constructor and how they are different from non-static Constructor.

How can we use them in our application ?

**Edited

```<code>public class Test
{
    // Static constructor:
    static Test()
    {
        Console.WriteLine("Static constructor invoked.");
    }

    public static void TestMethod()
    {
       Console.WriteLine("TestMethod invoked.");
    }
}

class Sample
{
    static void Main()
    {
        Test.TestMethod();
    }
}
</code>```

Output :
Static constructor invoked.
TestMethod invoked.
So, this means that static constructor will be called once. if we again call  Test.TestMethod(); static constructor won't invoke.

Any pointer or suggestion would be appreciated
 '

Thanks

答:
You use them the same way you use instance constructors - to set default values. Only in this case you'll be initializing static fields, so static constructors get executed only once.

Be aware that the code in static constructor won't be executed until the first call to the class was made.

ContentLicense: CC BY-SA 2.5

Body:
I have couple of question regarding Static Constructor in C#.

What exactly are Static Constructor and how they are different from non-static Constructor.

How can we use them in our application ?

**Edited

public class Test
{
    // Static constructor:
    static Test()
    {
        Console.WriteLine("Static constructor invoked.");
    }

    public static void TestMethod()
    {
       Console.WriteLine("TestMethod invoked.");
    }
}

class Sample
{
    static void Main()
    {
        Test.TestMethod();
    }
}

Output :
Static constructor invoked.
TestMethod invoked.
So, this means that static constructor will be called once. if we again call  Test.TestMethod(); static constructor won't invoke.

Any pointer or suggestion would be appreciated
 '

Thanks


问:
Binary search / bisection for floating point numbers
It is easy to find an integer with binary search even if it can be arbitrarily large: first guess the order of magnitude, then keep dividing the interval.
This answer describes how to find an arbitrary rational number.

Having set the scene, my question is similar: how can we guess a IEEE 754 floating point number?  Assume it is not NaN, but everything else is fair game.  For each guess, your program will be told whether the number in question is higher, equal or lower.  Minimize the number of guesses required in the worst case.

(This is not a homework assignment.  Though, I might make it one, if this turns out to have an interesting answer that's not just "beat the floating point numerical difficulties to death with lots and lots of special case handling.")

Edit: if I were better at searching I could have found the answer---but that only works if you already know that reinterpretation as int works (with certain caveats). So leaving this up. Thanks to Harold for a great answer!

答:
IEEE-754 64-bit floating point numbers are really 64-bit representations. Furthermore, with the exception of NaN values, there is no difference between floating point comparison and integer comparison of positive values. (That is, two bit patterns with the sign bit unset will produce the same comparison result regardless of whether you compare them as int64_t or double, unless one of the bit patterns is a floating point NaN-.)

That means you can find a number in 64 guesses by guessing one bit at a time, even if the number is ±∞. Start by comparing the number with 0; if the target is "less", then produce the guesses in the same way as below, but negate them before guessing. (Since IEEE-754 floats are sign/magnitude, you can negate the number by setting the sign bit to 1. Or you could do the positive bit-pattern reinterpretation and then floating point negate the result.)

After that, guess one bit at a time, starting with the highest-order value bit. Set that bit to 1 if the number is greater than or equal to the guess; set that bit to 0 if the number is less; and continue with the next bit until there aren't any more. To construct the guess, reinterpret the bit pattern as a double.

There are two caveats:

You cannot distinguish between ±0 with comparison tests. That means that if your opponent wants you to distinguish between them, they will have to supply you with a way to ask about equality with −0, and you'll have to use that mechanism after you've apparently established that the number is 0 (which will happen on the 64th guess). This would add one guess, for a total of 65.

If you are assured that the target is not a NaN, then there is no other problem. If it might be a NaN, you need to be careful how you compare: things will work out fine if you always ask "is X less than this guess?", because a NaN comparison will always return false. That means that after 11 successive "no" answers (not counting the one to establish the sign), you will find yourself guessing ∞, with the assumption that if the number is not less than ∞, it must be equal. However, in this case alone you need to explicitly test for equality as well, because that will also be false if the target is a NaN. This doesn't add an additional guess to the count, because it will always happen long before 64 guesses have been used up.


答:
Try this:</p>

```<code>echo '<script type="text/javascript">';
echo 'alert("New record created successfully");';
echo 'window.location.href = "displaydata.php";';
echo '</script>';
</code>```

Title: On click of submit button I want to get an success alert and then clicking on OK I should get redirected to a new page for PHP

Body:
Try this:

echo '<script type="text/javascript">';
echo 'alert("New record created successfully");';
echo 'window.location.href = "displaydata.php";';
echo '</script>';


问:
Why C++ doesn't allow derived class to use base class member in initialization list?
I've got following program:

```<code>#include<iostream>
using namespace std;
struct Base01{
    int m;
    Base01():m(2){}
    void p(){cout<<m<<endl;}
};
struct Derived01:public Base01{
    Derived01():m(3){}
};
struct Derived02:virtual public Base01{
    Derived01():m(4){}
};
struct my: Derived01,Derived02{
    my():m(5){}
};
int main(){
    return 0;
}
</code>```

Both gcc/clang reports compilation error.

I just wish to know what's the language design consideration here, why derived class can only call base class ctor in initialization list, but cannot use base class members directly?

答:
The fundamental language design considerations in this are separation of concerns (avoiding making a base class depend on its derived classes), and that a base class is responsible for initialising its own members (and any bases it has).

A related consideration is that members of the base class don't exist - as far as the derived class constructor is concerned - before the base class constructor completes.   If an initialiser list of a derived class was able to reach in and initialise a base class member, then there are two possible consequences

If the base class constructor has not been invoked, its members will not exist when the derived class tries to initialise them.

If the base class constructor has been invoked, the member has been initialised.  Initialisation (as distinct from assignment to reinitialise) happens once in the lifetime of an object, so it does not make sense to initialise it again.

Neither of these possibilities really make sense in practice, unless the base class is poorly designed (e.g. its constructors do not properly initialise its members).   The sort of machinery needed so they might make sense (e.g. changing order of construction of base classes in a hierarchy, dependent on what member a derived class is trying to initialise) would make compiler machinery more complicated (e.g. being able to both control and track the order of construction of base class members, in case a derived class should choose to reach in), and also mean that the order of construction of classes would depend on derived classs).   This would introduce a dependency of the base class behaviour (the means by which it is initialised) on derived classes.

The simpler means is for the base class to provide a constructor that properly initialised the member in question, and for the derived class constructor to invoke that base class constructor in its initialiser list.  All of the above (hypothetical) considerations then go away.

Body:
I've got following program:

#include<iostream>
using namespace std;
struct Base01{
    int m;
    Base01():m(2){}
    void p(){cout<<m<<endl;}
};
struct Derived01:public Base01{
    Derived01():m(3){}
};
struct Derived02:virtual public Base01{
    Derived01():m(4){}
};
struct my: Derived01,Derived02{
    my():m(5){}
};
int main(){
    return 0;
}

Both gcc/clang reports compilation error.

I just wish to know what's the language design consideration here, why derived class can only call base class ctor in initialization list, but cannot use base class members directly?


问:
Set margin in btn-group in bootstrap
How can I add top margin and margin in general in btn-group bootstrap. What class I should add and where? Thanks in advance

How can I add top margin and margin in general in btn-group bootstrap. What class I should add and where? Thanks in advance

btn-group

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Golden Titles</title>

    <meta name="description" content="Source code">
    <meta name="author" content="Rahman">

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

  </head>
  <body>

    <div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="btn-group pull-right">

                <button class="btn btn-default" type="button">
                    Sign in
                </button>
                <button class="btn btn-default" type="button">
                    My Account
                </button>
                <button class="btn btn-default" type="button">
                    Help
                </button>

            </div>
        </div>
    </div>
</div>

    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/scripts.js"></script>
  </body>
</html>
</code>```

答:
add new css file (customized-bootstrap.css)

append below code to this file:

```<code>.btn-group button {
    top-margin: 1em !important;
}
</code>```

add this file after bootstrap file in layout page

```<code><link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<link href="../css/customized-bootstrap.css" rel="stylesheet">
</code>```

Title: Set margin in btn-group in bootstrap

Body:
How can I add top margin and margin in general in btn-group bootstrap. What class I should add and where? Thanks in advance

How can I add top margin and margin in general in btn-group bootstrap. What class I should add and where? Thanks in advance

btn-group

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Golden Titles</title>

    <meta name="description" content="Source code">
    <meta name="author" content="Rahman">

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

                <button class="btn btn-default" type="button">
                    Sign in
                </button>
                <button class="btn btn-default" type="button">
                    My Account
                </button>
                <button class="btn btn-default" type="button">
                    Help
                </button>

Body:
add new css file (customized-bootstrap.css)

append below code to this file:

.btn-group button {
    top-margin: 1em !important;
}

add this file after bootstrap file in layout page

<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<link href="../css/customized-bootstrap.css" rel="stylesheet">


问:
Can I 'drop' a PHP request without replying?
I am not completely sure that this is possible from within PHP or even the HTTP protocol in depth. Is it possible to receive PHP script to run when it is requested but then the script drops the connection? Without replying?

Hopefully my question makes sense.

(I am using Apache)

答: That depends on the software you use. Apache for example terminates any scripts as soon as the connection closes.</p>

OwnerDisplayName: gs


问:
How can I make an element on hover?
All I'm trying to do is something like this mechanism:

Here is what I've tried so far:

$(document).ready(function(){
    $('a').bind('mouseenter', function() {
      var self = $(this);
      this.iid = setInterval(function() {
        var tag_name = self.text(),
             top      = self.position().top + self.outerHeight(true),
             left     = self.position().left;
         self.append("
Some explanations about"+tag_name+"
")
         $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
      }, 525);
  }).bind('mouseleave', function(){
     this.iid && clearInterval(this.iid);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  padding: 20px;
}

a {
    color: #3e6d8e !important;
    background-color: #E1ECF4;
    padding: 2px 5px;
}
.tag_info{
  position: reletive;
  width: 130px;
  height: 30px;
  display:none;
  background-color: black;
  color: white;
}</code>```

tag1
tag2```

As you see, it will be repeated every time. How can I execute it once per hover? And why the position doesn't apply?

Also is what I'm doing a right algorithm for such thing?

Thank you.

答:
I am not sure why you are using setInterval but I think this should work. I removed setInterval and everytime the mouseenter event occurs we can append
 and every time mouseleave event occurs we can remove the the appended div.

$(document).ready(function(){
    $('#test').bind('mouseenter', function() {
      var self = $(this);
        var tag_name = self.text(),
             top      = self.position().top + self.outerHeight(true),
             left     = self.position().left;
         self.append("
Some explanations about"+tag_name+"
")
         $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
  }).bind('mouseleave', function(){
     $(this).children('.tag_info').remove();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  padding: 20px;
}

a {
    color: #3e6d8e !important;
    background-color: #E1ECF4;
    padding: 2px 5px;
}
.tag_info{
  position: reletive;
  width: 130px;
  height: 30px;
  display:none;
  background-color: black;
  color: white;
}</code>```

tag1```

Title: How can I make an element on hover?

Body:
All I'm trying to do is something like this mechanism:

Here is what I've tried so far:

$(document).ready(function(){
    $('a').bind('mouseenter', function() {
      var self = $(this);
      this.iid = setInterval(function() {
        var tag_name = self.text(),
             top      = self.position().top + self.outerHeight(true),
             left     = self.position().left;
         self.append("
Some explanations about"+tag_name+"
")
         $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
      }, 525);
  }).bind('mouseleave', function(){
     this.iid && clearInterval(this.iid);
  });
});

body{
  padding: 20px;
}

a {
    color: #3e6d8e !important;
    background-color: #E1ECF4;
    padding: 2px 5px;
}
.tag_info{
  position: reletive;
  width: 130px;
  height: 30px;
  display:none;
  background-color: black;
  color: white;
}

tag1
tag2

As you see, it will be repeated every time. How can I execute it once per hover? And why the position doesn't apply?

Also is what I'm doing a right algorithm for such thing?

Thank you.

Body:
I am not sure why you are using setInterval but I think this should work. I removed setInterval and everytime the mouseenter event occurs we can append <div class='tag_info'> and every time mouseleave event occurs we can remove the the appended div.

$(document).ready(function(){
    $('#test').bind('mouseenter', function() {
      var self = $(this);
        var tag_name = self.text(),
             top      = self.position().top + self.outerHeight(true),
             left     = self.position().left;
         self.append("<div class='tag_info'>Some explanations about"+tag_name+"</div>")
         $(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
  }).bind('mouseleave', function(){
     $(this).children('.tag_info').remove();
  });
});

body{
  padding: 20px;
}

a {
    color: #3e6d8e !important;
    background-color: #E1ECF4;
    padding: 2px 5px;
}
.tag_info{
  position: reletive;
  width: 130px;
  height: 30px;
  display:none;
  background-color: black;
  color: white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="test">tag1</a>


问:
codeigniter login after email verified
I am trying to make sure user can login after confirming their email verification in which STATUS in the database changes from 0 to 1. how do I log users in based on the change of status in the database. Thanks in advance

MODEL:

```<code>   public function login($username, $password){
    //validation
    $this->db->where('username', $username);
    $this->db->where('password', $password);

    $result = $this->db->get('users');
    if($result->num_rows() == 1){
        return $result->row(0)->id;

    } else {
        return FALSE;
    }
}
</code>```

CONTROLLER:

```<code>   public function login(){
    $data['title'] = 'Login';

    $this->form_validation-> set_rules('username', 'Username', 'required');
    $this->form_validation-> set_rules('password', 'Password', 'required');

    if($this->form_validation->run() === FALSE){

    $this->load->view('templates/header');
    $this->load->view('users/login', $data);
    $this->load->view('templates/footer');
    } else {

        // fetching user
    $username = $this->input->post('username');
        //password
    $password = ($this->input->post('password'));

    //login user
    $user_id = $this->user_model->login($username, $password);

    if($user_id){
        //creating session
        $user_data = array(
            'user_id' => $user_id,
            'username' => $username,
            'logged_in' => TRUE,

        );
        $this->session->set_userdata($user_data);
                // Set message to be sent
    $this->session->set_flashdata('user_login', 'Welcome');
    redirect('posts');
    } else {
        // Set message to be sent
    $this->session->set_flashdata('login_fail', 'Login Failed');
    redirect('users/login');
    }

    }

}
</code>```

答:
If you are asking about how to check that user is verified or not then this should be your model code:

```<code>public function login($username, $password){

    $query = $this->db
            ->select('your_column')
            ->where(['user_email' => $user_name, 'user_password' => $user_password])
            ->where('user_verification_status','1')
            ->get('users');

            if ($query->num_rows() == 1) {
                $result = $query->row_array();
                return $result;
            } else {
                return FALSE;
            }

}
</code>```

OR if you want to verify user after registration then you should follow this step:

When Someone Register in your system and when you are saving that user data in your registration table at that time you should use entered email and send the verified link on user email.

In that verification link you have structured it as when user click on it it came to your verification page and at that time you should change the status of user and show message that user is verified and now you can login into the system.

And as the model code given in the answer you should check that user have verified or not.

Please let me know if you need more detail regarding the user verification.

Title: codeigniter login after email verified

Body:
I am trying to make sure user can login after confirming their email verification in which STATUS in the database changes from 0 to 1. how do I log users in based on the change of status in the database. Thanks in advance

MODEL:

   public function login($username, $password){
    //validation
    $this->db->where('username', $username);
    $this->db->where('password', $password);

    $result = $this->db->get('users');
    if($result->num_rows() == 1){
        return $result->row(0)->id;

    } else {
        return FALSE;
    }
}

CONTROLLER:

   public function login(){
    $data['title'] = 'Login';

    $this->form_validation-> set_rules('username', 'Username', 'required');
    $this->form_validation-> set_rules('password', 'Password', 'required');

    if($this->form_validation->run() === FALSE){

    $this->load->view('templates/header');
    $this->load->view('users/login', $data);
    $this->load->view('templates/footer');
    } else {

        // fetching user
    $username = $this->input->post('username');
        //password
    $password = ($this->input->post('password'));

    //login user
    $user_id = $this->user_model->login($username, $password);

    if($user_id){
        //creating session
        $user_data = array(
            'user_id' => $user_id,
            'username' => $username,
            'logged_in' => TRUE,

        );
        $this->session->set_userdata($user_data);
                // Set message to be sent
    $this->session->set_flashdata('user_login', 'Welcome');
    redirect('posts');
    } else {
        // Set message to be sent
    $this->session->set_flashdata('login_fail', 'Login Failed');
    redirect('users/login');
    }

    }

}

Body:
If you are asking about how to check that user is verified or not then this should be your model code:

public function login($username, $password){

    $query = $this->db
            ->select('your_column')
            ->where(['user_email' => $user_name, 'user_password' => $user_password])
            ->where('user_verification_status','1')
            ->get('users');

            if ($query->num_rows() == 1) {
                $result = $query->row_array();
                return $result;
            } else {
                return FALSE;
            }

}

OR if you want to verify user after registration then you should follow this step:

When Someone Register in your system and when you are saving that user data in your registration table at that time you should use entered email and send the verified link on user email.

In that verification link you have structured it as when user click on it it came to your verification page and at that time you should change the status of user and show message that user is verified and now you can login into the system.

And as the model code given in the answer you should check that user have verified or not.

Please let me know if you need more detail regarding the user verification.


问:
AWS Lambda/Cognito Authentication - Assuming Auth Role
I am attempting to create an iOS app in Swift that uses the following authentication service using AWS Lambda - https://github.com/danilop/LambdAuth

It uses the AWS Mobile SDK for iOS to communicate with DynamoDB and Lambda - http://docs.aws.amazon.com/mobile/sdkforios/developerguide/

Here is the sample code for the website that utilizes the token returned from the Lambda login function, I imagine the Swift code will be something similar - https://github.com/danilop/LambdAuth/blob/master/www/login.html#L69

Here is the cloud function that generates the token for the user - https://github.com/danilop/LambdAuth/blob/master/LambdAuthLogin/index.js#L102

I have created an identity pool in AWS Cognito (Federated Identities) and I have two roles, auth and unauth. My application appears to always being the unauth role (arn:aws:sts::123123123:assumed-role/_unauth_MOBILEHUB_123123123/CognitoIdentityCredentials). My users are being stored in a dynamodb table, with a salted password.

The root of the problem is that I don't know the correct Swift code to write after I receive a login token from the service to transition my user into the authenticated role (use the auth arn). I want it to be using the auth role for every service call to AWS (dynamodb, lambda, etc). I'm hoping that someone can point me in the right direction - thank you.

答:
As per the design in Danilo's book, if you are using the aws-sdk javascript , you should define your objects like :

```<code>var creds = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: //hard coded value for your system//
})

AWS.config.update({
    region: 'us-east-1',
    credentials: creds
});

var lambda = new AWS.Lambda();
</code>```

then once you receive your identityId and token , you should assign them to you creds as follow :

```<code>creds.params['IdentityId'] = output.identityId;
creds.params['Logins'] = {};
creds.params['Logins']['cognito-identity.amazonaws.com'] = output.token;
creds.expired = true;
</code>```

where output is the response from your LambdAuthLogin Lambda function.

Body:
As per the design in Danilo's book, if you are using the aws-sdk javascript , you should define your objects like :

var creds = new AWS.CognitoIdentityCredentials({
    IdentityPoolId: //hard coded value for your system//
})

AWS.config.update({
    region: 'us-east-1',
    credentials: creds
});

var lambda = new AWS.Lambda();

then once you receive your identityId and token , you should assign them to you creds as follow :

creds.params['IdentityId'] = output.identityId;
creds.params['Logins'] = {};
creds.params['Logins']['cognito-identity.amazonaws.com'] = output.token;
creds.expired = true;

where output is the response from your LambdAuthLogin Lambda function.


问:
Is lldb working with fortran?
I am trying to breakpoint a fortran program with lldb on a Mac OS 10.12.5 system. I have

```<code>program badcall
      integer a,b
      a=2
      b=3

write(*,*) a, b
end
</code>```

I (have to) compile with the intel compilers.

```<code>ifort -g badcall.f90 -o badcall
</code>```

then I run with lldb and do

```<code>breakpoint set -f badcall.f90 -l 5
</code>```

programs stops normally

```<code>Process 59474 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x0000000100000f35 prova`MAIN__ at badcall.f90:6
   3          a=2
   4          b=3
   5
</code>```

However if I then try to print the variable b I get nothing

```<code>(lldb) p b
(lldb) print b
(lldb) q
</code>```

So am I missing something? Is lldb really usable to debug fortran code?

答:
It seems that lldb doesn't support Fortran, yet :( You will have to go with gdb:

```<code>curl "http://ftp.gnu.org/gnu/gdb/gdb-8.0.tar.gz" -o gdb-8.0.tar.gz
tar zxf gdb-8.0.tar.gz
cd gdb-8.0
./configure
make
</code>```

Make sure to Code Sign the gdb! Follow instructions here:

https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gnat_ugn_unw/Codesigning-the-Debugger.html

and you should be good to go

```<code>gfortran -g -o fort_sample ./fort_sample.f90
gdb ./fort_sample
(gdb) list
1   program badcall
2         integer a,b
3         a=2
4         b=3
5
6   write(*,*) a, b
7   end
(gdb) break 6
Breakpoint 1 at 0x100000e0e: file ./fort_sample.f90, line 6.
(gdb) run
...
...
badcall () at ./fort_sample.f90:6
6   write(*,*) a, b
(gdb) print a
$1 = 2
(gdb) print b
$2 = 3
(gdb)
</code>```

Title: Is lldb working with fortran?

Body:
I am trying to breakpoint a fortran program with lldb on a Mac OS 10.12.5 system. I have

program badcall
      integer a,b
      a=2
      b=3

write(*,*) a, b
end

I (have to) compile with the intel compilers.

ifort -g badcall.f90 -o badcall

then I run with lldb and do

breakpoint set -f badcall.f90 -l 5

programs stops normally

Process 59474 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x0000000100000f35 prova`MAIN__ at badcall.f90:6
   3          a=2
   4          b=3
   5

However if I then try to print the variable b I get nothing

(lldb) p b
(lldb) print b
(lldb) q

So am I missing something? Is lldb really usable to debug fortran code?

Body:
It seems that lldb doesn't support Fortran, yet :( You will have to go with gdb:

curl "http://ftp.gnu.org/gnu/gdb/gdb-8.0.tar.gz" -o gdb-8.0.tar.gz
tar zxf gdb-8.0.tar.gz
cd gdb-8.0
./configure
make

Make sure to Code Sign the gdb! Follow instructions here:

https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gnat_ugn_unw/Codesigning-the-Debugger.html

and you should be good to go

gfortran -g -o fort_sample ./fort_sample.f90
gdb ./fort_sample
(gdb) list
1   program badcall
2         integer a,b
3         a=2
4         b=3
5
6   write(*,*) a, b
7   end
(gdb) break 6
Breakpoint 1 at 0x100000e0e: file ./fort_sample.f90, line 6.
(gdb) run
...
...
badcall () at ./fort_sample.f90:6
6   write(*,*) a, b
(gdb) print a
$1 = 2
(gdb) print b
$2 = 3
(gdb)


问:
How to get values from dynamically generated DOM input elements Java
so I have this HTML code:

```<code><form method="get" action="#" id="startForm">
    <input type="text" name="period" id="period" placeholder="The number of days"/>
    <input type="submit" name="submit" value="submit" id="startSubmit"/>
</form>
</code>```

and this is the JavaScript code:

```<code>var btnSubmit = document.getElementById('startSubmit');
btnSubmit.addEventListener('click', function (e) {

    e.preventDefault();
    var myForm = document.createElement('form');
    var period  = document.getElementById('period').value;

    for(var i = 0; i < period ; i++){

        var input0 = document.createElement('input');

        input0.setAttribute('type', 'text');
        input0.setAttribute('placeholder', 'The count of tasks');
        input0.setAttribute('style', 'margin: 10px');
        input0.setAttribute('id', 'taskDone'+i);
        input0.setAttribute('onchange', 'myFunction()');

        document.body.appendChild(input0);
        myForm.appendChild(input0);
        document.body.appendChild(myForm);

        function myFunction(){
            var  taskDone = document.getElementById('taskDone').value;
            var  newForm = document.createElement('form');

            for(var j = 0; j < taskDone ; j++){

                var input1 = document.createElement('input');

                input1.setAttribute('type', 'text');
                input1.setAttribute('id', 'time'+i);

                document.body.appendChild(input1);
                newForm.appendChild(input1);
                document.body.appendChild(newForm);
            };
        };
    };
    console.log(myForm);
});
</code>```

so my problem is that in the function when I try to take the value from the generated DOM element it will reset the page what I want to do is to take the number that is going to be placed into the input and make as many new inputs textboxes as it's the number is typed (it takes the number from the generated dom element and creates new dom element)

答:
You are just doing the wastage of memory you must not place the definition of function inside a loop. You must place it outside the block or a separate definition. You should only call the function inside loop. However, inside your

```<code>myFunction()
</code>```

you are trying to get the id of an element that doesn't exist as you have created the element with id = 'taskdone'+i. So you must also append 'i' inside the myFunction() to get element ids.
But I will suggest you there is a clean way to this task is just pass the element inside myFunction on changing the element value.
Use something like that :

```<code> `input0.setAttribute('onchange', 'myFunction(this)');`
</code>```

Then you would no longer require the element id to get its value.
And create your myFunction like this:

```<code>  function myFunction(element) {
     var id = element.id;
     var taskDone = element.value;
     var i = id.split('taskDone')[1];
     var newForm = document.createElement('form');

     for (var j = 0; j < taskDone; j++) {

         var input1 = document.createElement('input');

         input1.setAttribute('type', 'text');
         input1.setAttribute('id', 'time' + i);

         document.body.appendChild(input1);
         newForm.appendChild(input1);
         document.body.appendChild(newForm);
     };
 };
</code>```

See the snippet for more details and help:

var btnSubmit = document.getElementById('startSubmit');
  console.log(btnSubmit);
btnSubmit.addEventListener('click', function (e) {

    e.preventDefault();
    var myForm = document.createElement('form');
    var period  = document.getElementById('period').value;

    for(var i = 0; i < period ; i++){

        var input0 = document.createElement('input');

        input0.setAttribute('type', 'text');
        input0.setAttribute('placeholder', 'The count of tasks');
        input0.setAttribute('style', 'margin: 10px');
        input0.setAttribute('id', 'taskDone'+i);
        input0.setAttribute('onchange', 'myFunction(this)');

        document.body.appendChild(input0);
        myForm.appendChild(input0);
        document.body.appendChild(myForm);

    };
    console.log(myForm);
});
 function myFunction(element){
            var  id = element.id;
   var taskDone = element.value;
   var i = id.split('taskDone')[1];
            var  newForm = document.createElement('form');

            for(var j = 0; j < taskDone ; j++){

                var input1 = document.createElement('input');

                input1.setAttribute('type', 'text');
                input1.setAttribute('id', 'time'+i);

                document.body.appendChild(input1);
                newForm.appendChild(input1);
                document.body.appendChild(newForm);
            };
        };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="get" action="#" id="startForm">
    <input type="text" name="period" id="period" placeholder="The number of days"/>
    <input type="submit" name="submit" value="submit" id="startSubmit"/>
</form></code>```

Body:
so I have this HTML code:

<form method="get" action="#" id="startForm">
    <input type="text" name="period" id="period" placeholder="The number of days"/>
    <input type="submit" name="submit" value="submit" id="startSubmit"/>
</form>

and this is the JavaScript code:

var btnSubmit = document.getElementById('startSubmit');
btnSubmit.addEventListener('click', function (e) {

    e.preventDefault();
    var myForm = document.createElement('form');
    var period  = document.getElementById('period').value;

    for(var i = 0; i < period ; i++){

        var input0 = document.createElement('input');

        input0.setAttribute('type', 'text');
        input0.setAttribute('placeholder', 'The count of tasks');
        input0.setAttribute('style', 'margin: 10px');
        input0.setAttribute('id', 'taskDone'+i);
        input0.setAttribute('onchange', 'myFunction()');

        document.body.appendChild(input0);
        myForm.appendChild(input0);
        document.body.appendChild(myForm);

        function myFunction(){
            var  taskDone = document.getElementById('taskDone').value;
            var  newForm = document.createElement('form');

            for(var j = 0; j < taskDone ; j++){

                var input1 = document.createElement('input');

                input1.setAttribute('type', 'text');
                input1.setAttribute('id', 'time'+i);

                document.body.appendChild(input1);
                newForm.appendChild(input1);
                document.body.appendChild(newForm);
            };
        };
    };
    console.log(myForm);
});

so my problem is that in the function when I try to take the value from the generated DOM element it will reset the page what I want to do is to take the number that is going to be placed into the input and make as many new inputs textboxes as it's the number is typed (it takes the number from the generated dom element and creates new dom element)

Body:
You are just doing the wastage of memory you must not place the definition of function inside a loop. You must place it outside the block or a separate definition. You should only call the function inside loop. However, inside your

myFunction()

you are trying to get the id of an element that doesn't exist as you have created the element with id = 'taskdone'+i. So you must also append 'i' inside the myFunction() to get element ids.
But I will suggest you there is a clean way to this task is just pass the element inside myFunction on changing the element value.
Use something like that :

 `input0.setAttribute('onchange', 'myFunction(this)');`

Then you would no longer require the element id to get its value.
And create your myFunction like this:

  function myFunction(element) {
     var id = element.id;
     var taskDone = element.value;
     var i = id.split('taskDone')[1];
     var newForm = document.createElement('form');

     for (var j = 0; j < taskDone; j++) {

         var input1 = document.createElement('input');

         input1.setAttribute('type', 'text');
         input1.setAttribute('id', 'time' + i);

         document.body.appendChild(input1);
         newForm.appendChild(input1);
         document.body.appendChild(newForm);
     };
 };

See the snippet for more details and help:

var btnSubmit = document.getElementById('startSubmit');
  console.log(btnSubmit);
btnSubmit.addEventListener('click', function (e) {

    e.preventDefault();
    var myForm = document.createElement('form');
    var period  = document.getElementById('period').value;

    for(var i = 0; i < period ; i++){

        var input0 = document.createElement('input');

        input0.setAttribute('type', 'text');
        input0.setAttribute('placeholder', 'The count of tasks');
        input0.setAttribute('style', 'margin: 10px');
        input0.setAttribute('id', 'taskDone'+i);
        input0.setAttribute('onchange', 'myFunction(this)');

        document.body.appendChild(input0);
        myForm.appendChild(input0);
        document.body.appendChild(myForm);

    };
    console.log(myForm);
});
 function myFunction(element){
            var  id = element.id;
   var taskDone = element.value;
   var i = id.split('taskDone')[1];
            var  newForm = document.createElement('form');

            for(var j = 0; j < taskDone ; j++){

                var input1 = document.createElement('input');

                input1.setAttribute('type', 'text');
                input1.setAttribute('id', 'time'+i);

                document.body.appendChild(input1);
                newForm.appendChild(input1);
                document.body.appendChild(newForm);
            };
        };

<form method="get" action="#" id="startForm">
    <input type="text" name="period" id="period" placeholder="The number of days"/>
    <input type="submit" name="submit" value="submit" id="startSubmit"/>
</form>


问:
calculating sum of values after combining results of multiple AJAX calls.
I am trying to write a JS function which calculates the sum of all visible rows in a column in a table.
The way the values in the column is filled is by making multiple ajax calls (50 rows at a time).

I am trying to keep track of no of requests sent and when I receive all responses back  calculate the sum.

```<code>function onClickofCalculateButton() {
    var noOfRequestsSent = 0;
    var sum = 0;

    var sucCallback = function(response) {
        updateColumn(response, noOfRequestsSent, sum);
    };

    //Some logic to send requests 50 rows a time and I increment the value of noOfRequestsSent;
}
</code>```

in my updateColumn function()

```<code>function updateColumn(response, noOfRequestsSent, sum) {
    noOfRequestsSent--;
    //Do some logic to retrieve value of each row and add it to sum
    if(noOfRequestsSent == 0) {
        alert(sum);
    }
}
</code>```

However what is happening is the value of noOfRequestsSent is always equal to the actual number of requestssent even after subtracting it in updateColumn function. So it never reaches the condition where noOfRequestsSent == 0 and neither does the sum get added onto the previous value.

I guess I have to pass some object reference or something like pointers in C but I am unable to figure out how to do in JS.

答:
You could try like this. Since you want to send variable as reference. In this way you can avoid global variables.</p>

```<code>function onClickofCalculateButton() {
    var noOfRequests = {
                       sent:0
                       };
    var sum = 0;

    var sucCallback = function(response) {
        updateColumn(response, noOfRequests, sum);
    };

    //Some logic to send requests 50 rows a time and I increment the value of noOfRequestsSent;
}

function updateColumn(response, noOfRequestsSent, sum) {
    noOfRequests.sent--;
    //Do some logic to retrieve value of each row and add it to sum
    if(noOfRequests.sent == 0) {
        alert(sum);
    }
}
</code>```

Body:
I am trying to write a JS function which calculates the sum of all visible rows in a column in a table.
The way the values in the column is filled is by making multiple ajax calls (50 rows at a time).

I am trying to keep track of no of requests sent and when I receive all responses back  calculate the sum.

function onClickofCalculateButton() {
    var noOfRequestsSent = 0;
    var sum = 0;

    var sucCallback = function(response) {
        updateColumn(response, noOfRequestsSent, sum);
    };

    //Some logic to send requests 50 rows a time and I increment the value of noOfRequestsSent;
}

in my updateColumn function()

function updateColumn(response, noOfRequestsSent, sum) {
    noOfRequestsSent--;
    //Do some logic to retrieve value of each row and add it to sum
    if(noOfRequestsSent == 0) {
        alert(sum);
    }
}

However what is happening is the value of noOfRequestsSent is always equal to the actual number of requestssent even after subtracting it in updateColumn function. So it never reaches the condition where noOfRequestsSent == 0 and neither does the sum get added onto the previous value.

I guess I have to pass some object reference or something like pointers in C but I am unable to figure out how to do in JS.

Body:
You could try like this. Since you want to send variable as reference. In this way you can avoid global variables.

function onClickofCalculateButton() {
    var noOfRequests = {
                       sent:0
                       };
    var sum = 0;

    var sucCallback = function(response) {
        updateColumn(response, noOfRequests, sum);
    };

    //Some logic to send requests 50 rows a time and I increment the value of noOfRequestsSent;
}

function updateColumn(response, noOfRequestsSent, sum) {
    noOfRequests.sent--;
    //Do some logic to retrieve value of each row and add it to sum
    if(noOfRequests.sent == 0) {
        alert(sum);
    }
}


问:
Subsetting by index rows not working in R?
I've done this thousands of times, but I know I'm missing something here. I want to subset a data frame I have by the columns that match up in another one. However, the standard process doesn't seem to be working. Here's what I have:

```<code>a <- as.character(df1$col1)
b <- names(df2)
df2[(b %in% a), ]
</code>```

Now the final line doesn't appear to do anything. No errors, but the b %in% a bit certainly doesn't return all TRUE.

```<code>a[1:10]
"2.5D"             "2D"               "2DFighter"        "3DPlatformer"    "3DVision"         "4PlayerLocal"     "4X"               "Abstract"        "Action"           "Action-Adventure"

b[1:10]
"appid"            "2.5D"             "2D"               "4PlayerLocal"    "6DOF"             "Action"           "Action-Adventure" "ActionRPG"       "Adventure"        "Anime"

b[1:10] %in% a[1:10]
FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE FALSE FALSE

names(df2[(b %in% a), ])
"appid"            "2.5D"             "2D"               "4PlayerLocal"    "6DOF"             "Action"           "Action-Adventure" "ActionRPG"       "Adventure"        "Anime"
</code>```

What I want is df2 to be subset by the matching columns in df1. I want to say this is the right approach, as I even have both the vectors that I'm matching with %in% are both the same character format. Yet the columnar subset appears to not be doing anything.

Is there anything immediately obvious as to what I'm doing wrong here?

答:
What's important here is that when subsetting using df[a,b], the a subsets rows, and the b subsets columns.

This(as mentioned by @Kevin in the comments):

```<code>df2[(b %in% a), ]
</code>```

is subsetting some rows out of the data frame, meaning all columns are still present. To subset columns instead, we need:

```<code>df2[ ,(b %in% a) ]
</code>```

Body:
I've done this thousands of times, but I know I'm missing something here. I want to subset a data frame I have by the columns that match up in another one. However, the standard process doesn't seem to be working. Here's what I have:

a <- as.character(df1$col1)
b <- names(df2)
df2[(b %in% a), ]

Now the final line doesn't appear to do anything. No errors, but the b %in% a bit certainly doesn't return all TRUE.

a[1:10]
"2.5D"             "2D"               "2DFighter"        "3DPlatformer"    "3DVision"         "4PlayerLocal"     "4X"               "Abstract"        "Action"           "Action-Adventure"

b[1:10]
"appid"            "2.5D"             "2D"               "4PlayerLocal"    "6DOF"             "Action"           "Action-Adventure" "ActionRPG"       "Adventure"        "Anime"

b[1:10] %in% a[1:10]
FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE FALSE FALSE

names(df2[(b %in% a), ])
"appid"            "2.5D"             "2D"               "4PlayerLocal"    "6DOF"             "Action"           "Action-Adventure" "ActionRPG"       "Adventure"        "Anime"

What I want is df2 to be subset by the matching columns in df1. I want to say this is the right approach, as I even have both the vectors that I'm matching with %in% are both the same character format. Yet the columnar subset appears to not be doing anything.

Is there anything immediately obvious as to what I'm doing wrong here?

Body:
What's important here is that when subsetting using df[a,b], the a subsets rows, and the b subsets columns.

This(as mentioned by @Kevin in the comments):

df2[(b %in% a), ]

is subsetting some rows out of the data frame, meaning all columns are still present. To subset columns instead, we need:

df2[ ,(b %in% a) ]


问:
ScrollView does not show full content?
I have a Constraint Layout and within that I have an ImageView. I put a Linear Layout in my XML underneath that for some ImageButtons  I want my app to scroll through. I researched and found that I need to wrap my Linear Layout in a ScrollView which I did but for some reason it will not show the bottom of my content. It cuts off the bottom of the view in the emulator.
I tried wrapping the ScrollView in a Relative Layout which was suggested in one of the forums but that did nothing. I also tried setting the ScrollView with android:fillViewport="true" but that did not work either. I will attach screen shot of what it looks like and I will paste XML below that.

screenshot of app with content not showing at bottom

```<code><?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.autismacademyed.www.autismacademy.AutismAcademy">

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/logo" />

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/imageView2">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:layout_marginTop="0dp"
        android:orientation="vertical"
        android:scrollIndicators="right|end"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:layout_constraintVertical_bias="0.0">

        <ImageButton
            android:id="@+id/imageButtonRed"
            android:layout_width="104dp"
            android:layout_height="124dp"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:background="@null"
            android:onClick="imageButtonOnClick"
            android:scaleType="centerCrop"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imageButtonYellow"
            app:srcCompat="@drawable/ic_action_red" />

        <ImageButton
            android:id="@+id/imageButtonBlue"
            android:layout_width="125dp"
            android:layout_height="110dp"
            android:layout_marginTop="8dp"
            android:background="@null"
            android:scaleType="centerCrop"
            app:layout_constraintTop_toBottomOf="@+id/imageButtonRed"
            app:srcCompat="@drawable/ic_action_blue"
            tools:layout_editor_absoluteX="0dp" />

        <ImageButton
            android:id="@+id/imageButtonYellow"
            android:layout_width="109dp"
            android:layout_height="125dp"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:background="@null"
            android:onClick="imageButtonOnClick"
            android:scaleType="centerCrop"
            android:visibility="visible"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imageView2"
            app:srcCompat="@mipmap/ic_yellowpuzzlepiece" />

        <ImageButton
            android:id="@+id/imageButtonGreen"
            android:layout_width="109dp"
            android:layout_height="125dp"
            android:background="@null"
            android:scaleType="centerCrop"
            app:layout_constraintTop_toBottomOf="@+id/imageButtonYellow"
            app:srcCompat="@drawable/ic_action_green" />

        <ImageButton
            android:id="@+id/imageButtonBrown"
            android:layout_width="109dp"
            android:layout_height="125dp"
            android:background="@null"
            android:scaleType="centerCrop"
            app:layout_constraintTop_toBottomOf="@+id/imageButtonYellow"
            app:srcCompat="@drawable/ic_action_green" />

    </LinearLayout>

</ScrollView>

</android.support.constraint.ConstraintLayout>
</code>```

答:
So after doing a considerable amount of research on this forums site and through video tutorials I decided to post this question. I apologize to waste other people's time but I noticed on the left related questions! I found an article that was similar enough to my layout that when reading it I understood how to solve my own problem! I messed around with the code and removed the Linear Layout from my XML and replaced it with another Constraint Layout. I also added the fillViewPort line of code to ScrollView and removed the Layout Width and Height and changed it to 0dp. I use the constraints option to have the ScrollView fit properly in the Emulator and I did the same things for the ImageButtons to align on top of each other properly. I will link the article that helped me! </p>

<p>Bottom of ScrollView clipped when using ConstraintLayout </p>

Title: ScrollView does not show full content?

Body:
I have a Constraint Layout and within that I have an ImageView. I put a Linear Layout in my XML underneath that for some ImageButtons  I want my app to scroll through. I researched and found that I need to wrap my Linear Layout in a ScrollView which I did but for some reason it will not show the bottom of my content. It cuts off the bottom of the view in the emulator.
I tried wrapping the ScrollView in a Relative Layout which was suggested in one of the forums but that did nothing. I also tried setting the ScrollView with android:fillViewport="true" but that did not work either. I will attach screen shot of what it looks like and I will paste XML below that.

screenshot of app with content not showing at bottom

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.autismacademyed.www.autismacademy.AutismAcademy">

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/logo" />

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/imageView2">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="0dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:layout_marginTop="0dp"
        android:orientation="vertical"
        android:scrollIndicators="right|end"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:layout_constraintVertical_bias="0.0">

        <ImageButton
            android:id="@+id/imageButtonRed"
            android:layout_width="104dp"
            android:layout_height="124dp"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:background="@null"
            android:onClick="imageButtonOnClick"
            android:scaleType="centerCrop"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imageButtonYellow"
            app:srcCompat="@drawable/ic_action_red" />

        <ImageButton
            android:id="@+id/imageButtonBlue"
            android:layout_width="125dp"
            android:layout_height="110dp"
            android:layout_marginTop="8dp"
            android:background="@null"
            android:scaleType="centerCrop"
            app:layout_constraintTop_toBottomOf="@+id/imageButtonRed"
            app:srcCompat="@drawable/ic_action_blue"
            tools:layout_editor_absoluteX="0dp" />

        <ImageButton
            android:id="@+id/imageButtonYellow"
            android:layout_width="109dp"
            android:layout_height="125dp"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:background="@null"
            android:onClick="imageButtonOnClick"
            android:scaleType="centerCrop"
            android:visibility="visible"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imageView2"
            app:srcCompat="@mipmap/ic_yellowpuzzlepiece" />

        <ImageButton
            android:id="@+id/imageButtonGreen"
            android:layout_width="109dp"
            android:layout_height="125dp"
            android:background="@null"
            android:scaleType="centerCrop"
            app:layout_constraintTop_toBottomOf="@+id/imageButtonYellow"
            app:srcCompat="@drawable/ic_action_green" />

        <ImageButton
            android:id="@+id/imageButtonBrown"
            android:layout_width="109dp"
            android:layout_height="125dp"
            android:background="@null"
            android:scaleType="centerCrop"
            app:layout_constraintTop_toBottomOf="@+id/imageButtonYellow"
            app:srcCompat="@drawable/ic_action_green" />

    </LinearLayout>

</ScrollView>

</android.support.constraint.ConstraintLayout>

Body:
So after doing a considerable amount of research on this forums site and through video tutorials I decided to post this question. I apologize to waste other people's time but I noticed on the left related questions! I found an article that was similar enough to my layout that when reading it I understood how to solve my own problem! I messed around with the code and removed the Linear Layout from my XML and replaced it with another Constraint Layout. I also added the fillViewPort line of code to ScrollView and removed the Layout Width and Height and changed it to 0dp. I use the constraints option to have the ScrollView fit properly in the Emulator and I did the same things for the ImageButtons to align on top of each other properly. I will link the article that helped me!

Bottom of ScrollView clipped when using ConstraintLayout


问:
Maximum number of pairs
I need to find out the maximum number of pairs of 1's and 0's that can be found by just altering a single number in a given array.

For example:

If my input is {1,0,0,1,0,0}, here at index position 3 if I replace  1 with 0 then I will get 4 pairs i.e the arrays becomes {1,0,0,0,0,0}, and the pairs are (1,2), (2,3), (3,4), (4,5).

But if I replace index position 0 from 1 to 0 then the array is {0,0,0,1,0,0} here I will get only 3 pairs i.e (0,1), (1,2), (4,5)

I need a program that returns maximum number of pairs possible for a given input array. In this case the program should give 4 as result.

Here the array contains only 1's and 0's.

Here is my program:

```<code>public class Program {

    public static void main(String[] args) {
        Program program = new Program();
        int[] a = { 1, 0, 0, 1, 0, 1 };
        int response = program.calculate(a);
        System.out.println(response);
    }

    int calculate(int[] input) {
        if(input == null || input.length == 0) {
            return -1;
        }
        int length = input.length;
        int result = 0;
        for (int i = 0; i < length - 1; i++) {
            if (input[i] == input[i + 1]) {
                result = result + 1;
            }
        }
        int temp = 0;
        for (int i = 0; i < length - 1; i++) {
            int count = 0;
            if (i > 0) {
                if (input[i - 1] != input[i]) {
                    count = count + 1;
                } else {
                    count = count - 1;
                }
            }

            if (i < length - 1) {
                if (input[i + 1] != input[i]) {
                    count = count + 1;
                } else {
                    count = count - 1;
                }
            }

            temp = Math.max(temp, count);
        }
        return result + temp;
    }
}
</code>```

I was told the program is having some bugs but I was not able to find out where the issue is. I tried passing various values to this program but it is still working without issues. Can you please help me with some combination of inputs for which this program fails.

Title: Maximum number of pairs

Body:
I need to find out the maximum number of pairs of 1's and 0's that can be found by just altering a single number in a given array.

For example:

If my input is {1,0,0,1,0,0}, here at index position 3 if I replace  1 with 0 then I will get 4 pairs i.e the arrays becomes {1,0,0,0,0,0}, and the pairs are (1,2), (2,3), (3,4), (4,5).

But if I replace index position 0 from 1 to 0 then the array is {0,0,0,1,0,0} here I will get only 3 pairs i.e (0,1), (1,2), (4,5)

I need a program that returns maximum number of pairs possible for a given input array. In this case the program should give 4 as result.

Here the array contains only 1's and 0's.

Here is my program:

public class Program {

    public static void main(String[] args) {
        Program program = new Program();
        int[] a = { 1, 0, 0, 1, 0, 1 };
        int response = program.calculate(a);
        System.out.println(response);
    }

    int calculate(int[] input) {
        if(input == null || input.length == 0) {
            return -1;
        }
        int length = input.length;
        int result = 0;
        for (int i = 0; i < length - 1; i++) {
            if (input[i] == input[i + 1]) {
                result = result + 1;
            }
        }
        int temp = 0;
        for (int i = 0; i < length - 1; i++) {
            int count = 0;
            if (i > 0) {
                if (input[i - 1] != input[i]) {
                    count = count + 1;
                } else {
                    count = count - 1;
                }
            }

            if (i < length - 1) {
                if (input[i + 1] != input[i]) {
                    count = count + 1;
                } else {
                    count = count - 1;
                }
            }

            temp = Math.max(temp, count);
        }
        return result + temp;
    }
}

I was told the program is having some bugs but I was not able to find out where the issue is. I tried passing various values to this program but it is still working without issues. Can you please help me with some combination of inputs for which this program fails.

Body:
Well, it seems to be failing for

{ 0, 0, 0, 0, 0, 0, 1}; -> 5 but not {0, 1}; -> 1
{ 1, 0, 1}; -> 2
{ 1, 1, 1}; -> 2
{ 1,0,0,0,0,1,1,0,0,0}; -> 7


问:
How to react to changes in SimpleForm Inputs?
I'm making a custom input component that needs to change when other input values are changed in the form.

```<code><ReferenceInput source="foo">
  <SelectInput />
</ReferenceInput>
<NumberInput onChange={(e, newValue) => {this.setState({ newValue })} />
<CustomInput numberValue={this.state.newValue} />
</code>```

When NumberInput changes, I can pass CustomInput the new value. But ReferenceInput / SelectInput doesn't have an onChange. How do I get the new value of SelectInput to the CustomInput? (Note that inside CustomInput, props.record.foo doesn't update when ReferenceInput changes.)

答:
Check out aor dependent input

https://github.com/marmelab/aor-dependent-input

Body:
I'm making a custom input component that needs to change when other input values are changed in the form.

<ReferenceInput source="foo">
  <SelectInput />
</ReferenceInput>
<NumberInput onChange={(e, newValue) => {this.setState({ newValue })} />
<CustomInput numberValue={this.state.newValue} />

When NumberInput changes, I can pass CustomInput the new value. But ReferenceInput / SelectInput doesn't have an onChange. How do I get the new value of SelectInput to the CustomInput? (Note that inside CustomInput, props.record.foo doesn't update when ReferenceInput changes.)