问:
How do I get data from a text file into a jtable?
How can I display the contents of my text file into a jTable?</p>

```<code>String fileName = "/Users/JJ/Desktop/SSD Text.txt";

// This will reference one line at a time
String line = null;

try {
    // FileReader reads text files in the default encoding.
   FileReader fileReader = new FileReader(fileName);

    // Wraps FileReader in BufferedReader.
    BufferedReader bufferedReader =
        new BufferedReader(fileReader);
    int i = 0;
    int x= 0;
    Object[][] myarray = new String [4][100];
    while((line = bufferedReader.readLine()) != null) {
      x=0;
        for (String retval: line.split (",")) {
        myarray[x][i]=retval;
        }
</code>```

答:
The following code reads data from a file and puts it in column 1 of a JTable. I hope this can help you. </p>

```<code>import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class Main {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            public void run() {
                new Main().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {

        try {
            JFrame frame = new JFrame();
            frame.setLayout(new BorderLayout());
            JTable table = new JTable();

            String readLine = null;

            StudentTableModel tableModel = new StudentTableModel();
            File file = new File("/home/developer/ffmpeg.txt"/*Give your File Path here*/);

            FileReader reader = new FileReader(file);
            BufferedReader bufReader = new BufferedReader(reader);

            List<Line> studentList = new ArrayList<Line>();
            while((readLine = bufReader.readLine()) != null) {
                String[] splitData = readLine.split(";");

                Line line = new Line();
                line.setName(splitData[0]);
                studentList.add(line);
            }

            tableModel.setList(studentList);
            table.setModel(tableModel);

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new JScrollPane(table));
            frame.setTitle("File to JTable");
            frame.pack();
            frame.setVisible(true);

        } catch(IOException ex) {}
    }

    class Line {

        private String name;
        private String number;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

    class StudentTableModel extends AbstractTableModel {

        private List<Line> list = new ArrayList<Line>();
        private String[] columnNames = {"column1", "column2"};

        public void setList(List<Line> list) {
            this.list = list;
            fireTableDataChanged();
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        public int getRowCount() {
            return list.size();
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            switch (columnIndex) {
                case 0:
                    return list.get(rowIndex).getName();
                default:
                    return null;
            }
        }
    }
}
</code>```

Body:
How can I display the contents of my text file into a jTable?

String fileName = "/Users/JJ/Desktop/SSD Text.txt";

// This will reference one line at a time
String line = null;

try {
    // FileReader reads text files in the default encoding.
   FileReader fileReader = new FileReader(fileName);

    // Wraps FileReader in BufferedReader.
    BufferedReader bufferedReader =
        new BufferedReader(fileReader);
    int i = 0;
    int x= 0;
    Object[][] myarray = new String [4][100];
    while((line = bufferedReader.readLine()) != null) {
      x=0;
        for (String retval: line.split (",")) {
        myarray[x][i]=retval;
        }

Body:
The following code reads data from a file and puts it in column 1 of a JTable. I hope this can help you.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class Main {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            public void run() {
                new Main().createUI();
            }
        };

        EventQueue.invokeLater(r);
    }

    private void createUI() {

        try {
            JFrame frame = new JFrame();
            frame.setLayout(new BorderLayout());
            JTable table = new JTable();

            String readLine = null;

            StudentTableModel tableModel = new StudentTableModel();
            File file = new File("/home/developer/ffmpeg.txt"/*Give your File Path here*/);

            FileReader reader = new FileReader(file);
            BufferedReader bufReader = new BufferedReader(reader);

            List<Line> studentList = new ArrayList<Line>();
            while((readLine = bufReader.readLine()) != null) {
                String[] splitData = readLine.split(";");

                Line line = new Line();
                line.setName(splitData[0]);
                studentList.add(line);
            }

            tableModel.setList(studentList);
            table.setModel(tableModel);

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new JScrollPane(table));
            frame.setTitle("File to JTable");
            frame.pack();
            frame.setVisible(true);

        } catch(IOException ex) {}
    }

    class Line {

        private String name;
        private String number;

        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }

    class StudentTableModel extends AbstractTableModel {

        private List<Line> list = new ArrayList<Line>();
        private String[] columnNames = {"column1", "column2"};

        public void setList(List<Line> list) {
            this.list = list;
            fireTableDataChanged();
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        public int getRowCount() {
            return list.size();
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            switch (columnIndex) {
                case 0:
                    return list.get(rowIndex).getName();
                default:
                    return null;
            }
        }
    }
}


来源: stackexchange

问:
jquery mask input plugin only set day value of the date
I am using masked-input-plugin. Only day part need to change but month and year not need to change. Here is my code.

```<code>$("#id").mask("99/06/2017",{placeholder:"dd/mm/yyyy"});
</code>```

During the input time :
it seeing like dd/06/2017 but if I select the input box then remove the cursor(without pressing any number) that time it's show something like as 06/06/2017

I have seen
this question and answer

I am very sorry for my poor English.

Thanks in advance.

答:
At last, I am able to solve the problem. I am posting this answer, so anybody can get help.

Firstly, extend the mask function of the mask input plugin. Then customized some code to solve this problem.

For the solution please visit this link

ContentLicense: CC BY-SA 3.0

Body:
I am using masked-input-plugin. Only day part need to change but month and year not need to change. Here is my code.

$("#id").mask("99/06/2017",{placeholder:"dd/mm/yyyy"});

During the input time :
it seeing like dd/06/2017 but if I select the input box then remove the cursor(without pressing any number) that time it's show something like as 06/06/2017

I have seen
this question and answer

I am very sorry for my poor English.

Thanks in advance.


问:
Implement poisson disk sampling in linear time
I’m trying to implement the noise generator (Poisson disk noise) demonstrated here and described here, but I don’t know how to make it run in linear time due to the requirement that a random active sample (the red dots in the example) be popped from the active sample queue. As far as I can tell, this step itself has linear complexity since the sample isn’t popped from the end or dequeued from the beginning of the queue, making the whole algorithm quadratic.

How do I make the noise generator truly linear in time? As far as I can tell, this requires a sequence that a random element can be removed from in constant time.

答:
As far as I can see, the only operations you need to perform on this queue are to select and remove a random element, and to add new elements. In particular, you don't need to preserve order.

To implement this I would use a class supporting a variable length array, such as std::vector or java.util.ArrayList. To add an element, just add one on the end with push_back() or add(). To remove a random element, pick a random element within the array, save it, copy the element at the end of the array over element that you have just saved, and then reduce the size of the array by one. Something like

index = rng.nex()tInt(arr.size());

toReturn = arr.get(index);

arr.set(index, arr.get(arr.size() - 1));

arr.resize(arr.size() - 1);

return toReturn;


问:
replace every second line of my triangle with a blank line for loops
instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this

```<code>  5

 555

55555
</code>```

This is my code:

```<code> for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");
    }
       System.out.println();
}
</code>```

答:
Try this

```<code>for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");   //Use 5 instaed of * to draw
    }
       System.out.println();
       System.out.println();     //This one will solve your problem
}
</code>```

Output will be:

```<code>     5

    555

   55555

  5555555

 555555555
</code>```

Body:
instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this

  5

 555

55555

This is my code:

 for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");
    }
       System.out.println();
}

Body:
Try this

for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");   //Use 5 instaed of * to draw
    }
       System.out.println();
       System.out.println();     //This one will solve your problem
}

Output will be:

     5

    555

   55555

  5555555

 555555555


问:
How to connect to local host using JDBC?
I installed MySql on my own machine. I created database, create table, ... using MySql CommandLine Client. When working on a project in school, I connected to school's database using this syntax:

```<code>public static Statement connect() {
  try {
   Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
   conn = DriverManager.getConnection( "1", "2", "3" );
   stmt = conn.createStatement();
  }
  catch( Exception e ) {
   System.out.println( "Connection Error:  " + e );
  }
  return stmt;
 }
</code>```

In my local machine, I don't have to type in user name, all I did is just login with my password as root user:

```<code>Enter password: ****
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.53-community MySQL Community Server (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use chandb;
Database changed
mysql> show tables;
+------------------+
| Tables_in_chandb |
+------------------+
| another          |
| cars             |
| employees        |
+------------------+
3 rows in set (0.03 sec)

mysql> select * from Another;
+----+-----------+----------+
| Id | GoldValue | Model    |
+----+-----------+----------+
|  0 |       100 | Civic DX |
+----+-----------+----------+
1 row in set (0.00 sec)

mysql>
</code>```

I would like to know how can I connect to my local machine's database? what should I put as parameters within method .getConnection

```<code>conn = DriverManager.getConnection(
   "1", // ?
   "2", // ?
   "3"  ); // ?
</code>```

Best regards,

Chan

答:
Simple Connection:

```<code>import java.sql.Connection;
import java.sql.DriverManager;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "org.gjt.mm.mysql.Driver";
    Class.forName(driverName);

    String serverName = "localhost";
    String mydatabase = "mydatabase";
    String url = "jdbc:mysql://" + serverName + "/" + mydatabase;

    String username = "username";
    String password = "password";
    Connection connection = DriverManager.getConnection(url, username, password);
  }
}
</code>```

Body:
I installed MySql on my own machine. I created database, create table, ... using MySql CommandLine Client. When working on a project in school, I connected to school's database using this syntax:

public static Statement connect() {
  try {
   Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
   conn = DriverManager.getConnection( "1", "2", "3" );
   stmt = conn.createStatement();
  }
  catch( Exception e ) {
   System.out.println( "Connection Error:  " + e );
  }
  return stmt;
 }

In my local machine, I don't have to type in user name, all I did is just login with my password as root user:

