问:
Returning form results in a separate div tag
So I want to return a user's form results in a div so they can see what they have chosen underneath the form using JQuery but struggling to use the right code? Ive tried using the .html function and replaceWith. etc but nothing seems to be working?

Here's my html code:

```<code><form id="myform">
    <h4>Enter your booking slot here:</h4><br>
    <select id="programmes">
        <option value="test1">Test 1</option>
        <option value="test2">Test 2</option>
        <option value="test3">Test 3</option>
        <option value="test4">Test 4</option>
        <option value="test5">Test 5</option>
    </select><br><br>
    <select id="time">
        <option value="one">01:00</option>
        <option value="two">02:00</option>
        <option value="three">03:00</option>
        <option value="four">04:00</option>
        <option value="five">05:00</option>
        <option value="six">06:00</option>
        <option value="seven">07:00</option>
        <option value="eight">08:00</option>
        <option value="nine">09:00</option>
        <option value="ten">10:00</option>
        <option value="eleven">11:00</option>
        <option value="twevle">12:00</option>
        <option value="one-pm">13:00</option>
        <option value="two-pm">14:00</option>
        <option value="three-pm">15:00</option>
        <option value="four-pm">16:00</option>
        <option value="five-pm">17:00</option>
        <option value="six-pm">18:00</option>
        <option value="seven-pm">19:00</option>
        <option value="eight-pm">20:00</option>
        <option value="nine-pm">21:00</option>
        <option value="ten-pm">22:00</option>
        <option value="eleven-pm">23:00</option>
        <option value="midnight">00:00</option>
    </select><br><br>
    <button type="submit" value="Submit Booking">
</form>
</div>

<div></div>
</code>```

答:
$('#select').on('change', function() {
  $('#result').html( $(this).find('option:selected').text() )
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select">
  <option value="test_1">Test 1</option>
  <option value="test_2">Test 2</option>
  <option value="test_3">Test 3</option>
  <option value="test_4">Test 4</option>
  <option value="test_5">Test 5</option>
</select>

<div id="result"></div></code>```

Body:
So I want to return a user's form results in a div so they can see what they have chosen underneath the form using JQuery but struggling to use the right code? Ive tried using the .html function and replaceWith. etc but nothing seems to be working?

Here's my html code:

<form id="myform">

Enter your booking slot here:

    <select id="programmes">
        <option value="test1">Test 1</option>
        <option value="test2">Test 2</option>
        <option value="test3">Test 3</option>
        <option value="test4">Test 4</option>
        <option value="test5">Test 5</option>
    </select>

    <select id="time">
        <option value="one">01:00</option>
        <option value="two">02:00</option>
        <option value="three">03:00</option>
        <option value="four">04:00</option>
        <option value="five">05:00</option>
        <option value="six">06:00</option>
        <option value="seven">07:00</option>
        <option value="eight">08:00</option>
        <option value="nine">09:00</option>
        <option value="ten">10:00</option>
        <option value="eleven">11:00</option>
        <option value="twevle">12:00</option>
        <option value="one-pm">13:00</option>
        <option value="two-pm">14:00</option>
        <option value="three-pm">15:00</option>
        <option value="four-pm">16:00</option>
        <option value="five-pm">17:00</option>
        <option value="six-pm">18:00</option>
        <option value="seven-pm">19:00</option>
        <option value="eight-pm">20:00</option>
        <option value="nine-pm">21:00</option>
        <option value="ten-pm">22:00</option>
        <option value="eleven-pm">23:00</option>
        <option value="midnight">00:00</option>
    </select>

    <button type="submit" value="Submit Booking">
</form>

Body:
$('#select').on('change', function() {
  $('#result').html( $(this).find('option:selected').text() )
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select">
  <option value="test_1">Test 1</option>
  <option value="test_2">Test 2</option>
  <option value="test_3">Test 3</option>
  <option value="test_4">Test 4</option>
  <option value="test_5">Test 5</option>
</select>

<div id="result"></div>


来源: stackexchange

问:
FileNotFoundException with Universal Image Loader
This question is about this popular Android library, Universal Image Loader for Android: https://github.com/nostra13/Android-Universal-Image-Loader

I made sure WRITE_EXTERNAL_STORAGE is added.

I enabled both memory and disk cache

I used UnlimitedDiscCache for disk cache

I'm building against Android 2.2 SDK. The exception is found when I'm testing the app on a Android 4.1.2 Nexus S device.

For most of my images, the loading is smooth and fine. However, for certain images, I always get the same exception. Below is an example.

Image URL: http://i10.topit.me/l046/10046137034b1c0db0.jpg

Back trace:

```<code>01-14 00:24:42.125:

ERROR/ImageLoader(1671): http://i10.topit.me/l046/10046137034b1c0db0.jpg

java.io.FileNotFoundException: http://i10.topit.me/l046/10046137034b1c0db0.jpg

at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)

at com.nostra13.universalimageloader.core.download.URLConnectionImageDownloader.getStreamFromNetwork(URLConnectionImageDownloader.java:40)

at com.nostra13.universalimageloader.core.download.ImageDownloader.getStream(ImageDownloader.java:27)

at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.saveImageOnDisc(LoadAndDisplayImageTask.java:296)

at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:204)

at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:128)

at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)
</code>```

Please help.

答:
This configuration tuning is custom. You can tune every option, you may tune some of them, or you can create default configuration by ImageLoaderConfiguration.createDefault(this); method.

```<code> public static void initImageLoader(Context context) {

    ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
    config.threadPriority(Thread.NORM_PRIORITY - 2);
    config.denyCacheImageMultipleSizesInMemory();
    config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
    config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
    config.tasksProcessingOrder(QueueProcessingType.LIFO);
    config.writeDebugLogs(); // Remove for release app

    // Initialize ImageLoader with configuration.
    ImageLoader.getInstance().init(config.build());
}
</code>```

I hope this helps anyone.

ContentLicense: CC BY-SA 3.0

Body:
This question is about this popular Android library, Universal Image Loader for Android: https://github.com/nostra13/Android-Universal-Image-Loader

I made sure WRITE_EXTERNAL_STORAGE is added.

I enabled both memory and disk cache

I used UnlimitedDiscCache for disk cache

I'm building against Android 2.2 SDK. The exception is found when I'm testing the app on a Android 4.1.2 Nexus S device.

For most of my images, the loading is smooth and fine. However, for certain images, I always get the same exception. Below is an example.

Image URL: http://i10.topit.me/l046/10046137034b1c0db0.jpg

Back trace:

01-14 00:24:42.125:

ERROR/ImageLoader(1671): http://i10.topit.me/l046/10046137034b1c0db0.jpg

java.io.FileNotFoundException: http://i10.topit.me/l046/10046137034b1c0db0.jpg

at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)

at com.nostra13.universalimageloader.core.download.URLConnectionImageDownloader.getStreamFromNetwork(URLConnectionImageDownloader.java:40)

at com.nostra13.universalimageloader.core.download.ImageDownloader.getStream(ImageDownloader.java:27)

at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.saveImageOnDisc(LoadAndDisplayImageTask.java:296)

at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:204)

at com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:128)

at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:442)

Please help.

Body:
This configuration tuning is custom. You can tune every option, you may tune some of them, or you can create default configuration by ImageLoaderConfiguration.createDefault(this); method.

 public static void initImageLoader(Context context) {

    ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
    config.threadPriority(Thread.NORM_PRIORITY - 2);
    config.denyCacheImageMultipleSizesInMemory();
    config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
    config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
    config.tasksProcessingOrder(QueueProcessingType.LIFO);
    config.writeDebugLogs(); // Remove for release app

    // Initialize ImageLoader with configuration.
    ImageLoader.getInstance().init(config.build());
}

I hope this helps anyone.


问:
JS: Item List - copy value content to clipboard
I have a item list (listview), something like this:

```<code><option value="String I want to get copied" title="String I want to get copied">Item1</option>
<option value="String I want to get copied-1" title="String I want to get copied-1">Item2</option>
</code>```

I need to get copied to clipboard the content of (Please, attention!) Title or Value, but NOT "Item1" or "Item2".

Select an item- Right click-Copy the value or title field to clipboard...

It would be great if it possible to do it via menu right mouse click (I'm making a chrome extension). But any idea where to dig will be much appreciated!

答:
Basically with JavaScript, you can't copy not printed text.
You can request special permission to do it but is not compatible with all web browsers.

https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Interact_with_the_clipboard

For that you need to use a flash plugin.

Body:
I have a item list (listview), something like this:

<option value="String I want to get copied" title="String I want to get copied">Item1</option>
<option value="String I want to get copied-1" title="String I want to get copied-1">Item2</option>

I need to get copied to clipboard the content of (Please, attention!) Title or Value, but NOT "Item1" or "Item2".

Select an item- Right click-Copy the value or title field to clipboard...

It would be great if it possible to do it via menu right mouse click (I'm making a chrome extension). But any idea where to dig will be much appreciated!


问:
Get username by id in Twitter Api
How can I get the user name by userid via a request to the Twitter Api?

Some other methods, like followers/ids, give us as response an array of IDs, from which I am not sure how I can get their usernames.

The response of the method "followers/ids" looks something like this:

```<code>{
"ids": [782235942383972400, 16664925, 839240398010781700, 39606379, 19713521,
...
...
...
...
...
899462802, 198446818],
"next_cursor": 0,
"next_cursor_str": "0",
"previous_cursor": 0,
"previous_cursor_str": "0"
}
</code>```

How I can get the username from these ids? I want something like what this webpage does.

答:
Use GET https://api.twitter.com/1.1/users/show.json?user_id=ID and see the screen_name property of the returned JSON object.

Reference: https://api.twitter.com/1.1/users/show.json

Title: Get username by id in Twitter Api

Body:
How can I get the user name by userid via a request to the Twitter Api?

Some other methods, like followers/ids, give us as response an array of IDs, from which I am not sure how I can get their usernames.

The response of the method "followers/ids" looks something like this:

{
"ids": [782235942383972400, 16664925, 839240398010781700, 39606379, 19713521,
...
...
...
...
...
899462802, 198446818],
"next_cursor": 0,
"next_cursor_str": "0",
"previous_cursor": 0,
"previous_cursor_str": "0"
}

How I can get the username from these ids? I want something like what this webpage does.


问:
Get PHP variabile in div from ajax call
I have this code in default.php:

jQuery(document).ready(function() {
  jQuery(function($) {
    var $from = jQuery("#from"),
      $to = jQuery("#to");

    $from.datepicker({
      numberOfMonths: 1,
      minDate: 1,
      dateFormat: 'dd-mm-yy',
      onClose: function(selectedDate) {
        $to.datepicker("option", "minDate", selectedDate);
      }
    });

    $from.change(function() {

      jQuery.ajax({
        url: 'index.php?option=com_vehiclemanager&task=default2',
        type: 'POST',
        data: {
          datepicker_value: $(this).val()
        },
        success: function(data) {
          $('#result').html(data);
        }
      });
    });

    ...
```