Enter password: ****
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.53-community MySQL Community Server (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use chandb;
Database changed
mysql> show tables;
+------------------+
| Tables_in_chandb |
+------------------+
| another          |
| cars             |
| employees        |
+------------------+
3 rows in set (0.03 sec)

mysql> select * from Another;
+----+-----------+----------+
| Id | GoldValue | Model    |
+----+-----------+----------+
|  0 |       100 | Civic DX |
+----+-----------+----------+
1 row in set (0.00 sec)

mysql>

I would like to know how can I connect to my local machine's database? what should I put as parameters within method .getConnection

conn = DriverManager.getConnection(
   "1", // ?
   "2", // ?
   "3"  ); // ?

Best regards,

Chan

Body:
Simple Connection:

import java.sql.Connection;
import java.sql.DriverManager;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "org.gjt.mm.mysql.Driver";
    Class.forName(driverName);

    String serverName = "localhost";
    String mydatabase = "mydatabase";
    String url = "jdbc:mysql://" + serverName + "/" + mydatabase;

    String username = "username";
    String password = "password";
    Connection connection = DriverManager.getConnection(url, username, password);
  }
}

ContentLicense: CC BY-SA 2.5


问:
Google Maps in jQuery Accordion works in jsFiddle, but maps do not load on my server until window MANUALLY resized
I am trying to simply make an expanding list of Google Maps which allow you to locate an item.  Here I have a static HTML page where you can click records and they will expand to show you a Google Map.  The map, however, only comes through as grey until you resize the page.

Here is the page with the problem (the extension says php, but it doesn't actually have any): https://yt074.addons.la/tmp/track/list.php

I'm already calling google.maps.event.trigger(maps[i], 'resize'); within the code (as you can see by viewing source), and I have tried jQuery(window).trigger('resize');, window.dispatchEvent(new Event('resize')); and a few others to simulate a resizing of the window, but to no avail.

Here is a jsFiddle with the code from above literally copy/pasted into the fiddle and it works: https://jsfiddle.net/myingling/Lkdmp1zo/

Or here is a shorter version on my server which is not working: https://yt074.addons.la/tmp/track/fiddle.php

What am I missing on my server?  Server is ubuntu running nginx on an AWS EC2 cluster, but once the code is client-side I don't understand why that would matter (but better safe to explain).

答:
The problem is that your .map elements are hidden when Google Maps is initialised. You can test this by setting the first accordion panel to being open by default, and then the map renders.

To fix the problem, you need to trigger a resize event when the accordion panel is opened. The following revised version of your code does that. I've tested this with the example hosted on your server and it works.

```<code>(function ($) {
    var maps = [];

    var $accordion = $('#accordion').accordion({
        active: false,
        collapsible: true
    });

    $accordion.on('accordionactivate', function(event, ui) {
        var map = ui.newPanel.find('.map').data('map');
        google.maps.event.trigger(map, 'resize');
        map.setCenter(map._center);
    });

    $accordion.find('.map').each(function(i, o) {
        var latLong = new google.maps.LatLng($(o).data('lat'), $(o).data('long'));

        var map = new google.maps.Map(o, {
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.ROAD,
            center: latLong
        });

        maps.push(map);

        var marker = new google.maps.Marker({
            position: latLong,
            map: map,
            title: $(o).data('time')
        });

        map.setCenter(latLong);
        map._center = latLong;

        $(o).data('map', map);
    });

})(jQuery)
</code>```

Body:
The problem is that your .map elements are hidden when Google Maps is initialised. You can test this by setting the first accordion panel to being open by default, and then the map renders.

To fix the problem, you need to trigger a resize event when the accordion panel is opened. The following revised version of your code does that. I've tested this with the example hosted on your server and it works.

(function ($) {
    var maps = [];

    var $accordion = $('#accordion').accordion({
        active: false,
        collapsible: true
    });

    $accordion.on('accordionactivate', function(event, ui) {
        var map = ui.newPanel.find('.map').data('map');
        google.maps.event.trigger(map, 'resize');
        map.setCenter(map._center);
    });

    $accordion.find('.map').each(function(i, o) {
        var latLong = new google.maps.LatLng($(o).data('lat'), $(o).data('long'));

        var map = new google.maps.Map(o, {
            zoom: 12,
            mapTypeId: google.maps.MapTypeId.ROAD,
            center: latLong
        });

        maps.push(map);

        var marker = new google.maps.Marker({
            position: latLong,
            map: map,
            title: $(o).data('time')
        });

        map.setCenter(latLong);
        map._center = latLong;

        $(o).data('map', map);
    });

})(jQuery)


答:
you need small modification in your code and you can get what you want.

```<code>   for(int i = 0; i < 5; i++) {

         for(int j = i; j < 5; j++) {

             System.out.print(" ");

         }

        for(int k = 0; k <= (i*2); k++) {
            if(i%2==0)
            System.out.print("*");
        }
           System.out.println();
    }
</code>```

check it out.

Title: replace every second line of my triangle with a blank line for loops

Body:
you need small modification in your code and you can get what you want.

   for(int i = 0; i < 5; i++) {

         for(int j = i; j < 5; j++) {

             System.out.print(" ");

         }

        for(int k = 0; k <= (i*2); k++) {
            if(i%2==0)
            System.out.print("*");
        }
           System.out.println();
    }

check it out.


问:
Is facebook sdk(iOS) supporting ipv6?
Our App was refused, and the problem was IPV6. this screenshot is feedback from Apple.enter image description here. If I login in IPV6，it was always showing the indicator, but if not in IPV6, it would work.

If someone knows that,pls help me.

Thank you in advance.

答:
I had faced the same issue. Mine was also rejected due to IPV6. Check below two things for your application:

Facebook SDK is 100% support IPv6. So just check below steps to resolve your issue.

1) Make sure you API link which you used in your application, doesn't have any IP address. If you calling API using IPAddress then your application will be rejected.

2) Do testing your application using IPV6 network through your system. Here is the link.

If your application is fulfilled both test case, then don't do anything, just write comment in iTuneConnect and told them that my application is running in IPV6 network. Can you please guide to find my issue? If possible then can I have a call with your representative?

So they ask your contact detail and give you call and your issue will be resolved. I have wasted around 20 days to solved this issue. But Apple representative told that this is them internal issue.

So my humble advice to contact Apple representative as soon as possible and your issue will resolve without doing anything.

Title: Is facebook sdk(iOS) supporting ipv6?


问:
Random number guessing game throws error: > or < cannot be used between str and int
I have the following code for a random number guessing game:

```<code>import random
number = random.randint(1,100)

name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")

guess1 = input()
if guess1 == number:
    print ("Good job, you got it!")
while guess1 != number:
    if guess1 > number:
        print ('your guess is too high')
    if guess1 < number:
        print ('your guess is too low')
</code>```

which throws the error that > or < cannot be used between str and int.

What should I do so it doesn't trigger that error?

答:
You can make use of a while loop here - https://www.tutorialspoint.com/python/python_while_loop.htm

The logic should be:

```<code>answer_is_correct = False

while not answer_is_correct :

    Keep receiving input until answer is correct
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following code for a random number guessing game:

import random
number = random.randint(1,100)

name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")

guess1 = input()
if guess1 == number:
    print ("Good job, you got it!")
while guess1 != number:
    if guess1 > number:
        print ('your guess is too high')
    if guess1 < number:
        print ('your guess is too low')

which throws the error that > or < cannot be used between str and int.

What should I do so it doesn't trigger that error?

Body:
You can make use of a while loop here - https://www.tutorialspoint.com/python/python_while_loop.htm

The logic should be:

answer_is_correct = False

while not answer_is_correct :

    Keep receiving input until answer is correct


问:
How to set a cookie if the paypal transaction was successful
I have added a Paypal button to my web app using the javascript at:

https://github.com/paypal/JavaScriptButtons

How can I set a cookie if the transaction was successful in Paypal? I have currently set it up so that the return url is passing a value: ?transaction=true but I am just afraid that users can easily inspect the site and change the value of this cookie.

答: use a session object. users cant change that.</p>


问:
Why doesn't Javascript Dynamic HTML5 Table Not Appear on Page
I am attempting to take quantities of products and multiplying them by the price before inserting these constantly updating values into an HTML table. I am using a forever loop to constantly take input for the sake of the example.</p>

```<code>    <!DOCTYPE html>
    <html>

    <head>
    <meta charset="utf-8">

<script>
<!--
var product1 = 0;
var product2 = 0;
var product3 = 0;
var product4 = 0;
var product5 = 0;
var productNum = 0;
var productNumInt = 0;
var quantitySold = 0;
var quantitySoldInt = 0;

document.write("<table>");
document.write("<tr><th>Product Number</th><th>Quantity Sold</th></tr>");
document.write("<tr><td>1</td><td>$" + product1 + "</td></tr>");
document.write("<tr><td>2</td><td>$" + product2 + "</td></tr>");
document.write("<tr><td>3</td><td>$" + product3 + "</td></tr>");
document.write("<tr><td>4</td><td>$" + product4 + "</td></tr>");
document.write("<tr><td>5</td><td>$" + product5 + "</td></tr>");
document.write("</table>");

while (true) {
  productNum = window.prompt("Please enter the product number");
  quantitySold = window.prompt("Please enter the quantity sold");
  productNumInt = parseInt(productNum);
  quantitySoldInt = parseInt(quantitySold);

  switch (productNumInt) {
    case 1:
      product1 += quantitySoldInt * 2.98;
      break;
    case 2:
      product2 += quantitySoldInt * 4.50;
      break;
    case 3:
      product3 += quantitySoldInt * 9.98;
      break;
    case 4:
      product4 += quantitySoldInt * 4.49;
      break;
    case 5:
      product5 += quantitySoldInt * 6.87;
      break;
  }
}
// -->
</script>
</head>

<body>
</body>

</html>
</code>```

答: You have to write script after your  tag ends i.e. after .

Body:
I am attempting to take quantities of products and multiplying them by the price before inserting these constantly updating values into an HTML table. I am using a forever loop to constantly take input for the sake of the example.

    <!DOCTYPE html>

    <meta charset="utf-8">

Body: You have to write script after your <body> tag ends i.e. after </body>.


问:
Google Maps GMSMaker iconView - iOS SDK
Error:

value of type GMSmarker has no member iconView

How can I  use iconView?

```<code>        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: 13.7990609, longitude: 100.5494513)
        marker.title = "Coffee Factory"
        marker.snippet = "Chatuchak"
        marker.iconView = imageView
        marker.map = mapView
</code>```

答:
Here it's what i'm done with this. Hope it will also work for you.

Swift 3.0

```<code>let marker = GMSMarker()

let markerImage = UIImage(named: "mapMarker")!.withRenderingMode(.alwaysTemplate)

let markerView = UIImageView(image: markerImage)

marker.position = CLLocationCoordinate2D(latitude: 33.5067, longitude: 51.2045)

marker.iconView = markerView
marker.map = mapView
</code>```

Title: Google Maps GMSMaker iconView - iOS SDK

Body:
Error:

value of type GMSmarker has no member iconView

How can I  use iconView?

        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: 13.7990609, longitude: 100.5494513)
        marker.title = "Coffee Factory"
        marker.snippet = "Chatuchak"
        marker.iconView = imageView
        marker.map = mapView

Body:
Here it's what i'm done with this. Hope it will also work for you.

Swift 3.0

let marker = GMSMarker()

let markerImage = UIImage(named: "mapMarker")!.withRenderingMode(.alwaysTemplate)

let markerView = UIImageView(image: markerImage)

marker.position = CLLocationCoordinate2D(latitude: 33.5067, longitude: 51.2045)

marker.iconView = markerView
marker.map = mapView


问:
Understanding Precision and Recall Results on a Binary Classifier
I know the difference between Precision and Recall metrics in Machine Learning. One optimizes on False Positives and other on False Negative. In Statistics it is called as optimizing on Type I or Type II error.

However, I am a but confused on under what circumstances one can get complete opposite Precision and Recall? Like Precision =1 and Recall=0?.

Let me iterate:

```<code>precision = true positives / (true positives + false positives)

recall = true positives / (true positives + false negatives)
</code>```

And here is the Confusion Matrix

```<code>  predicted
            (+)   (-)
            ---------
       (+) | TP | FN |
actual      ---------
       (-) | FP | TN |
            ---------
</code>```

Now, if Precision is =1 for a classifier for the positive (1) class, that means, there are no FP and all predicted labels are TP.

Then how can for the same positive class the Recall be 0? If there is already some TP being predicted, in fact as per Precision all predicted ones are TP only, then for Recall, we would have numerator non zero, then under what circumstances can one get Recall 0 then for the same classifier positive class?

To give some context, I ran a Logistic regression classifier for a binary classification problem. I had some 23K training data with 774 features. 770 features are binary or dummy variables.

And this is the distribution of my class labels:

```<code>1    20429
0    12559
</code>```

And here is the confusion matrix and accuracy values after a 5 fold grid search on some 25 combination of Hyper parameter values.

```<code>The mean train scores are [ 0.66883049  0.54314532  0.67008959  0.63187226  0.63100366  0.53165968
  0.54131812  0.55507725  0.5578254   0.57663273  0.57247462  0.57230056
  0.54402055  0.5762753   0.50925733  0.45781882  0.39366017  0.39037968
  0.3919818   0.38878762  0.39784982  0.39506755  0.48238147  0.38932944
  0.39801223]

The mean validation scores are [ 0.66445801  0.54107661  0.66878871  0.63184791  0.6305487   0.5291239
  0.53899788  0.55324585  0.55822615  0.57784418  0.57269066  0.57312373
  0.54536399  0.57593868  0.50790351  0.45727773  0.39318349  0.38906933
  0.39214413  0.38924256  0.39794725  0.39461262  0.4827855   0.38811658
  0.39812048]

The score on held out data is: 0.6687887055562773
 Hyper-Parameters for Best Score : {'alpha': 0.0001, 'l1_ratio': 0.45}

The accuracy of sgd on test data is: 0.37526523188845107

Classification Metrics for sgd :
             precision    recall  f1-score   support

          0       0.38      1.00      0.55      3712
          1       1.00      0.00      0.00      6185

avg / total       0.77      0.38      0.21      9897
</code>```

答: The output you've posted is rounded to 2 decimal places, so it's likely that you have precision = 1 and recall equal to say 0.001. This could happen for example if you only had one case (correctly) predicted as 1, and everything else predicted as 0. So you have a very high false positive rate, and your recall is 1/6185 which is close to 0.</p>

Body:
I know the difference between Precision and Recall metrics in Machine Learning. One optimizes on False Positives and other on False Negative. In Statistics it is called as optimizing on Type I or Type II error.

However, I am a but confused on under what circumstances one can get complete opposite Precision and Recall? Like Precision =1 and Recall=0?.

Let me iterate:

precision = true positives / (true positives + false positives)

recall = true positives / (true positives + false negatives)

And here is the Confusion Matrix

  predicted
            (+)   (-)
            ---------
       (+) | TP | FN |
actual      ---------
       (-) | FP | TN |
            ---------

Now, if Precision is =1 for a classifier for the positive (1) class, that means, there are no FP and all predicted labels are TP.

Then how can for the same positive class the Recall be 0? If there is already some TP being predicted, in fact as per Precision all predicted ones are TP only, then for Recall, we would have numerator non zero, then under what circumstances can one get Recall 0 then for the same classifier positive class?

To give some context, I ran a Logistic regression classifier for a binary classification problem. I had some 23K training data with 774 features. 770 features are binary or dummy variables.

And this is the distribution of my class labels:

1    20429
0    12559

And here is the confusion matrix and accuracy values after a 5 fold grid search on some 25 combination of Hyper parameter values.

The mean train scores are [ 0.66883049  0.54314532  0.67008959  0.63187226  0.63100366  0.53165968
  0.54131812  0.55507725  0.5578254   0.57663273  0.57247462  0.57230056
  0.54402055  0.5762753   0.50925733  0.45781882  0.39366017  0.39037968
  0.3919818   0.38878762  0.39784982  0.39506755  0.48238147  0.38932944
  0.39801223]

The mean validation scores are [ 0.66445801  0.54107661  0.66878871  0.63184791  0.6305487   0.5291239
  0.53899788  0.55324585  0.55822615  0.57784418  0.57269066  0.57312373
  0.54536399  0.57593868  0.50790351  0.45727773  0.39318349  0.38906933
  0.39214413  0.38924256  0.39794725  0.39461262  0.4827855   0.38811658
  0.39812048]

The score on held out data is: 0.6687887055562773
 Hyper-Parameters for Best Score : {'alpha': 0.0001, 'l1_ratio': 0.45}

The accuracy of sgd on test data is: 0.37526523188845107

Classification Metrics for sgd :
             precision    recall  f1-score   support

          0       0.38      1.00      0.55      3712
          1       1.00      0.00      0.00      6185

avg / total       0.77      0.38      0.21      9897


问:
creating objects in for loop javascript
I hope you can help me with this hopefully stupid problem.
I try to do the following:

creating array with data

looping through this array within a for loop (based on array.length)

create new object based on data in array

So far I got the following:

create array

loop through array

create one object based on my constructor

The problem is, the array has a length of 4 and should therefore create 4 objects but it creates only one. If I remove the creation of the object and just log "i' it works, but in the original intention it ends after the first
The loop looks as follows:

```<code>for(i=0;i<array.length;i++)
        {
        newObj[i]=new ObjectName(array[i].param1,array[i].param2,array[i].param3)
        }
</code>```

I have no idea why it ends after the first run and I also don't get an error displayed when looking into firebug.

Cheers

答:
```<code>for (i = 0; i < (stringNums.length); i++) {
    Dictionary[stringNums[i]] =  stringNums[i].length;
}
</code>```

Title: creating objects in for loop javascript

Body:
I hope you can help me with this hopefully stupid problem.
I try to do the following:

creating array with data

looping through this array within a for loop (based on array.length)

create new object based on data in array

So far I got the following:

create array

loop through array

create one object based on my constructor

The problem is, the array has a length of 4 and should therefore create 4 objects but it creates only one. If I remove the creation of the object and just log "i' it works, but in the original intention it ends after the first
The loop looks as follows:

for(i=0;i<array.length;i++)
        {
        newObj[i]=new ObjectName(array[i].param1,array[i].param2,array[i].param3)
        }

I have no idea why it ends after the first run and I also don't get an error displayed when looking into firebug.

Cheers


问:
Why does this callback function not add bind.(this)?
As I know, we need to use .bind each time when you pass your custom function to an event handler like onChange or onSubmit

In the following Example ,we pass an event handler (talk function) as a prop.
When a user click a button,talk function will be called.

```<code>var React = require('react');
var ReactDOM = require('react-dom');
var Button = require('./Button');

var Talker = React.createClass({
  talk: function () {
    for (var speech = '', i = 0; i < 10000; i++) {
      speech += 'blah ';
    }
    alert(speech);
  },

  render: function () {
    return <Button talk={this.talk}/>;
  }
});

ReactDOM.render(
  <Talker />,
  document.getElementById('app')
);
</code>```

Button.js

```<code>var React = require('react');

var Button = React.createClass({
  render: function () {
    return (
      <button onClick={this.props.talk}>
        Click me!
      </button>
    );
  }
});