<p>This is the php script:</p>

```<?php

$database = JFactory::getDBO();

$datepicker_value = isset($_POST['datepicker_value']) ? $_POST['datepicker_value'] : NULL;
$month = date("m",strtotime($datepicker_value));

  $selectstring = "SELECT * FROM #__vehiclemanager_rent_sal WHERE fk_vehiclesid = 128 AND monthW = '$month'";
  $database->setQuery($selectstring);
  $string = $database->loadObject();

header('Content-Type: application/json');
$array[] = array(
'deposito'=>$string->deposit,
'spese'=>$string->cfee,
);
echo json_encode($array);
?>
```

I have a jquery datepicker in a table and i want to pick the variable from the php script via a database query with an ajax call, i can see the json object [{"deposito":"300","spese":"100"}]
but the single php variabile shows me undefined.
I inserted the task in the ajax url because the filename sends me back to the index.php, the homepage, as this is an external plugin.
I hope I explained myself and thanks for your help.

答: Instead of $(this).val(), try referencing the actual element. Something like this: $('#from').val().

Title: Get PHP variabile in div from ajax call

Body:
I have this code in default.php:

jQuery(document).ready(function() {
  jQuery(function($) {
    var $from = jQuery("#from"),
      $to = jQuery("#to");

    $from.datepicker({
      numberOfMonths: 1,
      minDate: 1,
      dateFormat: 'dd-mm-yy',
      onClose: function(selectedDate) {
        $to.datepicker("option", "minDate", selectedDate);
      }
    });

    $from.change(function() {

      jQuery.ajax({
        url: 'index.php?option=com_vehiclemanager&task=default2',
        type: 'POST',
        data: {
          datepicker_value: $(this).val()
        },
        success: function(data) {
          $('#result').html(data);
        }
      });
    });

    ...

This is the php script:

<?php

$database = JFactory::getDBO();

$datepicker_value = isset($_POST['datepicker_value']) ? $_POST['datepicker_value'] : NULL;
$month = date("m",strtotime($datepicker_value));

  $selectstring = "SELECT * FROM #__vehiclemanager_rent_sal WHERE fk_vehiclesid = 128 AND monthW = '$month'";
  $database->setQuery($selectstring);
  $string = $database->loadObject();

header('Content-Type: application/json');
$array[] = array(
'deposito'=>$string->deposit,
'spese'=>$string->cfee,
);
echo json_encode($array);
?>

I have a jquery datepicker in a table and i want to pick the variable from the php script via a database query with an ajax call, i can see the json object [{"deposito":"300","spese":"100"}]
but the single php variabile shows me undefined.
I inserted the task in the ajax url because the filename sends me back to the index.php, the homepage, as this is an external plugin.
I hope I explained myself and thanks for your help.


问:
Having trouble reading mutiple text files from a folder. filenotfoundexception
I have no problem getting it to run but it crashes when I hit the "Find Ranking" button. I've tried running it in BlueJ and NetBeans, both have the same issues. I get the following error:

```<code> java.io.FileNotFoundException: /Users/Marque/Desktop/Years (Is a directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at Main.readFile(Main.java:128)
    at Main$1.actionPerformed(Main.java:94)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6535)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6300)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4891)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

Below is my code.

```<code>import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
   Map<String,String> fileMap;

   JFrame f;
   JPanel yearPanel;
   JLabel yearLabel;
   JComboBox yearBox;
   JPanel genderPanel;
   JLabel genderLabel;
   JComboBox genderBox;
   JPanel namePanel;
   JLabel nameLabel;
   JTextField tf1;
   JPanel textPanel;
   JTextField textField;
   Main(){
       fileMap = new HashMap<String,String>();

       fileMap.put("2006", "/Users/Marque/Desktop/Years/2006.txt");
       fileMap.put("2007", "/Users/Marque/Desktop/Years/2007.txt");
       fileMap.put("2008", "/Users/Marque/Desktop/Years/2008.txt");
       fileMap.put("2009", "/Users/Marque/Desktop/Years/2009.txt");
       fileMap.put("2010", "/Users/Marque/Desktop/Years/2010.txt");

       String years[]={"2006","2007","2008","2009","2010"};
       String genders[]={"MALE","FEMALE"};
       f=new JFrame("Baby Name Popularity");

       yearPanel= new JPanel();
       yearLabel =new JLabel("Year");
       yearPanel.add(yearLabel);
       yearBox=new JComboBox<String>(years);
       yearPanel.add(yearBox);
       yearPanel.setLayout(new GridLayout(1, 2));
       f.add(yearPanel);

       genderPanel= new JPanel();
       genderLabel =new JLabel("Gender");
       genderPanel.add(genderLabel);
       genderBox=new JComboBox<String>(genders);
       genderPanel.add(genderBox);
       genderPanel.setLayout(new GridLayout(1, 2));
       f.add(genderPanel);

       namePanel= new JPanel();
       nameLabel =new JLabel("NAME");
       namePanel.add(nameLabel);
       tf1 = new JTextField();
       namePanel.add(tf1);
       namePanel.setLayout(new GridLayout(1, 2));
       f.add(namePanel);

       JPanel buttonPanel= new JPanel();
       buttonPanel.setLayout(new GridLayout(1, 2));
       JButton jb =new JButton("Find Ranking");

       buttonPanel.add(jb,0);

       f.add(buttonPanel);

       textPanel= new JPanel();
       textField = new JTextField();
       textPanel.add(textField);
       textPanel.setLayout(new GridLayout(1, 2));
       f.add(textPanel);

       jb.addActionListener(new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent e) {
               String year = (String)yearBox.getSelectedItem();
               String gender =(String)genderBox.getSelectedItem();
               String name =(String)tf1.getText();
               readFile("Years");
           }
       });

       f.setLayout(new GridLayout(5, 2,10,20));
       f.setSize(400,500);
       f.setVisible(true);

   }

   public static void main(String args[])
   {
       new Main();
   }

   public void readFile(String FILENAME){

       if(fileMap.containsKey(FILENAME))
           FILENAME = fileMap.get("/Users/Marque/Desktop/Years");

       BufferedReader br = null;
       FileReader fr = null;

       try {

           fr = new FileReader("/Users/Marque/Desktop/Years");
           br = new BufferedReader(fr);

           String sCurrentLine;

           br = new BufferedReader(new FileReader(FILENAME));
           boolean found =false;
           String name = (String)tf1.getText().trim();
           while ((sCurrentLine = br.readLine()) != null) {
               sCurrentLine=sCurrentLine.replaceAll("\\s+"," ");
               for(int i=0;i<sCurrentLine.split(" ").length;i++)
               {
                   String s=sCurrentLine.split(" ")[i];
                   if(s.equalsIgnoreCase(name)){
                       found=true;
                       textField.setText(""+s+" was #"+sCurrentLine.split(" ")[i+1]+" in "+yearBox.getSelectedItem()+"!");
                   }
               }
               if(!found)
               {
                   textField.setText("NAME NOT FOUND");
               }
           }

       } catch (IOException e) {

           e.printStackTrace();

       } finally {

           try {

               if (br != null)
                   br.close();

               if (fr != null)
                   fr.close();

           } catch (IOException ex) {

               ex.printStackTrace();

           }

       }
    }
}
</code>```

答:
refer to this:

https://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html

This class states that it accepts 3 types of parameter input:

```<code>FileReader(File file);
FileReader(FileDescriptor fd);
FileReader(String fileName);
</code>```

Looks like you're passing a directory while it explicitly states that you need to pass a File or a file location path.

Body:
I have no problem getting it to run but it crashes when I hit the "Find Ranking" button. I've tried running it in BlueJ and NetBeans, both have the same issues. I get the following error:

 java.io.FileNotFoundException: /Users/Marque/Desktop/Years (Is a directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at java.io.FileReader.<init>(FileReader.java:58)
    at Main.readFile(Main.java:128)
    at Main$1.actionPerformed(Main.java:94)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6535)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6300)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4891)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4713)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Below is my code.

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {
   Map<String,String> fileMap;

   JFrame f;
   JPanel yearPanel;
   JLabel yearLabel;
   JComboBox yearBox;
   JPanel genderPanel;
   JLabel genderLabel;
   JComboBox genderBox;
   JPanel namePanel;
   JLabel nameLabel;
   JTextField tf1;
   JPanel textPanel;
   JTextField textField;
   Main(){
       fileMap = new HashMap<String,String>();

       fileMap.put("2006", "/Users/Marque/Desktop/Years/2006.txt");
       fileMap.put("2007", "/Users/Marque/Desktop/Years/2007.txt");
       fileMap.put("2008", "/Users/Marque/Desktop/Years/2008.txt");
       fileMap.put("2009", "/Users/Marque/Desktop/Years/2009.txt");
       fileMap.put("2010", "/Users/Marque/Desktop/Years/2010.txt");

       String years[]={"2006","2007","2008","2009","2010"};
       String genders[]={"MALE","FEMALE"};
       f=new JFrame("Baby Name Popularity");

       yearPanel= new JPanel();
       yearLabel =new JLabel("Year");
       yearPanel.add(yearLabel);
       yearBox=new JComboBox<String>(years);
       yearPanel.add(yearBox);
       yearPanel.setLayout(new GridLayout(1, 2));
       f.add(yearPanel);

       genderPanel= new JPanel();
       genderLabel =new JLabel("Gender");
       genderPanel.add(genderLabel);
       genderBox=new JComboBox<String>(genders);
       genderPanel.add(genderBox);
       genderPanel.setLayout(new GridLayout(1, 2));
       f.add(genderPanel);

       namePanel= new JPanel();
       nameLabel =new JLabel("NAME");
       namePanel.add(nameLabel);
       tf1 = new JTextField();
       namePanel.add(tf1);
       namePanel.setLayout(new GridLayout(1, 2));
       f.add(namePanel);

       JPanel buttonPanel= new JPanel();
       buttonPanel.setLayout(new GridLayout(1, 2));
       JButton jb =new JButton("Find Ranking");

       buttonPanel.add(jb,0);

       f.add(buttonPanel);

       textPanel= new JPanel();
       textField = new JTextField();
       textPanel.add(textField);
       textPanel.setLayout(new GridLayout(1, 2));
       f.add(textPanel);

       jb.addActionListener(new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent e) {
               String year = (String)yearBox.getSelectedItem();
               String gender =(String)genderBox.getSelectedItem();
               String name =(String)tf1.getText();
               readFile("Years");
           }
       });

       f.setLayout(new GridLayout(5, 2,10,20));
       f.setSize(400,500);
       f.setVisible(true);

   }

   public static void main(String args[])
   {
       new Main();
   }

   public void readFile(String FILENAME){

       if(fileMap.containsKey(FILENAME))
           FILENAME = fileMap.get("/Users/Marque/Desktop/Years");

       BufferedReader br = null;
       FileReader fr = null;

       try {

           fr = new FileReader("/Users/Marque/Desktop/Years");
           br = new BufferedReader(fr);

           String sCurrentLine;

           br = new BufferedReader(new FileReader(FILENAME));
           boolean found =false;
           String name = (String)tf1.getText().trim();
           while ((sCurrentLine = br.readLine()) != null) {
               sCurrentLine=sCurrentLine.replaceAll("\\s+"," ");
               for(int i=0;i<sCurrentLine.split(" ").length;i++)
               {
                   String s=sCurrentLine.split(" ")[i];
                   if(s.equalsIgnoreCase(name)){
                       found=true;
                       textField.setText(""+s+" was #"+sCurrentLine.split(" ")[i+1]+" in "+yearBox.getSelectedItem()+"!");
                   }
               }
               if(!found)
               {
                   textField.setText("NAME NOT FOUND");
               }
           }

       } catch (IOException e) {

           e.printStackTrace();

       } finally {

           try {

               if (br != null)
                   br.close();

               if (fr != null)
                   fr.close();

           } catch (IOException ex) {

               ex.printStackTrace();

           }

       }
    }
}

Body:
refer to this:

https://docs.oracle.com/javase/7/docs/api/java/io/FileReader.html

This class states that it accepts 3 types of parameter input:

FileReader(File file);
FileReader(FileDescriptor fd);
FileReader(String fileName);

Looks like you're passing a directory while it explicitly states that you need to pass a File or a file location path.


问:
Android ExoPlayer Listener Infinite loop
I want to use ExoPlayer with SurfaceView and SeekBar. buildTrackName function I took from ExoPlayer Demo. I want to use SeekBar for changing position of player and listView for displaying all of audio track of my video. When I'm use ExoPlayer functions to get player duration or get all audio tracks from video, these functions return -1 for getDuration() and 0 for getTrackCount(). I tried to put these functions in different parts of the code, but they work only in onPlayerStateChanged method of ExoPlayer.Listener. But! in this case, after all the functions, the program goes into an infinite loop.</p>

```<code>public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback{

private String videoPath = "myVideoPath";
private SurfaceView surfaceView;
private SeekBar seekBar;
private ListView listView;
private ArrayList<String> trackList;
private ArrayAdapter<String> arrayAdapter;
private ExoPlayer exoPlayer;

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

surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
seekBar = (SeekBar) findViewById(R.id.seekBar);
listView = (ListView) findViewById(R.id.listView);

trackList = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, audioList);
listView.setAdapter(arrayAdapter);

MediaCodecSelector mediaCodecSelector = MediaCodecSelector.DEFAULT;

Uri uri = Uri.parse(videoPath);
DataSource dataSource = new DefaultUriDataSource(this, "test");
ExtractorSampleSource extractorSampleSource = new ExtractorSampleSource(
        uri, dataSource, new DefaultAllocator(64*1024), 256*64*1024,null);
MediaCodecVideoTrackRenderer videoRenderer = new MediaCodecVideoTrackRenderer(this,extractorSampleSource,mediaCodecSelector,MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT);
MediaCodecAudioTrackRenderer audioRenderer = new MediaCodecAudioTrackRenderer(
        extractorSampleSource, mediaCodecSelector);

exoPlayer = ExoPlayer.Factory.newInstance(2);

exoPlayer.sendMessage(videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surfaceView.getHolder().getSurface());

exoPlayer.prepare(videoRenderer,audioRenderer);

exoPlayer.setPlayWhenReady(true);

exoPlayer.addListener(new ExoPlayer.Listener() {
    @Override
    public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
        if (playbackState == ExoPlayer.STATE_READY){
            seekBar.setMax((int)exoPlayer.getDuration());
            int trackCount = exoPlayer.getTrackCount(1);
            for (int i = 0; i < trackCount; i++) {
                trackList.add(buildTrackName(exoPlayer.getTrackFormat(1, i)));
            }
        } //infinite loop after this place
    }

    @Override
    public void onPlayWhenReadyCommitted() {

    }

    @Override
    public void onPlayerError(ExoPlaybackException error) {

    }
});

}