module.exports = Button;
</code>```

This example uses Button talk={this.talk} instead of Button {this.talk.bind.(this)}

,but why?

答:
This behavior is expected when using createClass where React binds every method (custom and that of React component API) to their component resulting 'this' to be available. same cannot be said about when using ES6 .... extends React.Component where react only binds 'this' to react component API methods.

Also, you don't exactly need to do this.talk.bind(this) each time were you using ES6 in your render method, instead

you could

```<code>constructor () {
    super()
    this.talk = this.talk.bind(this)
}
</code>```

and use this.talk() anywhere in it.

for in-depth explanation, https://www.fullstackreact.com/articles/react-create-class-vs-es6-class-components/

Body:
As I know, we need to use .bind each time when you pass your custom function to an event handler like onChange or onSubmit

In the following Example ,we pass an event handler (talk function) as a prop.
When a user click a button,talk function will be called.

var React = require('react');
var ReactDOM = require('react-dom');
var Button = require('./Button');

var Talker = React.createClass({
  talk: function () {
    for (var speech = '', i = 0; i < 10000; i++) {
      speech += 'blah ';
    }
    alert(speech);
  },

  render: function () {
    return <Button talk={this.talk}/>;
  }
});

ReactDOM.render(
  <Talker />,
  document.getElementById('app')
);

Button.js

var React = require('react');

var Button = React.createClass({
  render: function () {
    return (
      <button onClick={this.props.talk}>
        Click me!
      </button>
    );
  }
});

module.exports = Button;

This example uses Button talk={this.talk} instead of Button {this.talk.bind.(this)}

,but why?

Body:
This behavior is expected when using createClass where React binds every method (custom and that of React component API) to their component resulting 'this' to be available. same cannot be said about when using ES6 .... extends React.Component where react only binds 'this' to react component API methods.

Also, you don't exactly need to do this.talk.bind(this) each time were you using ES6 in your render method, instead

you could

constructor () {
    super()
    this.talk = this.talk.bind(this)
}

and use this.talk() anywhere in it.

for in-depth explanation, https://www.fullstackreact.com/articles/react-create-class-vs-es6-class-components/


答:
Apple provides the standard error message about IPv6 when the app is not able to respond within the given threshold time for any HTTP network request. In your case most probable cause of app getting rejected is that at some point in your app during the review process the app has not received the response from server due to which the spinner has continued spinning.

Also make sure you don't use any hard coded IP addresses in your network requests and must use fully qualified domain names for accessing RESTFul APIs.

Title: Is facebook sdk(iOS) supporting ipv6?

Body:
Our App was refused, and the problem was IPV6. this screenshot is feedback from Apple.enter image description here. If I login in IPV6，it was always showing the indicator, but if not in IPV6, it would work.

If someone knows that,pls help me.

Thank you in advance.


问:
SBT Error: "Failed to construct terminal; falling back to unsupported..."
I have run into an ERROR with SBT today. It can best be shown with the sbt sbt-version command:

Run on 5/29/17:

```<code>eric@linux-x2vq:~$ sbt sbt-version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option
MaxPermSize=256M; support was removed in 8.0
[info] Set current project to eric (in build file:/home/eric/)
[info] 0.13.13
</code>```

Run on 6/1/17:

```<code>eric@linux-x2vq:~$ sbt sbt-version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option
MaxPermSize=256M; support was removed in 8.0
[ERROR] Failed to construct terminal; falling back to unsupported
java.lang.NumberFormatException: For input string: "0x100"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at jline.internal.InfoCmp.parseInfoCmp(InfoCmp.java:59)
at jline.UnixTerminal.parseInfoCmp(UnixTerminal.java:233)
at jline.UnixTerminal.<init>(UnixTerminal.java:64)
at jline.UnixTerminal.<init>(UnixTerminal.java:49)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at jline.TerminalFactory.getFlavor(TerminalFactory.java:209)
at jline.TerminalFactory.create(TerminalFactory.java:100)
at jline.TerminalFactory.get(TerminalFactory.java:184)
at jline.TerminalFactory.get(TerminalFactory.java:190)
at sbt.ConsoleLogger$.ansiSupported(ConsoleLogger.scala:123)
at sbt.ConsoleLogger$.<init>(ConsoleLogger.scala:117)
at sbt.ConsoleLogger$.<clinit>(ConsoleLogger.scala)
at sbt.GlobalLogging$.initial(GlobalLogging.scala:43)
at sbt.StandardMain$.initialGlobalLogging(Main.scala:64)
at sbt.StandardMain$.initialState(Main.scala:73)
at sbt.xMain.run(Main.scala:29)
at xsbt.boot.Launch$$anonfun$run$1.apply(Launch.scala:109)
at xsbt.boot.Launch$.withContextLoader(Launch.scala:128)
at xsbt.boot.Launch$.run(Launch.scala:109)
at xsbt.boot.Launch$$anonfun$apply$1.apply(Launch.scala:35)
at xsbt.boot.Launch$.launch(Launch.scala:117)
at xsbt.boot.Launch$.apply(Launch.scala:18)
at xsbt.boot.Boot$.runImpl(Boot.scala:41)
at xsbt.boot.Boot$.main(Boot.scala:17)
at xsbt.boot.Boot.main(Boot.scala)

[info] Set current project to eric (in build file:/home/eric/)
[info] 0.13.13
</code>```

No changes (that I know of) to either my SBT or Java setup.

Any ideas on what might be causing this or how to fix the error?

Thank you!

答:
I had the same issue, especially when the TERM environment variable is set to xterm-256color. Setting it to a different value fixed the issue for me, e.g.

```<code>export TERM=xterm-color
</code>```

Body:
I have run into an ERROR with SBT today. It can best be shown with the sbt sbt-version command:

Run on 5/29/17:

eric@linux-x2vq:~$ sbt sbt-version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option
MaxPermSize=256M; support was removed in 8.0
[info] Set current project to eric (in build file:/home/eric/)
[info] 0.13.13

Run on 6/1/17:

eric@linux-x2vq:~$ sbt sbt-version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option
MaxPermSize=256M; support was removed in 8.0
[ERROR] Failed to construct terminal; falling back to unsupported
java.lang.NumberFormatException: For input string: "0x100"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at jline.internal.InfoCmp.parseInfoCmp(InfoCmp.java:59)
at jline.UnixTerminal.parseInfoCmp(UnixTerminal.java:233)
at jline.UnixTerminal.<init>(UnixTerminal.java:64)
at jline.UnixTerminal.<init>(UnixTerminal.java:49)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at jline.TerminalFactory.getFlavor(TerminalFactory.java:209)
at jline.TerminalFactory.create(TerminalFactory.java:100)
at jline.TerminalFactory.get(TerminalFactory.java:184)
at jline.TerminalFactory.get(TerminalFactory.java:190)
at sbt.ConsoleLogger$.ansiSupported(ConsoleLogger.scala:123)
at sbt.ConsoleLogger$.<init>(ConsoleLogger.scala:117)
at sbt.ConsoleLogger$.<clinit>(ConsoleLogger.scala)
at sbt.GlobalLogging$.initial(GlobalLogging.scala:43)
at sbt.StandardMain$.initialGlobalLogging(Main.scala:64)
at sbt.StandardMain$.initialState(Main.scala:73)
at sbt.xMain.run(Main.scala:29)
at xsbt.boot.Launch$$anonfun$run$1.apply(Launch.scala:109)
at xsbt.boot.Launch$.withContextLoader(Launch.scala:128)
at xsbt.boot.Launch$.run(Launch.scala:109)
at xsbt.boot.Launch$$anonfun$apply$1.apply(Launch.scala:35)
at xsbt.boot.Launch$.launch(Launch.scala:117)
at xsbt.boot.Launch$.apply(Launch.scala:18)
at xsbt.boot.Boot$.runImpl(Boot.scala:41)
at xsbt.boot.Boot$.main(Boot.scala:17)
at xsbt.boot.Boot.main(Boot.scala)

[info] Set current project to eric (in build file:/home/eric/)
[info] 0.13.13

No changes (that I know of) to either my SBT or Java setup.

Any ideas on what might be causing this or how to fix the error?

Thank you!

Body:
I had the same issue, especially when the TERM environment variable is set to xterm-256color. Setting it to a different value fixed the issue for me, e.g.

export TERM=xterm-color


问:
Live Wallpaper Preview Thumbnail Size
What's the width and height of the live wallpaper preview thumbnail in pixels? It's definitely larger than 72x72, that I know. </p>

答: I did a test by taking a screenshot of the wallpaper list in the emulator. It shows the medium DPI thumb version and had exactly 75x75 pixels. Since 75x2=150 you could saved yourself some pixels ;)</p>

Title: Live Wallpaper Preview Thumbnail Size


问:
ClassFormatError occured : Unknown constant tag 32 in class file Template_1007$_run_closure1_closure2
I have a java  controller class , name DataManageMent.java . I have found this error :

ClassFormatError occured : Unknown constant tag 32 in class file
  Template_1007$_run_closure1_closure2

Here is my code :

```<code>public static void viewDetails(Long id){

        String users = session.get("username");

        User user = User.findByName(users);

        List<Water> waterList=new ArrayList<Water>();
        List<Sanitation> sanitationList =new ArrayList<Sanitation>();
        List<SportsRecreation> sportsRecreationList =new ArrayList<SportsRecreation>();
        List<SchoolEnvironment> schoolEnvironmentList =new ArrayList<SchoolEnvironment>();

        List<GeoDivision> geoDivisionList = GeoDivision.findAll();
        List<GeoDistrict> geoDistrictList = GeoDistrict.findAll();
        List<GeoUpazilla> geoUpazillaList = GeoUpazilla.findAll();
        List<Form> formList = Form.findAll();
        List<SchoolInformation> schoolList = SchoolInformation.findAll();

        Long roleId = user.role.id;

        if(roleId==3){

            Long schoolId = user.school.id;
            Logger.info("school: " + schoolId + "roleId: " + roleId);

            waterList=Water.find("school_id=?",schoolId).fetch();
            Logger.info("size: " + waterList.size());
            sanitationList = Sanitation.find("school_id=?",schoolId).fetch();
            sportsRecreationList = SportsRecreation.find("school_id=?",schoolId).fetch();
            schoolEnvironmentList = SchoolEnvironment.find("school_id=?",schoolId).fetch();

            render(geoDivisionList, geoDistrictList, geoUpazillaList,schoolList, formList,waterList,sanitationList,sportsRecreationList,schoolEnvironmentList);
        }

        else if(roleId!=3){

            waterList = Water.findAll();
            Logger.info("size: " + waterList.size());
            sanitationList = Sanitation.findAll();
            sportsRecreationList = SportsRecreation.findAll();
            schoolEnvironmentList = SchoolEnvironment.findAll();

            render(geoDivisionList, geoDistrictList, geoUpazillaList,schoolList, formList,waterList,sanitationList,sportsRecreationList,schoolEnvironmentList);
        }
    }
</code>```

Where is the problem?

答: I have solved the problem. The size of view page was bigger . I have to make an external js and transfer the javascript code to it.And then,finally it works.</p>

Body:
I have a java  controller class , name DataManageMent.java . I have found this error :

ClassFormatError occured : Unknown constant tag 32 in class file
  Template_1007$_run_closure1_closure2

Here is my code :

public static void viewDetails(Long id){

        String users = session.get("username");

        User user = User.findByName(users);

        List<Water> waterList=new ArrayList<Water>();
        List<Sanitation> sanitationList =new ArrayList<Sanitation>();
        List<SportsRecreation> sportsRecreationList =new ArrayList<SportsRecreation>();
        List<SchoolEnvironment> schoolEnvironmentList =new ArrayList<SchoolEnvironment>();

        List<GeoDivision> geoDivisionList = GeoDivision.findAll();
        List<GeoDistrict> geoDistrictList = GeoDistrict.findAll();
        List<GeoUpazilla> geoUpazillaList = GeoUpazilla.findAll();
        List<Form> formList = Form.findAll();
        List<SchoolInformation> schoolList = SchoolInformation.findAll();

        Long roleId = user.role.id;

        if(roleId==3){

            Long schoolId = user.school.id;
            Logger.info("school: " + schoolId + "roleId: " + roleId);

            waterList=Water.find("school_id=?",schoolId).fetch();
            Logger.info("size: " + waterList.size());
            sanitationList = Sanitation.find("school_id=?",schoolId).fetch();
            sportsRecreationList = SportsRecreation.find("school_id=?",schoolId).fetch();
            schoolEnvironmentList = SchoolEnvironment.find("school_id=?",schoolId).fetch();

            render(geoDivisionList, geoDistrictList, geoUpazillaList,schoolList, formList,waterList,sanitationList,sportsRecreationList,schoolEnvironmentList);
        }

        else if(roleId!=3){

            waterList = Water.findAll();
            Logger.info("size: " + waterList.size());
            sanitationList = Sanitation.findAll();
            sportsRecreationList = SportsRecreation.findAll();
            schoolEnvironmentList = SchoolEnvironment.findAll();

            render(geoDivisionList, geoDistrictList, geoUpazillaList,schoolList, formList,waterList,sanitationList,sportsRecreationList,schoolEnvironmentList);
        }
    }

Where is the problem?


问:
JSF Primefaces TabView problems
I asked this in the PF Forum but no one seems to want to answer so I though I'd try my luck here.

I have a ui:repeat that is not being updated correctly after an Ajax call when it is within a TabView.

Simple scenario is I have a ui:repeat pointing at an ArrayList (ArrayList contains simple pojos with a String).  Within this I have an h:inputText whose value is the pojo's String getter/setter.  The ui:repeat is contained within a h:panelGroup.  I use a p:commandButton to run an action to update the ArrayList (just add a couple of objects to it a Math.random value for the String) and then update the h:panelGroup.  The updated values in the ArrayList are not reflecting in the ui:repeat input fields.  This only appears to be affecting input fields as outputText fields do update correctly.  Also if I do the same for a p:dataTable the input field are updated correctly.  If I remove the Tabview and Tab tags it works fine.

As it works when removing the Tabs I can only assume this is a bug and not designed to work like this.  If someone could please confirm if this is so or if there is a viable work around.  I need to use a ui:repeat as my fields are not in a tabular format.  This has only occurred since migrating from PF 2.2. I'm currently on PF 3.1, Weblogic 10.3.4 and Mojarra 2.0.4

```<code><p:tabView>
    <p:tab title="Test">

        <h:form prependId="false">

            <p:commandButton id="testStringCheck"
                             value="Test String Check"
                             process="@form"
                             update="testPanel"
                             action="#{testBean.generateVOwithRandomStrings}">
            </p:commandButton>

            <h:panelGroup id="testPanel" layout="block">
                <ui:repeat value="#{testBean.voList}" var="entry">
                    <h:outputText value="#{entry.randomString}"/>
                    <p:inputText style="display:block;"
                                 value="#{entry.randomString}"
                                 size="15">
                    </p:inputText>
                </ui:repeat>
            </h:panelGroup>

        </h:form>

    </p:tab>
</p:tabView>
</code>```

答:
temp solution: insert outside h:panelGroup:

```<code><p:outputPanel defered="true" delay="1" ..>
</code>```

and update outputPanel instead of panelGroup

Or use a datalist component instead of ui:repeat.

One more, i'm not sure but you can try, so update class instead id:

```<code><h:panelGroup id="testPanel" layout="block" styleClass="testPanelCl" ../>
</code>```

and update : @(.testPanelCl), don't forget id of panelGroup, without id JSF can not update by class

Title: JSF Primefaces TabView problems

Body:
I asked this in the PF Forum but no one seems to want to answer so I though I'd try my luck here.

I have a ui:repeat that is not being updated correctly after an Ajax call when it is within a TabView.

Simple scenario is I have a ui:repeat pointing at an ArrayList (ArrayList contains simple pojos with a String).  Within this I have an h:inputText whose value is the pojo's String getter/setter.  The ui:repeat is contained within a h:panelGroup.  I use a p:commandButton to run an action to update the ArrayList (just add a couple of objects to it a Math.random value for the String) and then update the h:panelGroup.  The updated values in the ArrayList are not reflecting in the ui:repeat input fields.  This only appears to be affecting input fields as outputText fields do update correctly.  Also if I do the same for a p:dataTable the input field are updated correctly.  If I remove the Tabview and Tab tags it works fine.

As it works when removing the Tabs I can only assume this is a bug and not designed to work like this.  If someone could please confirm if this is so or if there is a viable work around.  I need to use a ui:repeat as my fields are not in a tabular format.  This has only occurred since migrating from PF 2.2. I'm currently on PF 3.1, Weblogic 10.3.4 and Mojarra 2.0.4

        <h:form prependId="false">

            <h:panelGroup id="testPanel" layout="block">
                <ui:repeat value="#{testBean.voList}" var="entry">
                    <h:outputText value="#{entry.randomString}"/>

                </ui:repeat>
            </h:panelGroup>

        </h:form>

Body:
temp solution: insert outside h:panelGroup:

<p:outputPanel defered="true" delay="1" ..>

and update outputPanel instead of panelGroup

Or use a datalist component instead of ui:repeat.

One more, i'm not sure but you can try, so update class instead id:

<h:panelGroup id="testPanel" layout="block" styleClass="testPanelCl" ../>

and update : @(.testPanelCl), don't forget id of panelGroup, without id JSF can not update by class


问:
how to add button click event in android studio
So I have done some research, and after defining you button as an object by the code

```<code>private Button buttonname;
buttonname = (Button) findViewById(R.id.buttonnameinandroid) ;
</code>```

here is my problem

```<code>buttonname.setOnClickListener(this); //as I understand it, the "**this**" denotes the current `view(focus)` in the android program
</code>```

then your OnClick() event...

Problem:

When I type in the "this", it says:

```<code>setOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)
</code>```

I have no idea why?

here is the code from the .java file

```<code>import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    private Button btnClick;
    private EditText Name, Date;
    private TextView msg, NameOut, DateOut;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnClick = (Button) findViewById(R.id.button) ;
        btnClick.setOnClickListener(this);
        Name = (EditText) findViewById(R.id.textenter) ;
        Date = (EditText) findViewById(R.id.editText) ;
        msg = (TextView) findViewById(R.id.txtviewOut) ;
        NameOut = (TextView) findViewById(R.id.txtoutName) ;
        DateOut = (TextView) findViewById(R.id.txtOutDate) ;
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    public void onClick(View v)
    {
        if (v == btnClick)
        {
            if (Name.equals("") == false && Date.equals("") == false)
            {
                NameOut = Name;
                DateOut = Date;
                msg.setVisibility(View.VISIBLE);
            }
            else
            {
                msg.setText("Please complete both fields");
                msg.setVisibility(View.VISIBLE);
            }
        }
        return;

    }