///
}
</code>```

答: ExoPlayer 2 brigns supports seamless looping of videos with LoopingMediaSource</p>

Body:
I want to use ExoPlayer with SurfaceView and SeekBar. buildTrackName function I took from ExoPlayer Demo. I want to use SeekBar for changing position of player and listView for displaying all of audio track of my video. When I'm use ExoPlayer functions to get player duration or get all audio tracks from video, these functions return -1 for getDuration() and 0 for getTrackCount(). I tried to put these functions in different parts of the code, but they work only in onPlayerStateChanged method of ExoPlayer.Listener. But! in this case, after all the functions, the program goes into an infinite loop.

public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback{

private String videoPath = "myVideoPath";
private SurfaceView surfaceView;
private SeekBar seekBar;
private ListView listView;
private ArrayList<String> trackList;
private ArrayAdapter<String> arrayAdapter;
private ExoPlayer exoPlayer;

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

surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
seekBar = (SeekBar) findViewById(R.id.seekBar);
listView = (ListView) findViewById(R.id.listView);

trackList = new ArrayList<>();
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, audioList);
listView.setAdapter(arrayAdapter);

MediaCodecSelector mediaCodecSelector = MediaCodecSelector.DEFAULT;

Uri uri = Uri.parse(videoPath);
DataSource dataSource = new DefaultUriDataSource(this, "test");
ExtractorSampleSource extractorSampleSource = new ExtractorSampleSource(
        uri, dataSource, new DefaultAllocator(64*1024), 256*64*1024,null);
MediaCodecVideoTrackRenderer videoRenderer = new MediaCodecVideoTrackRenderer(this,extractorSampleSource,mediaCodecSelector,MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT);
MediaCodecAudioTrackRenderer audioRenderer = new MediaCodecAudioTrackRenderer(
        extractorSampleSource, mediaCodecSelector);

exoPlayer = ExoPlayer.Factory.newInstance(2);

exoPlayer.sendMessage(videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surfaceView.getHolder().getSurface());

exoPlayer.prepare(videoRenderer,audioRenderer);

exoPlayer.setPlayWhenReady(true);

exoPlayer.addListener(new ExoPlayer.Listener() {
    @Override
    public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
        if (playbackState == ExoPlayer.STATE_READY){
            seekBar.setMax((int)exoPlayer.getDuration());
            int trackCount = exoPlayer.getTrackCount(1);
            for (int i = 0; i < trackCount; i++) {
                trackList.add(buildTrackName(exoPlayer.getTrackFormat(1, i)));
            }
        } //infinite loop after this place
    }

    @Override
    public void onPlayWhenReadyCommitted() {

    }

    @Override
    public void onPlayerError(ExoPlaybackException error) {

    }
});

}

///
}


问:
Invoke Class Method using Reflection with different params in constructor?
Hello i am very new to c# reflection and i have the following problem.

I have a CommandDispatcher class that invokes a certain Command class that does something.

For now i use a switch to determinate what command to invoke.

i wanted to simplify the code by using reflection to invoke the right command and get rid of the switch for good.

But each command takes a certain service or more in its constructor. I don't want to change that part . I understand that if i had no services passed in the constructor the code would work fine.

So how can i invoke my commands with reflection when each command takes one or many services.

Here is an image for better understanding: The code with color indicators

I left the switch not commented out for easier reading.

Here is the code in pastebin: https://pastebin.com/AMQeh1zw

My search did not result in finding anything to solve my problem.

答:
The best way to handle your use case is to use IoC and DI.

For the case of reflection as of now you can determine the constructor parameters and their types for a given type by using following code.

Let say there is a class MyClass

```<code>public class MyClass
{
     int age;
     double salary;
     public MyClass(int x, double y)
     {
         age = x;
         salary = y;
     }
}
</code>```

You can get information about all the constructors of MyClass using following logic

```<code>var ctors = typeof(MyClass).GetConstructors();
// assuming class MyClass has only one constructor
var ctor = ctors[0];
foreach (var param in ctor.GetParameters())
{
    Console.WriteLine(string.Format(
        "Param {0} is named {1} and is of type {2}",
        param.Position, param.Name, param.ParameterType));
}
</code>```

Now once you know the type of the constructor parameters you can create objects of those types with values assigned to them and use them to create object of MyClass as following.

```<code>var parameters = new List<object>();
foreach (var param in ctor.GetParameters())
{
    var obj = Activator.CreateInstance(param.ParameterType);
    parameters.Add(obj);
}