</code>```

答:
Your Activity must implement View.OnClickListener, like this:

```<code>public class MainActivity extends
Activity implements View.OnClickListener{
// YOUR CODE
}
</code>```

And inside MainActivity override the method onClick(), like this:

```<code>@override
public void onClick (View view){
//here YOUR Action response to Click Button
}
</code>```

Body:
So I have done some research, and after defining you button as an object by the code

private Button buttonname;
buttonname = (Button) findViewById(R.id.buttonnameinandroid) ;

here is my problem

buttonname.setOnClickListener(this); //as I understand it, the "**this**" denotes the current `view(focus)` in the android program

then your OnClick() event...

Problem:

When I type in the "this", it says:

setOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)

I have no idea why?

here is the code from the .java file

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    private Button btnClick;
    private EditText Name, Date;
    private TextView msg, NameOut, DateOut;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnClick = (Button) findViewById(R.id.button) ;
        btnClick.setOnClickListener(this);
        Name = (EditText) findViewById(R.id.textenter) ;
        Date = (EditText) findViewById(R.id.editText) ;
        msg = (TextView) findViewById(R.id.txtviewOut) ;
        NameOut = (TextView) findViewById(R.id.txtoutName) ;
        DateOut = (TextView) findViewById(R.id.txtOutDate) ;
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    public void onClick(View v)
    {
        if (v == btnClick)
        {
            if (Name.equals("") == false && Date.equals("") == false)
            {
                NameOut = Name;
                DateOut = Date;
                msg.setVisibility(View.VISIBLE);
            }
            else
            {
                msg.setText("Please complete both fields");
                msg.setVisibility(View.VISIBLE);
            }
        }
        return;

    }

Body:
Your Activity must implement View.OnClickListener, like this:

public class MainActivity extends
Activity implements View.OnClickListener{
// YOUR CODE
}

And inside MainActivity override the method onClick(), like this:

@override
public void onClick (View view){
//here YOUR Action response to Click Button
}


问:
VBA Dynamic Named Range as Listbox RowSource Error
I have a dynamic named range that returns a list (array) of some values that are not assigned but once all values are assigned the list returns #N/A

Formula (Array):

=INDEX(EquipTable[Equip], MATCH(0,EquipTable[Flag],0), 1):INDEX(EquipTable[Equip],
  MATCH(0,EquipTable[Flag],0)+COUNTIF(EquipTable[Flag],0)-1, 1)

Problem is that I am using this Ranged named as a Listbox.RowSource and I can't find a way to check for the value of the named range or even to check whether its returns errors or not.

I used:

Application.WorksheetFunction.IsError(ActiveWorkbook.Names("UnassignedEquipment"))

But its always returning False

I also used:

IsEmpty(ActiveWorkbook.Names("UnassignedEquipment"))

and

IsError(ActiveWorkbook.Names("UnassignedEquipment"))

答:
One way is to use IFERROR in the formula used for the named range so that if the named range doesn't return anything, it refers to a specific range/cell.

```<code>=IFERROR(INDEX(EquipTable[Equip], MATCH(0,EquipTable[Flag],0), 1):INDEX(EquipTable[Equip], MATCH(0,EquipTable[Flag],0)+COUNTIF(EquipTable[Flag],0)-1, 1),A1)
</code>```

Here A1 is the cell which the named range would refer if nothing a valid range is not returned by the formula. Change A1 in the formula as per your requirement.

Body:
One way is to use IFERROR in the formula used for the named range so that if the named range doesn't return anything, it refers to a specific range/cell.

=IFERROR(INDEX(EquipTable[Equip], MATCH(0,EquipTable[Flag],0), 1):INDEX(EquipTable[Equip], MATCH(0,EquipTable[Flag],0)+COUNTIF(EquipTable[Flag],0)-1, 1),A1)

Here A1 is the cell which the named range would refer if nothing a valid range is not returned by the formula. Change A1 in the formula as per your requirement.


问:
Convert type X to Y in Map<K, Map<V, X>> using Java Stream API
I want to convert inner map from map of maps.

Old map: Map<String, Map<LocalDate, Integer>> Integer means seconds

New map: Map<String, Map<LocalDate, Duration>>

I have tried created new inner map, but got an error

Error: java: no suitable method found for putAll(java.util.stream.Stream<java.lang.Object>)
      method java.util.Map.putAll(java.util.Map<? extends java.time.LocalDate,? extends java.time.Duration>) is not applicable

```<code>oldMap.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey,
                e -> new HashMap<LocalDate, Duration>() {{
                    putAll(
                        e.getValue().entrySet().stream()
                            .map(x -> new HashMap.SimpleEntry<LocalDate, Duration>
                                (x.getKey(), Duration.ofSeconds(x.getValue())))
                    );
                }}
            ));
</code>```

答:
Here is solution by StreamEx:</p>

```<code>EntryStream.of(oldMap)
           .mapValues(v -> EntryStream.of(v).mapValues(Duration::ofSeconds).toMap())
           .toMap();
</code>```

Body:
I want to convert inner map from map of maps.

Old map: Map<String, Map<LocalDate, Integer>> Integer means seconds

New map: Map<String, Map<LocalDate, Duration>>

I have tried created new inner map, but got an error

Error: java: no suitable method found for putAll(java.util.stream.Stream<java.lang.Object>)
      method java.util.Map.putAll(java.util.Map<? extends java.time.LocalDate,? extends java.time.Duration>) is not applicable

oldMap.entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey,
                e -> new HashMap<LocalDate, Duration>() {{
                    putAll(
                        e.getValue().entrySet().stream()
                            .map(x -> new HashMap.SimpleEntry<LocalDate, Duration>
                                (x.getKey(), Duration.ofSeconds(x.getValue())))
                    );
                }}
            ));

Body:
Here is solution by StreamEx:

EntryStream.of(oldMap)
           .mapValues(v -> EntryStream.of(v).mapValues(Duration::ofSeconds).toMap())
           .toMap();


问:
react-native run-android fails, could not install app
I m having a problem when I try to run my react-native application in my Android Device. The device is connected even when I make sure that it is.

adb devices

List of devices attached

HMNBBCE6A2826109        device

Device: Huawei Y2
Android Version: 5.1
Debug mode: enbaled
the server is running.
When i run

react-native run-android

I get this error

Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

答:
Try the command.

```<code>adb devices
</code>```

See if there is any devices listed.

If so check the local.properties file inside android folder and check the sdk defined is correct.

if there is no local.properties files. add a new file named local.properties with the following content

```<code>## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Thu May 25 18:29:08 IST 2017
sdk.dir=path to sdk
</code>```

This command will also help

```<code> adb reverse tcp:8081 tcp:8081
</code>```

Body:
Try the command.

adb devices

See if there is any devices listed.

If so check the local.properties file inside android folder and check the sdk defined is correct.

if there is no local.properties files. add a new file named local.properties with the following content

## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Thu May 25 18:29:08 IST 2017
sdk.dir=path to sdk

This command will also help

 adb reverse tcp:8081 tcp:8081


问:
How to print out pdf file when button clicked?
I want to print out pdf file without download it, like I have button print when I click it, my pdf file opened into new tab, where I can see my pdf file and two button like print and close. How to do it? Are there any suggestions?</p>

答:
Installing Acrobat Reader should let you view it in your web browser for printing.
https://get.adobe.com/reader/</p>


问:
How to call another HTML page from current HTML with some elements hidden?
I'm currently developing a website. I have two page in this scenario and 1st one is home page and second one is signup page. In first page I have two buttons called Login and Signup. In signup HTML page I've made login form and signup form using divisions. Simply saying one division contain login form and other contain signup form and depending on what I need, I simply hide what I don't want using onclick method.

What I want

Now I need, when I click on login button in home page, it should go to the signup page but signup division should be hidden and login division should be visible. And if I click on signup button in home page, it should go to the signup page but login form including division should be hidden and login division should be visible.

```<code><div class="container">
    <div id="loginBox" style="margin-top:50px;padding-top:80px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
        //Code//
    </div>
    <div id="signupBox" style="margin-top:50px;padding-top:80px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
        //Code//
    </div>
</div>
</code>```

My Approach

I thought to use javascript to access requesting page (signup page) and hide the suitable division and open the page. But I don't know how to do that. I couldn't find anything regarding on internet too. If you have another method which is easier than this please feel free to say. Thanks.

答:
A CSS/HTML only approach

Step 1:

On your home page change buttons to links, but feel free to style them as buttons. Set a target on the links

E.g:

```<code><a href="signup.html#signupBox">Sign Up</a> <a href="signup.html#loginBox">Log In</a>
</code>```

Step 2:

Then in your signup.html page have something like the following:

```<code><div class="container signup">
    <div id="loginBox" style="margin-top:50px;padding-top:80px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
        //Code//
    </div>
    <div id="signupBox" style="margin-top:50px;padding-top:80px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
        //Code//
    </div>
</div>
</code>```

and add the following CSS

```<code>.signup > div {display:none;}
.signup > div:target {display:block;}
</code>```

When the signup page is accessed with a target eg http://yoursite/signup.html#loginBox, the appropriate section will be displayed.

This has the added benefit of signup and login being able to be bookmarked separately.

A simple one page demo:

.nav a {border: 1px solid black; padding: 15px; text-decoration: none; margin-right:15px; margin-top: 15px; font-weight:bold;}

.signup h2 {padding: 10px; background-color:blue;}
.signup a:link, .signup a:visited {color:white; text-decoration: none;}

.signup > div {display:none;}
.signup > div:target {display:block;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">

    Sign Up Log In
</div>

    <div class="container signup">
        <h2>Log In</h2>
        <div id="loginBox" style="margin-top:50px;padding-top:80px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
            Your Log In Form Here
        </div>
        <h2>Sign Up</h2>
        <div id="signupBox" style="margin-top:50px;padding-top:80px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
            Your Signup Form Here
        </div>
    </div></code>```

Note: them Demo just shows the basic mechanics in action.

If you want to get fancy you can use javascript to check if the # exists and set a default. See How do I get the value after hash (#) from a URL using jquery to get you started.

Body:
I'm currently developing a website. I have two page in this scenario and 1st one is home page and second one is signup page. In first page I have two buttons called Login and Signup. In signup HTML page I've made login form and signup form using divisions. Simply saying one division contain login form and other contain signup form and depending on what I need, I simply hide what I don't want using onclick method.

What I want

Now I need, when I click on login button in home page, it should go to the signup page but signup division should be hidden and login division should be visible. And if I click on signup button in home page, it should go to the signup page but login form including division should be hidden and login division should be visible.

        //Code//

        //Code//

My Approach

I thought to use javascript to access requesting page (signup page) and hide the suitable division and open the page. But I don't know how to do that. I couldn't find anything regarding on internet too. If you have another method which is easier than this please feel free to say. Thanks.

Body:
A CSS/HTML only approach

Step 1:

On your home page change buttons to links, but feel free to style them as buttons. Set a target on the links

E.g:

<a href="signup.html#signupBox">Sign Up</a> <a href="signup.html#loginBox">Log In</a>

Step 2:

Then in your signup.html page have something like the following:

<div class="container signup">
    <div id="loginBox" style="margin-top:50px;padding-top:80px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
        //Code//
    </div>
    <div id="signupBox" style="margin-top:50px;padding-top:80px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
        //Code//
    </div>
</div>

and add the following CSS

.signup > div {display:none;}
.signup > div:target {display:block;}

When the signup page is accessed with a target eg http://yoursite/signup.html#loginBox, the appropriate section will be displayed.

This has the added benefit of signup and login being able to be bookmarked separately.

A simple one page demo:

.nav a {border: 1px solid black; padding: 15px; text-decoration: none; margin-right:15px; margin-top: 15px; font-weight:bold;}

.signup h2 {padding: 10px; background-color:blue;}
.signup a:link, .signup a:visited {color:white; text-decoration: none;}

.signup > div {display:none;}
.signup > div:target {display:block;}

<div class="nav">

    <a href="#signupBox">Sign Up</a> <a href="#loginBox">Log In</a>
</div>

    <div class="container signup">
        <h2><a href="#loginBox">Log In</a></h2>
        <div id="loginBox" style="margin-top:50px;padding-top:80px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
            Your Log In Form Here
        </div>
        <h2><a href="#signupBox">Sign Up</a></h2>
        <div id="signupBox" style="margin-top:50px;padding-top:80px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
            Your Signup Form Here
        </div>
    </div>

Note: them Demo just shows the basic mechanics in action.

If you want to get fancy you can use javascript to check if the # exists and set a default. See How do I get the value after hash (#) from a URL using jquery to get you started.


问:
Get property from derived class in base class
base.php:

```<code><?php namespace MyQuestion\Base;

abstract class BaseSetting
{
    public function GetValue($setting)
    {
        return $this->$setting;
    }
}
</code>```

derived.php

```<code><?php namespace MyQuestion\Configs;

use MyQuestion\Base;

class Settings extends BaseSetting
{
    private $a = 'value 1';
    private $b = 'value 2';
    private $c = "value 3";
}
</code>```

index.php

```<code>$abc = new Settings();
$mySettings = $abc->GetValue('a');
</code>```

I try to debug code. Something is broken in $this->setting. How can I do that? I have some settings file and I need to get values from them using a function. I don't want to define the same function in every setting file.

答:
You can set the scope of private $a to protected $a

or

you can

```<code>class Settings extends BaseSetting
{
 public function GetValue($setting)
    {
        return parent::getValue($setting)
    }
}
</code>```

Without it when you will call mySettings = $abc->GetValue('a'); it will call BaseSetting::GetValue() in context of BaseSetting. As $a is private it wont have access in BaseSetting. Either you need to change access modifier to lower like public or protected or you need call override getValue() and call return parent::getValue($setting) from there.

Body:
base.php:

<?php namespace MyQuestion\Base;

abstract class BaseSetting
{
    public function GetValue($setting)
    {
        return $this->$setting;
    }
}

derived.php

<?php namespace MyQuestion\Configs;

use MyQuestion\Base;

class Settings extends BaseSetting
{
    private $a = 'value 1';
    private $b = 'value 2';
    private $c = "value 3";
}

index.php

$abc = new Settings();
$mySettings = $abc->GetValue('a');

I try to debug code. Something is broken in $this->setting. How can I do that? I have some settings file and I need to get values from them using a function. I don't want to define the same function in every setting file.

Body:
You can set the scope of private $a to protected $a

or

you can

class Settings extends BaseSetting
{
 public function GetValue($setting)
    {
        return parent::getValue($setting)
    }
}

Without it when you will call mySettings = $abc->GetValue('a'); it will call BaseSetting::GetValue() in context of BaseSetting. As $a is private it wont have access in BaseSetting. Either you need to change access modifier to lower like public or protected or you need call override getValue() and call return parent::getValue($setting) from there.


问:
How to disable high lighting with CSS?
I am trying to disable highlighting with CSS. It is pretty easy for a user to accidentally highlight elements on my site, and it ruins the appearance. What CSS property can I use to stop this?

highlight example:

答:
Try this out.</p>

```<code>.noselection {
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none; /* Safari */
  -khtml-user-select: none; /* Konqueror HTML */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* Internet Explorer/Edge */
  user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}
</code>```

Title: How to disable high lighting with CSS?

Body:
Try this out.

.noselection {
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none; /* Safari */
  -khtml-user-select: none; /* Konqueror HTML */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* Internet Explorer/Edge */
  user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome and Opera */
}


问:
Missing number(s) Interview Question Redux
The common interview problem of determining the missing value in a range from 1 to N has been done a thousand times over. Variations include 2 missing values up to K missing values.

Example problem: Range [1,10] (1 2 4 5 7 8 9 10) = {3,6}

Here is an example of the various solutions:

Easy interview question got harder: given numbers 1..100, find the missing number(s)

My question is that seeing as the simple case of one missing value is of O(n) complexity and that the complexity of the larger cases converge at roughly something larger than O(nlogn):

Couldn't it just be easier to answer the question by saying sort (mergesort) the range and iterate over it observing the missing elements?

This solution should take no more than O(nlogn) and is capable of solving the problem for ranges other than 1-to-N such as 10-to-1000 or -100 to +100 etc...

Is there any reason to believe that the given solutions in the above SO link will be better than the sorting based solution for larger number of missing values?

Note: It seems a lot of the common solutions to this problem, assume an only number theoretic approach. If one is being asked such a question in an S/E interview wouldn't it be prudent to use a more computer science/algorithmic approach, assuming the approach is on par with the number theoretic solution's complexity...

More related links:

https://mathoverflow.net/questions/25374/duplicate-detection-problem

How to tell if an array is a permutation in O(n)?

答:
If the range is given to you well ahead, in this case range is [1,10] you can perform XOR operation with your range and the numbers given to you. Since XOR is commutative operation. You will be left with {3,6}

(1 2 3 4 5 6 7 8 9 10) XOR (1 2 4 5 7 8 9 10) ={3,6}

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.


问:
How to pass large number of parameters from Angular js to rest service
I am trying to fetch parameters from angular JS $http service to rest service using **@queryParam** . I need to fetch lot of parameters(below have shown for 3 as an example ,but I need to use around 12-15 of them which I need to pass to the java side) ,so fetching all with @QueryParam makes the code look pretty bad .I am using GET.

How can I optimize this ?

Example what I am doing -

Angular Js code -

```<code>$http({
    url: someUrl,
    method: "GET",
    params: {filter1: $scope.filter1,
filter2:$scope.filter2,
filter3:$scope.filter3
 });
</code>```

Java side -

```<code>@path("/getAllData")
@GET
@Produces({..}
public response getAllData(@QueryParam("filter1") final String filter1,
                           @QueryParam("filter2") final String filter2,
                           @QueryParam("filter3") final String filter3){
}
</code>```

Also ,wanted to know the optimization in case when I am building URL instead of params object, and picking the same with @PathParam

```<code>$http.get('rest/test/getAllData/?filter1='$scope.filter1 +
           '&filter2='$scope.filter2 + '&filter3='$scope.filter3 +
           '&filter4='$scope.filter4)
</code>```

I am able to do it by passing individually in @QueryParam . I am looking for optimized code when we a large number of parameters.

答:
Create a POJO with all the required parameters.

In angular, do this

```<code>var obj = {};
obj.filter1 =  $scope.filter1;
obj.filter2 =  $scope.filter2;
obj.filter3 =  $scope.filter3;

$http({
    url: someUrl,
    method: "GET",
    params: obj
});
</code>```

You can accept all the parameters in you rest like this -

```<code>@path("/getAllData")
@GET
@Produces({..}
public response getAllData(MyPojo obj){
  //String filter1 = obj.filter1;
}
</code>```

Body:
I am trying to fetch parameters from angular JS $http service to rest service using **@queryParam** . I need to fetch lot of parameters(below have shown for 3 as an example ,but I need to use around 12-15 of them which I need to pass to the java side) ,so fetching all with @QueryParam makes the code look pretty bad .I am using GET.

How can I optimize this ?

Example what I am doing -

Angular Js code -