var myClassObj = Activator.CreateInstance(typeof(MyClass), parameters.ToArray());
</code>```

The limitation here, you would notice, is you can not set properties or values of obj as it is of tyoe object. If you convert it to specific type then you will end up having switch case or if-else ladder. So as long as the constructor of your class expects parameters of reference type (class type) this code would work fine.

Body:
The best way to handle your use case is to use IoC and DI.

For the case of reflection as of now you can determine the constructor parameters and their types for a given type by using following code.

Let say there is a class MyClass

public class MyClass
{
     int age;
     double salary;
     public MyClass(int x, double y)
     {
         age = x;
         salary = y;
     }
}

You can get information about all the constructors of MyClass using following logic

var ctors = typeof(MyClass).GetConstructors();
// assuming class MyClass has only one constructor
var ctor = ctors[0];
foreach (var param in ctor.GetParameters())
{
    Console.WriteLine(string.Format(
        "Param {0} is named {1} and is of type {2}",
        param.Position, param.Name, param.ParameterType));
}

Now once you know the type of the constructor parameters you can create objects of those types with values assigned to them and use them to create object of MyClass as following.

var parameters = new List<object>();
foreach (var param in ctor.GetParameters())
{
    var obj = Activator.CreateInstance(param.ParameterType);
    parameters.Add(obj);
}

var myClassObj = Activator.CreateInstance(typeof(MyClass), parameters.ToArray());

The limitation here, you would notice, is you can not set properties or values of obj as it is of tyoe object. If you convert it to specific type then you will end up having switch case or if-else ladder. So as long as the constructor of your class expects parameters of reference type (class type) this code would work fine.


问:
Camunda Rest API Assign Task Group
We are using Camunda in our application for approval flow. As per the below documentation from Camunda we can create the task and assign it to user.

I wanted to know if we can assign the task to a group instead of individual user

Request parameters - I tried with "candidateGroups" : {"value"} but no luck.

```<code>{
  "id": "aTaskId",
  "name": "My Task",
  "description": "This have to be done very urgent",
  "priority" : 30,
  "assignee" : "peter",
  "owner" : "mary",
  "delegationState" : "PENDING",
  "due" : "2014-08-30T10:00:00",
  "followUp" : "2014-08-25T10:00:00",
  "parentTaskId" : "aParentTaskId",
  "caseInstanceId" : "aCaseInstanceId"
}
</code>```

答:
You can't assign a task to a group. But you can define candidate groups into your BPMN process. This can also be a service/query.

The candidateGroups attribute: this custom extension allows you to
  make a group a candidate for a task.

```<code><userTask id="theTask" name="my task" camunda:candidateGroups="management, accountancy" />
</code>```

This is exactly
  the same as using a potentialOwner construct as defined above. Note
  that it is not required to use the group(management) declaration as is
  the case with the potential owner construct, since this attribute can
  only be used for groups.

https://docs.camunda.org/manual/7.6/reference/bpmn20/tasks/user-task/#candidate-groups

Title: Camunda Rest API Assign Task Group

Body:
We are using Camunda in our application for approval flow. As per the below documentation from Camunda we can create the task and assign it to user.

I wanted to know if we can assign the task to a group instead of individual user

Request parameters - I tried with "candidateGroups" : {"value"} but no luck.

{
  "id": "aTaskId",
  "name": "My Task",
  "description": "This have to be done very urgent",
  "priority" : 30,
  "assignee" : "peter",
  "owner" : "mary",
  "delegationState" : "PENDING",
  "due" : "2014-08-30T10:00:00",
  "followUp" : "2014-08-25T10:00:00",
  "parentTaskId" : "aParentTaskId",
  "caseInstanceId" : "aCaseInstanceId"
}

Body:
You can't assign a task to a group. But you can define candidate groups into your BPMN process. This can also be a service/query.

The candidateGroups attribute: this custom extension allows you to
  make a group a candidate for a task.

<userTask id="theTask" name="my task" camunda:candidateGroups="management, accountancy" />

This is exactly
  the same as using a potentialOwner construct as defined above. Note
  that it is not required to use the group(management) declaration as is
  the case with the potential owner construct, since this attribute can
  only be used for groups.

https://docs.camunda.org/manual/7.6/reference/bpmn20/tasks/user-task/#candidate-groups


问:
How to view Linux file system through file browser dialog?
I want to allow the user to select a folder path in a Linux file system from my Windows forms application. There are a number of Linux machines on my network, but I'm not sure how to go about accessing them from Windows. A file browser dialog for the file system of each Linux machine is ideal, but I'm not sure if it is realistic. Is this possible?

I have not worked with Linux before so I am a bit over my head right now, any help / workarounds are appreciated!

Thank you.

答:
This would be done by mounting your linux systems onto your windows PC as network drives. See how to do this here (guide is for windows 10 but same principal applies.)

After doing so you should be able to see and navigate the drives using a standard OpenFileDialog. If you need more help just leave a comment and I can try help with what you cannot understand, but try google or search stackoverflow first and someone may already have the same problem as what you are facing.


问:
Rails nested routes
I am learning Rails and making a reddit clone to help me understand how routing works.

Each post has subreddit. I have the following in my routes file:

```<code>resources :subreddits  do
 resources :posts
end
</code>```

This way I can create new posts with the following url:

```<code>/subreddits/:subreddit_id/posts/new(.:format)
</code>```

Example:

```<code>http://localhost:3000/subreddits/1/posts/new
</code>```

However I still need to specify in the new posts form what subreddit I want to post to belong to. Wheras what I want is a hidden field that sets the subreddit id to the correct one. The correct one being the one given in the URL.

This is what I currently have:

```<code>=simple_form_for @post, html: {multipart: true} do |f|
-if @post.errors.any?
    #errors
        %h2
        =pluralize(@post.errors.count, "error")
        prevented this pin from saving
        %ul
            -@post.errors.full_messages.each do |msg|
                %li= msg

.form-group
    =f.input :title, input_html: {class: 'form-control'}

.form-group
    =f.input :content, input_html: {class: 'form-control'}

=f.hidden_field :subreddit_id, :value => @post.subreddit_id

=f.button :submit, class: "btn btn-primary"
</code>```

I get the following error:

```<code>No route matches {:action=>"show", :controller=>"posts", :id=>33, :subreddit_id=>nil} missing required keys: [:subreddit_id]
</code>```

I think this is because I am trying to access the subreddit id of a post that hasn't been created yet. How do I solve this? Am I going about it in the wrong direction?

答:
In the new action of the posts_controller, you'll set the @subreddit instance variable

```<code>def new
  @subreddit = Subreddit.find(params[:subreddit_id])
  @post = Post.new
end
</code>```

In the form, you'll need to change the first line

```<code>= simple_form_for [@subreddit, @post], html: {multipart: true} do |f|
</code>```

:subreddit_id will now be in the url

Title: Rails nested routes

Body:
I am learning Rails and making a reddit clone to help me understand how routing works.

Each post has subreddit. I have the following in my routes file:

resources :subreddits  do
 resources :posts
end

This way I can create new posts with the following url:

/subreddits/:subreddit_id/posts/new(.:format)

Example:

http://localhost:3000/subreddits/1/posts/new

However I still need to specify in the new posts form what subreddit I want to post to belong to. Wheras what I want is a hidden field that sets the subreddit id to the correct one. The correct one being the one given in the URL.

This is what I currently have:

=simple_form_for @post, html: {multipart: true} do |f|
-if @post.errors.any?
    #errors
        %h2
        =pluralize(@post.errors.count, "error")
        prevented this pin from saving
        %ul
            -@post.errors.full_messages.each do |msg|
                %li= msg

.form-group
    =f.input :title, input_html: {class: 'form-control'}

.form-group
    =f.input :content, input_html: {class: 'form-control'}

=f.hidden_field :subreddit_id, :value => @post.subreddit_id

=f.button :submit, class: "btn btn-primary"

I get the following error:

No route matches {:action=>"show", :controller=>"posts", :id=>33, :subreddit_id=>nil} missing required keys: [:subreddit_id]

I think this is because I am trying to access the subreddit id of a post that hasn't been created yet. How do I solve this? Am I going about it in the wrong direction?

Body:
In the new action of the posts_controller, you'll set the @subreddit instance variable

def new
  @subreddit = Subreddit.find(params[:subreddit_id])
  @post = Post.new
end

In the form, you'll need to change the first line

= simple_form_for [@subreddit, @post], html: {multipart: true} do |f|

:subreddit_id will now be in the url


问:
'Pedido_Extra' object has no attribute 'update'
I have problems updating the fields of an object that was saved, first capture the id with ped.id and then pass it to get (id = ped.id) to then do the .update and that is the error, Which is tested in several ways is why I need your help please, thank you in advance!    </p>

```<code>def IngresarExtra(request, id_especialidad, cod_experto):
   especialidad = Especialidad.objects.get(id=id_especialidad)
   articulo = Articulo.objects.get(pk=cod_experto)
   if request.method == 'GET':
      form = ExtraForm()
   else:
      form = ExtraForm(request.POST)
         if form.is_valid():
             ped = form.save()
             ped.id
             ped_ex = Pedido_Extra.objects.get(id=ped.id).update(articulo_ex=articulo)
      ped_ex.save()
  return HttpResponseRedirect('/solicitar/pedidos-extra/')
</code>```

<p>return render(request, 'form2.html', {'form':form, 'especialidad':especialidad, 'articulo':articulo}) </p>

```<code>class Pedido_Extra(models.Model):
    articulo_ex       = models.ForeignKey('Articulo')
    especialidad_ex   = models.ForeignKey('Especialidad')
    fecha_pedido_ex   = models.DateTimeField(auto_now_add=True,null=True, blank=True)
    fecha_entrega_ex  = models.DateTimeField(auto_now_add=False)
    cantidad_ex       = models.IntegerField(blank=True, default=0)
    estado_ex         =  models.CharField(max_length=20, blank=True, default='pendiente')

    def __str__(self):
        return '{}'.format(self.articulo_ex, self.especialidad_ex, self.estado_ex, self.cantidad_ex)
</code>```

答:
From docs:

Sometimes you want to set a field to a particular value for all the objects in a QuerySet. You can do this with the update() method.

You cannot use update() with get(). It is a bulk operation.

You can try following methods:

Call filter() with id and then call update().

Use dot notation to assign new value to attribute of the object and call save().

Use update_or_create().

Body:
I have problems updating the fields of an object that was saved, first capture the id with ped.id and then pass it to get (id = ped.id) to then do the .update and that is the error, Which is tested in several ways is why I need your help please, thank you in advance!

def IngresarExtra(request, id_especialidad, cod_experto):
   especialidad = Especialidad.objects.get(id=id_especialidad)
   articulo = Articulo.objects.get(pk=cod_experto)
   if request.method == 'GET':
      form = ExtraForm()
   else:
      form = ExtraForm(request.POST)
         if form.is_valid():
             ped = form.save()
             ped.id
             ped_ex = Pedido_Extra.objects.get(id=ped.id).update(articulo_ex=articulo)
      ped_ex.save()
  return HttpResponseRedirect('/solicitar/pedidos-extra/')

return render(request, 'form2.html', {'form':form, 'especialidad':especialidad, 'articulo':articulo})

class Pedido_Extra(models.Model):
    articulo_ex       = models.ForeignKey('Articulo')
    especialidad_ex   = models.ForeignKey('Especialidad')
    fecha_pedido_ex   = models.DateTimeField(auto_now_add=True,null=True, blank=True)
    fecha_entrega_ex  = models.DateTimeField(auto_now_add=False)
    cantidad_ex       = models.IntegerField(blank=True, default=0)
    estado_ex         =  models.CharField(max_length=20, blank=True, default='pendiente')

    def __str__(self):
        return '{}'.format(self.articulo_ex, self.especialidad_ex, self.estado_ex, self.cantidad_ex)


问:
Rails: .build() does not seem to instantiate the object - why?
I have the following database/model structure:

```<code>User -< Userorganizations >- Organization -< Organizationlocations >- Location
</code>```

...where -< means: has_many / belongs_to

All of @user.userorganizations.first.organization (including Organization) is persisted (in the database).

Then, in my controller, I call:

```<code>@user.userorganizations.first.organization.organizationlocations.build
@user.userorganizations.first.organization.organizationlocations.first.build_location
</code>```

...and it returns:

```<code>undefined method `build_location' for nil:NilClass
</code>```

...meaning that...

```<code>@user.userorganizations.first.organization.organizationlocations.build
</code>```

...did not instantiate an Organizationlocation.

How can this be?

答:
The build key word does not actually instantiate the object.  As such you cannot do anything that will create a join that associates to the object that you have built until you have persisted the object in the database.

If you want to refer to the build objects you can do the following:

```<code>foo = @user.userorganizations.first.organization.organizationlocations.build

foo.first.build_location
</code>```

The issue remains though that you are calling to the db but build doesn't actually create the records in the DB until you call save.

Body:
I have the following database/model structure:

User -< Userorganizations >- Organization -< Organizationlocations >- Location

...where -< means: has_many / belongs_to

All of @user.userorganizations.first.organization (including Organization) is persisted (in the database).

Then, in my controller, I call:

@user.userorganizations.first.organization.organizationlocations.build
@user.userorganizations.first.organization.organizationlocations.first.build_location

...and it returns:

undefined method `build_location' for nil:NilClass

...meaning that...

@user.userorganizations.first.organization.organizationlocations.build

...did not instantiate an Organizationlocation.

How can this be?

Body:
The build key word does not actually instantiate the object.  As such you cannot do anything that will create a join that associates to the object that you have built until you have persisted the object in the database.

If you want to refer to the build objects you can do the following:

foo = @user.userorganizations.first.organization.organizationlocations.build

foo.first.build_location

The issue remains though that you are calling to the db but build doesn't actually create the records in the DB until you call save.


问:
Wordpress site - using custom PHP and database
I have finally finished coding a project with an HTML form for file upload, and a large PHP file that submits a 200 field CSV into my database. It first uploads to a staging table and then splits the data into smaller tables.

This all works perfectly but I'm having problems with the next step: This is needed to run on a wordpress site that already exists. I have a database just for this project with tables for users, clients, staging, meters, etc. I need all of these tables in their own database because these users are separate from the WP users.

I found a plugin that allows you to insert PHP into pages, but I need to know how to work with a custom database in WP, I've only ever worked with the actual database. Any help is greatly appreciated.

答:
If you want to use php, try this tutorial: https://www.w3schools.com/php/php_ref_mysqli.asp

If you are developing wordpress plugins check out the wordpress codex: https://codex.wordpress.org/Creating_Tables_with_Plugins

This is going to take a bit of research on your part.  Good luck!


问:
Substitution for INTERSECT in phpMyAdmin
I'm trying to use an intersect query on phpMyAdmin but obviously it doesn't supports INTERSECT, at least I'm pretty sure it doesn't. This is the query I'm trying to use, but what is another way I could put it to where I don't use INTERSECT?

```<code>SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer join lginvoice USING (cust_code) WHERE employee_id = 83649
INTERSECT
SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer join lginvoice USING (cust_code) WHERE employee_id = 83677
ORDER BY cust_lname, cust_fname;
</code>```

答:
Use joins instead :</p>

```<code>SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer
join lginvoice l1 on l1.cust_code = lgcustomer.cust_code AND l1.employee_id = 83649
join lginvoice l2 on l2.cust_code = lgcustomer.cust_code AND l2.employee_id = 83677
</code>```

Body:
I'm trying to use an intersect query on phpMyAdmin but obviously it doesn't supports INTERSECT, at least I'm pretty sure it doesn't. This is the query I'm trying to use, but what is another way I could put it to where I don't use INTERSECT?

SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer join lginvoice USING (cust_code) WHERE employee_id = 83649
INTERSECT
SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer join lginvoice USING (cust_code) WHERE employee_id = 83677
ORDER BY cust_lname, cust_fname;

Body:
Use joins instead :

SELECT cust_code, cust_fname, cust_lname
FROM lgcustomer
join lginvoice l1 on l1.cust_code = lgcustomer.cust_code AND l1.employee_id = 83649
join lginvoice l2 on l2.cust_code = lgcustomer.cust_code AND l2.employee_id = 83677


问:
How can hide sensitive info in SQL
I want to do this in SQL server:

If I have a name like 'Johnny English',

how can I show in a query this 'J***** E******'?

Thanks!

答:
Let's assume you have two columns of data here and you want only the first character but the rest of the characters as asterisks. You can do this using REPLICATE.

https://learn.microsoft.com/en-us/sql/t-sql/functions/replicate-transact-sql

```<code>declare @FirstName varchar(20) = 'Johnny'
    , @LastName varchar(20) = 'English'