$http({
    url: someUrl,
    method: "GET",
    params: {filter1: $scope.filter1,
filter2:$scope.filter2,
filter3:$scope.filter3
 });

Java side -

@path("/getAllData")
@GET
@Produces({..}
public response getAllData(@QueryParam("filter1") final String filter1,
                           @QueryParam("filter2") final String filter2,
                           @QueryParam("filter3") final String filter3){
}

Also ,wanted to know the optimization in case when I am building URL instead of params object, and picking the same with @PathParam

$http.get('rest/test/getAllData/?filter1='$scope.filter1 +
           '&filter2='$scope.filter2 + '&filter3='$scope.filter3 +
           '&filter4='$scope.filter4)

I am able to do it by passing individually in @QueryParam . I am looking for optimized code when we a large number of parameters.

Body:
Create a POJO with all the required parameters.

In angular, do this

var obj = {};
obj.filter1 =  $scope.filter1;
obj.filter2 =  $scope.filter2;
obj.filter3 =  $scope.filter3;

$http({
    url: someUrl,
    method: "GET",
    params: obj
});

You can accept all the parameters in you rest like this -

@path("/getAllData")
@GET
@Produces({..}
public response getAllData(MyPojo obj){
  //String filter1 = obj.filter1;
}


问:
Creating carousel using php and fetching data from sql
I am trying to create a page with carousel using php fetching image and title from sql. I created a carousel using html and css, but im not really sure how to transfer it using php.

My original carousel:

```<code><div class="container">
    <div id="myCarousel" class="carousel slide" data-ride="carousel">

      <div class="carousel-inner">

        <div class="item active">
          <img src="images/aa1.jpg">
           <div class="carousel-caption">
            <h4><b>Title</h4></b>
            <p><a class="label label-primary" href="news1.php" target="_blank" style="float: right;">Read More</a></p>
          </div>
        </div><!-- End Item -->

         <div class="item">
          <img src="images/aa2.jpg">
           <div class="carousel-caption">
           <h4><b>Title</h4></b>
            <p><a class="label label-primary" href="news2.php" target="_blank" style="float: right;">Read More</a></p>
          </div>
        </div><!-- End Item -->

        <div class="item">
          <img src="images/aa3.jpg">
           <div class="carousel-caption">
            <h4><b>Title</h4></b>
            <p><a class="label label-primary" href="news3.php" target="_blank" style="float: right;">Read More</a></p>
          </div>
        </div>

        <div class="item">
          <img src="images/aa4.jpg">
           <div class="carousel-caption">
            <h4><b>Title</h4></b>
            <p><a class="label label-primary" href="news4.php" target="_blank" style="float: right;">Read More</a></p>
          </div>
        </div>

        <div class="item">
          <img src="images/aa5.jpg">
           <div class="carousel-caption">
            <h4><b>Title</h4></b>
          <p><a class="label label-primary" href="news5.php" target="_blank" style="float: right;">Read More</a></p>
          </div>
        </div>

      </div>
    <ul class="list-group col-sm-4">
      <li data-target="#myCarousel" data-slide-to="0" class="list-group-item active"><h5>Tilte Tilte Tilte</h5></li>
      <li data-target="#myCarousel" data-slide-to="1" class="list-group-item"><h5>Tilte Tilte Tilte</h5></li>
      <li data-target="#myCarousel" data-slide-to="2" class="list-group-item"><h5>Tilte Tilte Tilte</h5></li>
      <li data-target="#myCarousel" data-slide-to="3" class="list-group-item"><h5>Tilte Tilte Tilte</h5></li>
      <li data-target="#myCarousel" data-slide-to="4" class="list-group-item"><h5>Tilte Tilte Tilte</h5></li>
    </ul>
      <!-- Controls -->
      <div class="carousel-controls">
          <a class="left carousel-control" href="#myCarousel" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left"></span>
          </a>
          <a class="right carousel-control" href="#myCarousel" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right"></span>
          </a>
      </div>
    </div>
          <a class="right carousel-control" href="#myCarousel" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right"></span>
          </a>
      </div>
</div>
</code>```

Now I created a database named test with a table named carousel looks like:

```<code>----------------------------------------------
| title | image        | link                |
----------------------------------------------
| demo  | demo.png     |images/demo.png      |
----------------------------------------------
</code>```

I tried calling it but nothing works. I'm new to php.

My Code:

```<code><?php
$link = mysqli_connect("localhost", "root", "", "test");
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM news";
if($result = mysqli_query($link, $sql)){
    if(mysqli_num_rows($result) > 0){
        echo "<div class=\"container\">";
        echo "<div id=\"myCarousel\"class=\"carousel slide\"data-ride=\"carousel\">";
      echo "<div class=\"carousel-inner\">";
      echo "<div class=\"item active\">";
           echo "<img alt=\"News\" src=\"images/{$row["image"]}\">";
           echo "<p>{$row["title"]}</p>";
           echo "<ul class=\"list-group col-sm-4\"href=\"{$row["link"]}\"echo "<b><h4>{$row["title"]}">;
    <a data-slide="prev" href="#Carousel" class="left carousel-control">‹</a> <a data-slide="next" href="#Carousel" class="right carousel-control">›</a> </div>
       echo "</div>"
    echo "</div>";
    echo "</div>";
    echo "</div>";
    echo "</div>";
?>
</code>```

How can I do that?

答:
You have to add while loop in your HTML file, try using this.</p>

```<code><div id="slideshow">
    <div id="slidesContainer">
       <div class="slide">
         <?php
            error_reporting(E_ALL);

            $query = "SELECT id, path, name FROM images";
            $result = mysql_query($query);
            $num = mysql_num_rows($result);

            while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
            echo "<img src=\"$row[path]\" title=\"$row[name]\" alt=\"\" />";
                                            }
            ?>
       </div>
     </div>
    </div>
</code>```

Body:
I am trying to create a page with carousel using php fetching image and title from sql. I created a carousel using html and css, but im not really sure how to transfer it using php.

My original carousel:

Title

Read More

Title

Read More

Title

Read More

Title

Read More

Title

Read More

Tilte Tilte Tilte

Tilte Tilte Tilte

Tilte Tilte Tilte

Tilte Tilte Tilte

Tilte Tilte Tilte

Now I created a database named test with a table named carousel looks like:

----------------------------------------------
| title | image        | link                |
----------------------------------------------
| demo  | demo.png     |images/demo.png      |
----------------------------------------------

I tried calling it but nothing works. I'm new to php.

My Code:

<?php
$link = mysqli_connect("localhost", "root", "", "test");
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM news";
if($result = mysqli_query($link, $sql)){
    if(mysqli_num_rows($result) > 0){
        echo "
";
        echo "
";
      echo "
";
      echo "
";
           echo "";
           echo "
{$row["title"]}
";
           echo "<ul class=\"list-group col-sm-4\"href=\"{$row["link"]}\"echo "
{$row["title"]}">;
    ‹ ›

       echo "
"
    echo "
";
    echo "
";
    echo "
";
    echo "
";
?>

How can I do that?

Body:
You have to add while loop in your HTML file, try using this.

<div id="slideshow">
    <div id="slidesContainer">
       <div class="slide">
         <?php
            error_reporting(E_ALL);

            $query = "SELECT id, path, name FROM images";
            $result = mysql_query($query);
            $num = mysql_num_rows($result);

            while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
            echo "<img src=\"$row[path]\" title=\"$row[name]\" alt=\"\" />";
                                            }
            ?>
       </div>
     </div>
    </div>


问:
How to fix AMPPS showing blank page
Randomly stopped being able to load any sites configured within AMPPS.

The pages would just load a blank white page with no content or errors.

I could successfully load the AMPPS config page at http://localhost/ampps/.

答:
Stop both Apache and MySQL

Navigate to PHP settings tab

Click change PHP version

Change to a different version and click apply

Change back to the original version and click apply

Start Apache & MySQL

Title: How to fix AMPPS showing blank page


问:
MySQL Insert with select subquery for one value
I have a MySQL insert query which needs to pull one data field from another table and I was wondering if this can be done with a select subquery

```<code>INSERT INTO resources
(
     client_account_id,
     date_time,
     resource_name,
     resource_description_id,
)
VALUES
(
      {0},
      '{1}',
      '{2}',
      {3},
 )
</code>```

and I need a select query to get the resource_description_id from another table

```<code>SELECT resource_description_id
FROM resource_descriptions
WHERE resource_description = '{0}'
</code>```

I have seen examples for duplicating entire tables, but I'm not sure how this can be done when just one field is needed from another table and the other fields come from a form.

Thanks!

答:
MySQL didn't like most of these queries unless I added parenthesis around the subquery. Here is what I used.</p>

```<code>INSERT INTO resources
(
 client_account_id,
 date_time,
 resource_name,
 resource_description_id,
)
VALUES
(
  '{0}',
  '{1}',
  '{2}',
  (SELECT resource_description_id
   FROM resource_descriptions
   WHERE resource_description = '{0}')
)
</code>```

Body:
I have a MySQL insert query which needs to pull one data field from another table and I was wondering if this can be done with a select subquery

INSERT INTO resources
(
     client_account_id,
     date_time,
     resource_name,
     resource_description_id,
)
VALUES
(
      {0},
      '{1}',
      '{2}',
      {3},
 )

and I need a select query to get the resource_description_id from another table

SELECT resource_description_id
FROM resource_descriptions
WHERE resource_description = '{0}'

I have seen examples for duplicating entire tables, but I'm not sure how this can be done when just one field is needed from another table and the other fields come from a form.

Thanks!

Body:
MySQL didn't like most of these queries unless I added parenthesis around the subquery. Here is what I used.

INSERT INTO resources
(
 client_account_id,
 date_time,
 resource_name,
 resource_description_id,
)
VALUES
(
  '{0}',
  '{1}',
  '{2}',
  (SELECT resource_description_id
   FROM resource_descriptions
   WHERE resource_description = '{0}')
)


问:
Split a separated value to new single column
I want to separate the | delimited string into new column, I tried the below code but I think is not a good practice.

```<code>SELECT
    REPLACE(SUBSTRING(ReferenceName, 1, CHARINDEX('|', ReferenceName)), '|', '') AS CreditCard,
    ReferenceName
FROM
    CTS.DBO.cts_TxSalesPayment
</code>```

Expected result

Split the value based on the delimiter:

```<code>CardNumber | ExpiryDate | ApprovalCode | .... | ... | ... | ...
</code>```

答:
One way would be to use a REPLACE function to allow the column to be parsed as XML, then PIVOT the result.

For example:

```<code>DECLARE @T TABLE (ReferenceName VARCHAR(MAX));
INSERT @T VALUES ('CardNumber=asdf|ExpiryDate=1234124x|ApprovalCode=aaaaa'), ('CardNumber=zzz|ExpiryDate=123|ApprovalCode=q'), ('CardNumber=zzz|ExpiryDate=111|ApprovalCode=q2');

SELECT *
FROM
(
    SELECT RN, colName = A.B.value('local-name(.)', 'varchar(max)'), colVal = A.B.value('@val', 'varchar(max)')
    FROM
    (
        SELECT RN = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), col = CAST('<' + REPLACE(REPLACE(ReferenceName, '=', ' val='''), '|', '''/><') + ''' />' AS XML)
        FROM @T
    ) AS T
    CROSS APPLY col.nodes('*') AS A(B)
) AS T
PIVOT
(
    MAX(colVal) FOR colName IN ([CardNumber], [ExpiryDate], [ApprovalCode])
) AS P;
</code>```

Body:
I want to separate the | delimited string into new column, I tried the below code but I think is not a good practice.

SELECT
    REPLACE(SUBSTRING(ReferenceName, 1, CHARINDEX('|', ReferenceName)), '|', '') AS CreditCard,
    ReferenceName
FROM
    CTS.DBO.cts_TxSalesPayment

Expected result

Split the value based on the delimiter:

CardNumber | ExpiryDate | ApprovalCode | .... | ... | ... | ...

Body:
One way would be to use a REPLACE function to allow the column to be parsed as XML, then PIVOT the result.

For example:

DECLARE @T TABLE (ReferenceName VARCHAR(MAX));
INSERT @T VALUES ('CardNumber=asdf|ExpiryDate=1234124x|ApprovalCode=aaaaa'), ('CardNumber=zzz|ExpiryDate=123|ApprovalCode=q'), ('CardNumber=zzz|ExpiryDate=111|ApprovalCode=q2');

SELECT *
FROM
(
    SELECT RN, colName = A.B.value('local-name(.)', 'varchar(max)'), colVal = A.B.value('@val', 'varchar(max)')
    FROM
    (
        SELECT RN = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), col = CAST('<' + REPLACE(REPLACE(ReferenceName, '=', ' val='''), '|', '''/><') + ''' />' AS XML)
        FROM @T
    ) AS T
    CROSS APPLY col.nodes('*') AS A(B)
) AS T
PIVOT
(
    MAX(colVal) FOR colName IN ([CardNumber], [ExpiryDate], [ApprovalCode])
) AS P;