select left(@FirstName, 1) + replicate('*', len(@FirstName) - 1) + ' ' + left(@LastName, 1) + replicate('*', len(@LastName) - 1)
</code>```

Title: How can hide sensitive info in SQL

Body:
Let's assume you have two columns of data here and you want only the first character but the rest of the characters as asterisks. You can do this using REPLICATE.

https://learn.microsoft.com/en-us/sql/t-sql/functions/replicate-transact-sql

declare @FirstName varchar(20) = 'Johnny'
    , @LastName varchar(20) = 'English'

select left(@FirstName, 1) + replicate('*', len(@FirstName) - 1) + ' ' + left(@LastName, 1) + replicate('*', len(@LastName) - 1)


答: Generally access to clipboard is restricted in JavaScript for security reasons. (esp for browser plugins). So you will have to use third party solutions (like flash) There are some APIs available like exeCommand to hack around it: execCommand </p>

Title: JS: Item List - copy value content to clipboard

Body:
I have a item list (listview), something like this:

<option value="String I want to get copied" title="String I want to get copied">Item1</option>
<option value="String I want to get copied-1" title="String I want to get copied-1">Item2</option>

I need to get copied to clipboard the content of (Please, attention!) Title or Value, but NOT "Item1" or "Item2".

Select an item- Right click-Copy the value or title field to clipboard...

It would be great if it possible to do it via menu right mouse click (I'm making a chrome extension). But any idea where to dig will be much appreciated!


问:
Jquery each and visible - Unknown Pseudoclass or Pseudoelement 'visible'

i have a problem with jquery/visible. Hope somebody can help me.

This code works, but i get an error in firebug

```<code>$('.fse:visible').each(function (i)
</code>```

-> Unknown Pseudoclass or Pseudoelement 'visible'.

second try

```<code>$('.fse').is(':visible').each(function (i)
</code>```

->  $(".fse").is(":visible").each is not a function

Whats wrong?

Thanks in advance!

Peter

答:
I don't think it is an Error but a CSS Warning you are getting and it is normal. Had the same trouble (even appears on the jquery.com website) some time back.

See the discussion here:
http://old.nabble.com/Unknown-pseudo-class-or-pseudo-element-%27odd%27.-td25425663s27240.html

ContentLicense: CC BY-SA 2.5

Body:
i have a problem with jquery/visible. Hope somebody can help me.

This code works, but i get an error in firebug

$('.fse:visible').each(function (i)

-> Unknown Pseudoclass or Pseudoelement 'visible'.

second try

$('.fse').is(':visible').each(function (i)

->  $(".fse").is(":visible").each is not a function

Whats wrong?

Thanks in advance!

Peter


问:
How to authorize 000webhost posts?
I am using curl in php to post data from my local server to a webhost server:

```<code>  $post = array('test' => 'this is a test' );
    $url = "https://my-app.000webhostapp.com";
            $curlSesh = curl_init();
            curl_setopt($curlSesh, CURLOPT_URL, $url);
            curl_setopt($curlSesh, CURLOPT_POST, true);
            curl_setopt($curlSesh, CURLOPT_POSTFIELDS, $post);
            curl_setopt($curlSesh, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($curlSesh);
            curl_close($curlSesh);
            echo "response: ";
            echo $response;
            if ($response == "validate post")echo ' post has been validated';
</code>```

On my 000webhost server, I accept the array sent in $post using file put contents:

```<code>file_put_contents('incomingData.txt', $_POST["test"]. "\n", FILE_APPEND );
</code>```

Surely this means that anyone can send a post request to my webhost server with an array key 'test' and that will be placed in my incomingData.txt file? This is extremely unsecure. Is there a way to make it so only my local server data is accepted, or maybe can I encrypt the data in some way? Thanks.

答:
To clarify, your data is already being encrypted by using https://. There are a plethora of ways to authenticate your traffic, but a simple way would be to add a "private key" in your post statement.

So you could do

```<code>$post = array('key' => 'some private key', 'text' => ... )
</code>```

And on the server check to ensure dirty data isn't getting through

```<code>if ($_POST['key'] != 'the key you made')
  die()
</code>```

Title: How to authorize 000webhost posts?

Body:
I am using curl in php to post data from my local server to a webhost server:

  $post = array('test' => 'this is a test' );
    $url = "https://my-app.000webhostapp.com";
            $curlSesh = curl_init();
            curl_setopt($curlSesh, CURLOPT_URL, $url);
            curl_setopt($curlSesh, CURLOPT_POST, true);
            curl_setopt($curlSesh, CURLOPT_POSTFIELDS, $post);
            curl_setopt($curlSesh, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($curlSesh);
            curl_close($curlSesh);
            echo "response: ";
            echo $response;
            if ($response == "validate post")echo ' post has been validated';

On my 000webhost server, I accept the array sent in $post using file put contents:

file_put_contents('incomingData.txt', $_POST["test"]. "\n", FILE_APPEND );

Surely this means that anyone can send a post request to my webhost server with an array key 'test' and that will be placed in my incomingData.txt file? This is extremely unsecure. Is there a way to make it so only my local server data is accepted, or maybe can I encrypt the data in some way? Thanks.

Body:
To clarify, your data is already being encrypted by using https://. There are a plethora of ways to authenticate your traffic, but a simple way would be to add a "private key" in your post statement.

So you could do

$post = array('key' => 'some private key', 'text' => ... )

And on the server check to ensure dirty data isn't getting through

if ($_POST['key'] != 'the key you made')
  die()


问:
Using the Gson library to parse unknown data dynamically
I want to parse following JSON data in Android Studio using Gson library. But the data is generic..dont know what keys(objects) are come in data..

under school object - there is number 1103 which is object.

and under that object we have shoolname, shortname, students
  again under students - there are id's like 2201, 2202...
  these objects are dynamic dont know what comes in response..

so question is how to parse this json string in android using Gson?

or any other solution for that is welcome

```<code>{
"schools": {
    "home": "1103",
    "statelevel": "1348"
},
"school": {
    "1103": {
        "schoolname": "Indira School",
        "nameshort": "ind",
        "students": {
            "2201": {
                "name": "Ritesh",
                "isCR": true,
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "2202": {
                "name": "Sanket",
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "2203": {
                "name": "Ajit",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    },
    "1348": {
        "schoolname": "Patil School",
        "nameshort": "pat",
        "students": {
            "3201": {
                "name": "Ravi",
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "3202": {
                "name": "Raj",
                "isCR": true,
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "3203": {
                "name": "Ram",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    }
}
</code>```

}

I have refered the How to parse dynamic JSON fields with GSON?.. but not worked in my case..i have inner generic classes too.

I have found the solution here https://stackoverflow.com/a/23473650/7790252.
implements deserializer to model classes like school and students.

答:
You can simply use java.util.Map that is an associative key/value container where keys and values are arbitrary objects, and can align with JSON dynamic objects using Gson really straight-forward. You just have to define appropriate mappings (I made the field collapsed to save some visual space):

final class Response {
    @SerializedName("schools") final HomeSchool school = null;
    @SerializedName("school") final Map<Integer, School> schools = null;
}

final class HomeSchool {
    @SerializedName("home") final int home = Integer.valueOf(0);
    @SerializedName("statelevel") final int stateLevel = Integer.valueOf(0);
}

final class School {
    @SerializedName("schoolname") final String name = null;
    @SerializedName("nameshort") final String shortName = null;
    @SerializedName("students") final Map<Integer, Student> students = null;
}

final class Student {
    @SerializedName("name") final String name = null;
    @SerializedName("isCR") final boolean isCr = Boolean.valueOf(false);
    @SerializedName("maths") final Maths maths = null;
}

final class Maths {
    @SerializedName("score") final int score = Integer.valueOf(0);
    @SerializedName("lastscore") final int lastScore = Integer.valueOf(0);
}
```

<p>Now, once you have the mappings, you can easily deserialize your JSON:</p>

<pre class="lang-java prettyprint-override"><code>private static final Gson gson = new Gson();

public static void main(final String... args) {
    final Response response = gson.fromJson(JSON, Response.class);
    for ( final Entry<Integer, School> schoolEntry : response.schools.entrySet() ) {
        final School school = schoolEntry.getValue();
        System.out.println(schoolEntry.getKey() + " " + school.name);
        for ( final Entry<Integer, Student> studentEntry : school.students.entrySet() ) {
            final Student student = studentEntry.getValue();
            System.out.println("\t" + studentEntry.getKey()
                    + " " + student.name
                    + " CR:" + (student.isCr ? "+" : "-")
                    + " (" + student.maths.score + ", " + student.maths.lastScore + ")"
            );
        }
    }
}
</code>```

1103 Indira School

    2201 Ritesh CR:+ (95, 86)

    2202 Sanket CR:- (98, 90)

    2203 Ajit CR:- (94, 87)

  1348 Patil School

    3201 Ravi CR:- (95, 86)

    3202 Raj CR:+ (98, 90)

    3203 Ram CR:- (94, 87)

The type token suggestions are partially correct: they are used to deserialize the objects you cannot or don't have concrete mappings for, like lists of something, or maps of strings to something. In your case Gson simply analyzes the field declarations to resolve the map types (both keys and values).

Body:
I want to parse following JSON data in Android Studio using Gson library. But the data is generic..dont know what keys(objects) are come in data..

under school object - there is number 1103 which is object.

and under that object we have shoolname, shortname, students
  again under students - there are id's like 2201, 2202...
  these objects are dynamic dont know what comes in response..

so question is how to parse this json string in android using Gson?

or any other solution for that is welcome

{
"schools": {
    "home": "1103",
    "statelevel": "1348"
},
"school": {
    "1103": {
        "schoolname": "Indira School",
        "nameshort": "ind",
        "students": {
            "2201": {
                "name": "Ritesh",
                "isCR": true,
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "2202": {
                "name": "Sanket",
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "2203": {
                "name": "Ajit",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    },
    "1348": {
        "schoolname": "Patil School",
        "nameshort": "pat",
        "students": {
            "3201": {
                "name": "Ravi",
                "maths": {
                    "score": 95,
                    "lastscore": 86
                }
            },
            "3202": {
                "name": "Raj",
                "isCR": true,
                "maths": {
                    "score": 98,
                    "lastscore": 90
                }
            },
            "3203": {
                "name": "Ram",
                "maths": {
                    "score": 94,
                    "lastscore": 87
                }
            }
        }
    }
}

}

I have refered the How to parse dynamic JSON fields with GSON?.. but not worked in my case..i have inner generic classes too.

I have found the solution here https://stackoverflow.com/a/23473650/7790252.
implements deserializer to model classes like school and students.

Body:
You can simply use java.util.Map that is an associative key/value container where keys and values are arbitrary objects, and can align with JSON dynamic objects using Gson really straight-forward. You just have to define appropriate mappings (I made the field collapsed to save some visual space):

final class Response {
    @SerializedName("schools") final HomeSchool school = null;
    @SerializedName("school") final Map<Integer, School> schools = null;
}

final class HomeSchool {
    @SerializedName("home") final int home = Integer.valueOf(0);
    @SerializedName("statelevel") final int stateLevel = Integer.valueOf(0);
}

final class School {
    @SerializedName("schoolname") final String name = null;
    @SerializedName("nameshort") final String shortName = null;
    @SerializedName("students") final Map<Integer, Student> students = null;
}

final class Student {
    @SerializedName("name") final String name = null;
    @SerializedName("isCR") final boolean isCr = Boolean.valueOf(false);
    @SerializedName("maths") final Maths maths = null;
}

final class Maths {
    @SerializedName("score") final int score = Integer.valueOf(0);
    @SerializedName("lastscore") final int lastScore = Integer.valueOf(0);
}

Now, once you have the mappings, you can easily deserialize your JSON:

private static final Gson gson = new Gson();

public static void main(final String... args) {
    final Response response = gson.fromJson(JSON, Response.class);
    for ( final Entry<Integer, School> schoolEntry : response.schools.entrySet() ) {
        final School school = schoolEntry.getValue();
        System.out.println(schoolEntry.getKey() + " " + school.name);
        for ( final Entry<Integer, Student> studentEntry : school.students.entrySet() ) {
            final Student student = studentEntry.getValue();
            System.out.println("\t" + studentEntry.getKey()
                    + " " + student.name
                    + " CR:" + (student.isCr ? "+" : "-")
                    + " (" + student.maths.score + ", " + student.maths.lastScore + ")"
            );
        }
    }
}

1103 Indira School

    2201 Ritesh CR:+ (95, 86)

    2202 Sanket CR:- (98, 90)

    2203 Ajit CR:- (94, 87)

  1348 Patil School

    3201 Ravi CR:- (95, 86)

    3202 Raj CR:+ (98, 90)

    3203 Ram CR:- (94, 87)

The type token suggestions are partially correct: they are used to deserialize the objects you cannot or don't have concrete mappings for, like lists of something, or maps of strings to something. In your case Gson simply analyzes the field declarations to resolve the map types (both keys and values).


问:
Access Ubuntu Server VM on Azure
I've setup an Ubuntu Server on Azure. On this server, an application is running on port 3000. I want to access this application external. Azure tells me my server has public ip 40.68.XXX.XXX.

When I ping this IP, there is no response, despite ssh works when connecting to this IP-address.

I want to access 40.68.XXX.XXX:3000 external, does somebody know how to get this work?

答:
Yes, you need to open up a port on the Network Security Group (NSG) and open up the port on your firewall (on the VM itself).

Easiest way to open the port is using the portal:

https://learn.microsoft.com/en-us/azure/virtual-machines/virtual-machines-windows-nsg-quickstart-portal

Title: Access Ubuntu Server VM on Azure


问:
Downloading data using Github
Complete novice in this. All I want to do is extract these files into any .csv or .xls or similar format.

committee-membership-current.yaml

from https://github.com/unitedstates/congress-legislators/commit/e008a100629110f3ec6ccf1a30a9003ff285aaad#diff-5a41af9d9d109ba2feb0d5b2bc7c3573

&

https://github.com/unitedstates/congress-legislators

I see alot of code, where do I plug it in an run!? ha ha , you see I told you I was novice .

Surely theres gotta be a way one can press a button on that site to extract the information the code is relaying?

Or do I need an add-on on my browser to stick the code in to, and run myself and from where I will be able to edit it for Publically available repositories of data like this?

Any advice or information will be appreciated!

答:
If you need to get few files, you can do that manually converting yaml to csv.

Particularly for your case file committee-membership-current.yaml is located by the target URL

https://raw.githubusercontent.com/unitedstates/congress-legislators/master/committee-membership-current.yaml

Then just open any online converter, e. g. this one http://convertcsv.com/yaml-to-csv.htm, paste the target URL,  save it as csv file, and open with Excel.

This question belongs to Super User in the first place.

Title: Downloading data using Github


问:
Protractor: Stale Element reference with using conditions
I have a piece of code which is try to see if a text is not present in an element

```<code>browser.wait(protractor.ExpectedConditions.not(protractor.ExpectedConditions.textToBePresentInElement(self.btnDashboards(),dashboardName)));
</code>```

where

```<code>self.btnDashboards = function() {
    return element(this.selectors.btnDashboards);
};
var dashboardName = 'foo';
</code>```

However this occasionally returns

```    Fatal error: 09:54:11.129 WARN - Exception thrown
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
  (Session info: chrome=44.0.2403.155)
  (Driver info: chromedriver=2.15.322455 (ae8db840dac8d0c453355d3d922c91adfb61df8f),platform=Mac OS X 10.10.4 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 182 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.45.0', revision: '5017cb8', time: '2015-02-26 23:59:50'
System info: host: 'Sujits-MacBook-Pro.local', ip: '10.80.132.90', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.10.4', java.version: '1.8.0_51'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, chrome={userDataDir=/var/folders/tc/89n0t1qs5p3fyw_n9hk1x7fc0000gn/T/.org.chromium.Chromium.QSwwCm}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, version=44.0.2403.155, platform=MAC, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: bbd4b5004df6ff3855bccacf8d16e8c0
    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:422)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
    at org.openqa.selenium.remote.RemoteWebElement.getText(RemoteWebElement.java:152)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.openqa.selenium.support.events.EventFiringWebDriver$EventFiringWebElement$1.invoke(EventFiringWebDriver.java:331)
    at com.sun.proxy.$Proxy2.getText(Unknown Source)
    at org.openqa.selenium.support.events.EventFiringWebDriver$EventFiringWebElement.getText(EventFiringWebDriver.java:381)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.openqa.selenium.remote.server.KnownElements$1.invoke(KnownElements.java:63)
    at com.sun.proxy.$Proxy3.getText(Unknown Source)
    at org.openqa.selenium.remote.server.handler.GetElementText.call(GetElementText.java:29)
    at org.openqa.selenium.remote.server.handler.GetElementText.call(GetElementText.java:1)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:168)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
```

Is there a better way to code this so that it doesn't happen at all? Also Why is this happening occasionally rather than regularly?

答:
Because browser.wait returns a promise you can use the .then({passed function}, {failed function}) to trap the error and try again.  Here's what I used.</p>

```<code>browser.prototype.wait2 = function (waitFunction, timeout, timeoutMessage) {
  var self = this;
  return browser.wait(waitFunction, timeout, timeoutMessage).then(function(pass){return pass}, function(error){
    //retry if the error is a stale element, half the timeout
    if(error.name == "StaleElementReferenceError") {
      return self.wait2(waitFunction, timeout/2, timeoutMessage);
    } else {
      throw error;
    }
  });
};
</code>```

Body:
I have a piece of code which is try to see if a text is not present in an element

browser.wait(protractor.ExpectedConditions.not(protractor.ExpectedConditions.textToBePresentInElement(self.btnDashboards(),dashboardName)));

where

self.btnDashboards = function() {
    return element(this.selectors.btnDashboards);
};
var dashboardName = 'foo';

However this occasionally returns

    Fatal error: 09:54:11.129 WARN - Exception thrown
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
  (Session info: chrome=44.0.2403.155)
  (Driver info: chromedriver=2.15.322455 (ae8db840dac8d0c453355d3d922c91adfb61df8f),platform=Mac OS X 10.10.4 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 182 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.45.0', revision: '5017cb8', time: '2015-02-26 23:59:50'
System info: host: 'Sujits-MacBook-Pro.local', ip: '10.80.132.90', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.10.4', java.version: '1.8.0_51'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, chrome={userDataDir=/var/folders/tc/89n0t1qs5p3fyw_n9hk1x7fc0000gn/T/.org.chromium.Chromium.QSwwCm}, takesHeapSnapshot=true, databaseEnabled=false, handlesAlerts=true, version=44.0.2403.155, platform=MAC, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: bbd4b5004df6ff3855bccacf8d16e8c0
    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:422)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
    at org.openqa.selenium.remote.RemoteWebElement.getText(RemoteWebElement.java:152)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.openqa.selenium.support.events.EventFiringWebDriver$EventFiringWebElement$1.invoke(EventFiringWebDriver.java:331)
    at com.sun.proxy.$Proxy2.getText(Unknown Source)
    at org.openqa.selenium.support.events.EventFiringWebDriver$EventFiringWebElement.getText(EventFiringWebDriver.java:381)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.openqa.selenium.remote.server.KnownElements$1.invoke(KnownElements.java:63)
    at com.sun.proxy.$Proxy3.getText(Unknown Source)
    at org.openqa.selenium.remote.server.handler.GetElementText.call(GetElementText.java:29)
    at org.openqa.selenium.remote.server.handler.GetElementText.call(GetElementText.java:1)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:168)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Is there a better way to code this so that it doesn't happen at all? Also Why is this happening occasionally rather than regularly?

Body:
Because browser.wait returns a promise you can use the .then({passed function}, {failed function}) to trap the error and try again.  Here's what I used.

browser.prototype.wait2 = function (waitFunction, timeout, timeoutMessage) {
  var self = this;
  return browser.wait(waitFunction, timeout, timeoutMessage).then(function(pass){return pass}, function(error){
    //retry if the error is a stale element, half the timeout
    if(error.name == "StaleElementReferenceError") {
      return self.wait2(waitFunction, timeout/2, timeoutMessage);
    } else {
      throw error;
    }
  });
};


问:
How to display just the group name of groups user is member of in powershell
So I have the following script but it lists the full name of the AD group. (e.g. CN=GroupName,OU=OUName,DC=DomainName,DC=com) How do I specify only the group's name, so that it lists only the name itself. The part after CN=. I tried $group.Name but no such luck.

```<code>Import-Module ActiveDirectory
$userlist = Get-Content "C:\Scripts\US_User_List.txt"

foreach ($username in $userlist) {
    $grplist = (Get-ADUser $username –Properties MemberOf | Select-Object MemberOf).MemberOf
    foreach ($group in $grplist) {
        write-host $group
    }
}
</code>```

Also as a second question is there some way to filter based on what the group name starts with?

答:
Here's one way:

```<code>foreach ( $name in $names ) {
  Get-ADUser $name -Properties memberOf |
    Select-Object -ExpandProperty memberOf |
    Get-ADPathname -Format Leaf -ValuesOnly |
    Where-Object { ($_ -like "this*") -or ($_ -like "that*") } |
    Sort-Object |
    ForEach-Object {
      [PSCustomObject] @{
        "Name" = $name
        "memberOf" = $_
      }
    }
}
</code>```

You can adjust the filter in the Where-Object scriptblock how you want it.

You can get the Get-ADPathname.ps1 script from here:

Windows IT Pro - Use PowerShell to Handle Active Directory Paths

A note on the Where-Object filter - if you want to say "groups whose names do not start with this or that", you would write it this way:

```<code>Where-Object { -not (($_ -like "this*") -or ($_ -like "that*")) }
</code>```

Body:
So I have the following script but it lists the full name of the AD group. (e.g. CN=GroupName,OU=OUName,DC=DomainName,DC=com) How do I specify only the group's name, so that it lists only the name itself. The part after CN=. I tried $group.Name but no such luck.

Import-Module ActiveDirectory
$userlist = Get-Content "C:\Scripts\US_User_List.txt"

foreach ($username in $userlist) {
    $grplist = (Get-ADUser $username –Properties MemberOf | Select-Object MemberOf).MemberOf
    foreach ($group in $grplist) {
        write-host $group
    }
}

Also as a second question is there some way to filter based on what the group name starts with?

Body:
Here's one way:

foreach ( $name in $names ) {
  Get-ADUser $name -Properties memberOf |
    Select-Object -ExpandProperty memberOf |
    Get-ADPathname -Format Leaf -ValuesOnly |
    Where-Object { ($_ -like "this*") -or ($_ -like "that*") } |
    Sort-Object |
    ForEach-Object {
      [PSCustomObject] @{
        "Name" = $name
        "memberOf" = $_
      }
    }
}

You can adjust the filter in the Where-Object scriptblock how you want it.

You can get the Get-ADPathname.ps1 script from here:

Windows IT Pro - Use PowerShell to Handle Active Directory Paths

A note on the Where-Object filter - if you want to say "groups whose names do not start with this or that", you would write it this way:

Where-Object { -not (($_ -like "this*") -or ($_ -like "that*")) }


问:
overload resolution failed because no accessible 'DataBind' is most specific for these arguments
I am getting this error 'overload resolution failed because no accessible 'DataBind' is most specific for these arguments' below is the code I am using.

```<code>    Private Overloads Sub DataBind(ByVal iPageIndex As Integer)
     //do some thing
    End Sub

    Protected Overridable Sub DataBind(raiseondatabinding as Boolean)
        //Do some thibg
    End Sub

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSearch.Click
            DataBind(Nothing) //this is where I am getting error
    End Sub
</code>```

Any help would be appropriated.

Thanks,

Pradeep

答:
It doesn't know which version of DataBind you're trying to use, because Nothing is convertible to both Boolean and Integer. You could either use a variable for this:

```<code>Private Sub btnSearch_Click(ByVal sender As Object, _
                            ByVal e As ImageClickEventArgs) _
                            Handles btnSearch.Click
    Dim x As Integer = Nothing
    DataBind(x)
End Sub
</code>```

or just specify 0 or False as the argument:

```<code>Private Sub btnSearch_Click(ByVal sender As Object, _
                            ByVal e As ImageClickEventArgs) _
                            Handles btnSearch.Click
    DataBind(False)
End Sub
</code>```

Adjust depending on which version you actually wanted to call. Like the compiler, I can't tell what you intended :)

Body:
I am getting this error 'overload resolution failed because no accessible 'DataBind' is most specific for these arguments' below is the code I am using.

    Private Overloads Sub DataBind(ByVal iPageIndex As Integer)
     //do some thing
    End Sub

    Protected Overridable Sub DataBind(raiseondatabinding as Boolean)
        //Do some thibg
    End Sub

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSearch.Click
            DataBind(Nothing) //this is where I am getting error
    End Sub

Any help would be appropriated.

Thanks,

Pradeep

Body:
It doesn't know which version of DataBind you're trying to use, because Nothing is convertible to both Boolean and Integer. You could either use a variable for this:

Private Sub btnSearch_Click(ByVal sender As Object, _
                            ByVal e As ImageClickEventArgs) _
                            Handles btnSearch.Click
    Dim x As Integer = Nothing
    DataBind(x)
End Sub

or just specify 0 or False as the argument:

Private Sub btnSearch_Click(ByVal sender As Object, _
                            ByVal e As ImageClickEventArgs) _
                            Handles btnSearch.Click
    DataBind(False)
End Sub

Adjust depending on which version you actually wanted to call. Like the compiler, I can't tell what you intended :)


问:
Can you use math calculations on two alias columns in MySQL?
I want to do this:

```<code>SELECT SUM(currentbalance) AS 'current', SUM(principal) AS 'prin', 'current' + 'prin' AS 'total'
FROM dbase
</code>```

This doesn't work. I've also tried:

```<code>SELECT sum(currentbalance) AS 'current', sum(principal) AS 'prin', (SELECT 'current') + (SELECT 'prin') AS 'total'
FROM dbase
</code>```

@juergen-d @fqhv

Both answers worked perfectly. I thought that would be enough for me to understand how to add it to my current query. How can I implement this inside this query? I need to divide the "file_principal" by the "total_cash_cleared"? Thanks in Advance.

```<code>SELECT a.portfolio
       ,a.dateplaced
       ,(SELECT SUM(chargedoffprincipal) FROM Dbase WHERE portfolio = a.portfolio ) AS 'file_principal'
       ,SUM(IF(b.paymentstatus IN ('POSTED','PROCCESED'), paymentamount, 0)) AS 'total_cash_cleared'
       ,SUM(IF(b.paymentstatus = 'PENDING', paymentamount, 0)) AS 'total_cash_pending'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 1 MONTH),paymentamount, 0)) AS '30_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 2 MONTH),paymentamount, 0)) AS '60_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 3 MONTH),paymentamount, 0)) AS '90_days'
FROM dbase a
LEFT JOIN payments b
ON a.filenumber = b.filenumber
GROUP BY a.portfolio
ORDER BY STR_TO_DATE(a.dateplaced, '%m/%d/%Y') DESC
</code>```

I tried to add this in a comment but it was too long so I edited this post sorry.

答:
I like juergen's answer better, but you could add using aliases if you put it in a subquery.</p>

```<code>SELECT [current] + [prin]
FROM (
    SELECT
      SUM(currentbalance) AS 'current',
      SUM(principal) AS 'prin'
    FROM dbase ) x
</code>```

Body:
I want to do this:

SELECT SUM(currentbalance) AS 'current', SUM(principal) AS 'prin', 'current' + 'prin' AS 'total'
FROM dbase

This doesn't work. I've also tried:

SELECT sum(currentbalance) AS 'current', sum(principal) AS 'prin', (SELECT 'current') + (SELECT 'prin') AS 'total'
FROM dbase

@juergen-d @fqhv

Both answers worked perfectly. I thought that would be enough for me to understand how to add it to my current query. How can I implement this inside this query? I need to divide the "file_principal" by the "total_cash_cleared"? Thanks in Advance.

SELECT a.portfolio
       ,a.dateplaced
       ,(SELECT SUM(chargedoffprincipal) FROM Dbase WHERE portfolio = a.portfolio ) AS 'file_principal'
       ,SUM(IF(b.paymentstatus IN ('POSTED','PROCCESED'), paymentamount, 0)) AS 'total_cash_cleared'
       ,SUM(IF(b.paymentstatus = 'PENDING', paymentamount, 0)) AS 'total_cash_pending'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 1 MONTH),paymentamount, 0)) AS '30_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 2 MONTH),paymentamount, 0)) AS '60_days'
       ,SUM(IF(b.paymentstatus = 'PENDING' AND YEAR(paymentdate) = YEAR(CURRENT_DATE + INTERVAL 1 MONTH) AND MONTH(paymentdate) = MONTH(CURRENT_DATE + INTERVAL 3 MONTH),paymentamount, 0)) AS '90_days'
FROM dbase a
LEFT JOIN payments b
ON a.filenumber = b.filenumber
GROUP BY a.portfolio
ORDER BY STR_TO_DATE(a.dateplaced, '%m/%d/%Y') DESC

I tried to add this in a comment but it was too long so I edited this post sorry.

Body:
I like juergen's answer better, but you could add using aliases if you put it in a subquery.

SELECT [current] + [prin]
FROM (
    SELECT
      SUM(currentbalance) AS 'current',
      SUM(principal) AS 'prin'
    FROM dbase ) x


问:
How to update payment method in Zuora using PHP
Can you help me on how to update payment method in Zuora using PHP? I have this sample JSON code below.

PUT https://api.zuora.com/rest/v1/accounts/{account-key}

JSON Request
{
  "paymentGateway" : "TestGateway"
}

Thanks

答:
If you are updating a payment method on an Account you can issue an update REST call using this endpoint : https://www.zuora.com/developer/api-reference/#operation/Object_PUTAccount

You will need the Account ID and the existing PaymentMethod ID

In your op, you referenced a Gateway, are you trying to update the PaymentMethod? or the Gateway?

If you're updating the Gateway, you can update the PaymentGateway field, using the same endpoint


问:
Keep application from crashing when phone sleep/locked
Hi guys as the title says I am trying to keep my application alive so to speak when the phone locks.

In detail my app would be open and running fine if I leave my phone alone for a while and unlock it my application is frozen and can't do anything. Now this only happens on some devices for some weird reason but I am wondering is there a way to manage these kind of things?

Thanks

答:
I have been trying to overcome this kind of issue in a few apps as well.  My research points me here: Android - Activity Lifecycle as it states this:

However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the instance state and is a collection of key-value pairs stored in a Bundle object.

So, we need to be leveraging the savedInstanceState Bundle for cleanly packing and unpacking each Activity and Fragment.

I'll work on an example for you ASAP.