问:
How do I pass an image view and its properties from one view controller to another?
So I have an image view in one viewcontroller.swift file that generates a random background image every time the a question is asked (it's a quiz app). When the user get's the answer right I want the random background image produced from the first view controller when the question is asked to be the same background image for the next view controller that displays when the answer is answered correctly. How do I make sure the both background image views displays the same random image every time a question is correctly answered? Here is a snippet of my code that deals with the background image.

```<code>class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = //array containing all the images

//random image generator function
func randomImage() {
    index = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[index]
}
</code>```

Now if I wanted an image view to always display the same background images produced by the randomImage function in a different class (class SecondViewController: UIViewController) for example what would be the best way to get the data from the original view controller? (If you click the right answer button according to the question it proceeds to a new "right answer" view controller that I want to have the same background image as the previous view controller).

答:
First you have to store the background image index that you will set in func randomImage(). So you have to declare a class variable

```<code>class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!
let randomIndex:Int!
let backgroundImages = //array containing all the images

//random image generator function
func randomImage() {
    // So now you can pass this value to next viewController.
    randomIndex = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[randomIndex]

}
</code>```

Body:
So I have an image view in one viewcontroller.swift file that generates a random background image every time the a question is asked (it's a quiz app). When the user get's the answer right I want the random background image produced from the first view controller when the question is asked to be the same background image for the next view controller that displays when the answer is answered correctly. How do I make sure the both background image views displays the same random image every time a question is correctly answered? Here is a snippet of my code that deals with the background image.

class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = //array containing all the images

//random image generator function
func randomImage() {
    index = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[index]
}

Now if I wanted an image view to always display the same background images produced by the randomImage function in a different class (class SecondViewController: UIViewController) for example what would be the best way to get the data from the original view controller? (If you click the right answer button according to the question it proceeds to a new "right answer" view controller that I want to have the same background image as the previous view controller).

Body:
First you have to store the background image index that you will set in func randomImage(). So you have to declare a class variable

class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!
let randomIndex:Int!
let backgroundImages = //array containing all the images

//random image generator function
func randomImage() {
    // So now you can pass this value to next viewController.
    randomIndex = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[randomIndex]

}


来源: stackexchange

问:
How do I pass credentials to Sonar API calls?
When I try to call:

https://sonar.mydomain.com/api/resources?resource=com.mydomain.project:MY&metrics=ncloc&format=json

I get

```<code>{"err_code":401,"err_msg":"Unauthorized"}
</code>```

How do I pass my credentials?

答:
According to the newest documentation said: SonarQube now support two way authentication:

User Token

This is the recommended way. Token is sent via the login field of HTTP basic authentication, this way will be more safety, without any password. For more information about how to generate a token, please visit this page User Token. Use curl send request like this:

```<code>curl -u THIS_IS_MY_TOKEN: https://sonarqube.com/api/user_tokens/search
# note that the colon after the token is required in curl to set an empty password
</code>```

HTTP Basic Access

Login and password are sent via the standard HTTP Basic fields:

```<code>curl -u MY_LOGIN:MY_PASSWORD https://sonarqube.com/api/user_tokens/search
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I try to call:

https://sonar.mydomain.com/api/resources?resource=com.mydomain.project:MY&metrics=ncloc&format=json

I get

{"err_code":401,"err_msg":"Unauthorized"}

How do I pass my credentials?

Body:
According to the newest documentation said: SonarQube now support two way authentication:

User Token

This is the recommended way. Token is sent via the login field of HTTP basic authentication, this way will be more safety, without any password. For more information about how to generate a token, please visit this page User Token. Use curl send request like this:

curl -u THIS_IS_MY_TOKEN: https://sonarqube.com/api/user_tokens/search
# note that the colon after the token is required in curl to set an empty password

HTTP Basic Access

Login and password are sent via the standard HTTP Basic fields:

curl -u MY_LOGIN:MY_PASSWORD https://sonarqube.com/api/user_tokens/search


问:
JQuery - Check if each dynamically added button clicked
I have buttons being added to an element via JQuery Ajax and a PHP script.  The number of buttons being added is variable.  I want to be able to check if each button has been clicked before enabling another action.

The relevant code in the PHP script is as follows with each button having an incremented ID:

```<code>$i = 1;
while ($row = mysql_fetch_array($result)) {
echo "<div class='dr_feedback_btn' id='dr_" . $i++ . "'>Feedback</div>";
}
</code>```

I have the following code in JQuery for the button click based on the button class:

```<code>    $('#dr_container').on('click', '.dr_feedback_btn', function() {
         ...
    });
</code>```

The image below shows the feedback buttons.

Any help appreciated.

答:
You need a way to store the information of whether or not a button has been clicked before and then on that final click, know to trigger the display of some other thing. You can store that data in many different ways. One is to use jquery's data attribute:

```<code>$('#dr_container').on('click', '.dr_feedback_btn', function() {
    $(this).data('clicked', true)
    var buttons = $('.dr_feedback_btn')
    var clickedButtons= buttons.filter(isClicked)
    if (clickedButtons.length === buttons.length) {
        // do your magic here
    }
});

function isClicked(idx, el) {
    return $(el).data('clicked') === true
}
</code>```

You can also rely more on selectors and use html's actual data attributes:

```<code>$('#dr_container').on('click', '.dr_feedback_btn', function() {
    $(this).attr('data-clicked', 'true')
    var buttons = $('.dr_feedback_btn')
    var clickedButtons= $('dr_feedback_btn[data-clicked=true]')
    if (clickedButtons.length === buttons.length) {
        // do your magic here
    }
});
</code>```

Body:
I have buttons being added to an element via JQuery Ajax and a PHP script.  The number of buttons being added is variable.  I want to be able to check if each button has been clicked before enabling another action.

The relevant code in the PHP script is as follows with each button having an incremented ID:

$i = 1;
while ($row = mysql_fetch_array($result)) {
echo "
Feedback
";
}

I have the following code in JQuery for the button click based on the button class:

    $('#dr_container').on('click', '.dr_feedback_btn', function() {
         ...
    });

The image below shows the feedback buttons.

Any help appreciated.

Body:
You need a way to store the information of whether or not a button has been clicked before and then on that final click, know to trigger the display of some other thing. You can store that data in many different ways. One is to use jquery's data attribute:

$('#dr_container').on('click', '.dr_feedback_btn', function() {
    $(this).data('clicked', true)
    var buttons = $('.dr_feedback_btn')
    var clickedButtons= buttons.filter(isClicked)
    if (clickedButtons.length === buttons.length) {
        // do your magic here
    }
});

function isClicked(idx, el) {
    return $(el).data('clicked') === true
}

You can also rely more on selectors and use html's actual data attributes:

$('#dr_container').on('click', '.dr_feedback_btn', function() {
    $(this).attr('data-clicked', 'true')
    var buttons = $('.dr_feedback_btn')
    var clickedButtons= $('dr_feedback_btn[data-clicked=true]')
    if (clickedButtons.length === buttons.length) {
        // do your magic here
    }
});


问:
Why won't form.submit() trigger the "submit" event?
I am submitting my form by using JavaScript .submit() function.

```<code>form.submit();
</code>```

But when I using addEventListener to capture my submit event, it wouldn't work.

```<code>form.addEventListener("submit", function(event){
    //codes
});
</code>```

I found out addEvenetListener function will only listen for onsubmit event instead of submit. Is there have any alternative solution to call my function when form.submit() is executed?

ps: For some reasons I need to stay with form.submit() to submit my form instead of using submit button.

答:
According to MDN:

The form's onsubmit event handler (for example, onsubmit="return false;") will not be triggered when invoking this method from Gecko-based applications. In general, it is not guaranteed to be invoked by HTML user agents.

To get around this issue, try using dispatchEvent():

var form = document.querySelector('form');

form.addEventListener('submit', function () {
  console.log('invoked');

  return false;
});

// form.submit();
form.dispatchEvent(new Event('submit'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form></form></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am submitting my form by using JavaScript .submit() function.

form.submit();

But when I using addEventListener to capture my submit event, it wouldn't work.

form.addEventListener("submit", function(event){
    //codes
});

I found out addEvenetListener function will only listen for onsubmit event instead of submit. Is there have any alternative solution to call my function when form.submit() is executed?

ps: For some reasons I need to stay with form.submit() to submit my form instead of using submit button.

Body:
According to MDN:

The form's onsubmit event handler (for example, onsubmit="return false;") will not be triggered when invoking this method from Gecko-based applications. In general, it is not guaranteed to be invoked by HTML user agents.

To get around this issue, try using dispatchEvent():

var form = document.querySelector('form');

form.addEventListener('submit', function () {
  console.log('invoked');

  return false;
});

// form.submit();
form.dispatchEvent(new Event('submit'));

<form></form>


问:
com.google.firebase.database.DatabaseException: Serializing Arrays is not supported, please use Lists instead
I am trying to persist a custom object using the following code:

```<code>DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference curWorkoutExercisesRef = databaseReference.child("workouts")
            .child(mCurrentWorkout.getId())
            .child("workoutExercises");

WorkoutExercise we = new WorkoutExercise(exercise);
curWorkoutExercisesRef.push().setValue(we);
</code>```

Here's my object:

```<code>public class WorkoutExercise {

    private String id;
    private Exercise exercise;

    public WorkoutExercise() {}

    // getters, setters, other methods
    // ...
}

public class Exercise {

    private String id;
    private String title;

    private List<BodyPart> bodyParts;

    public Exercise() {}

    // getters, setters, other methods
    // ...
}

public class BodyPart {

    private String id;
    private String name;

    public BodyPart() {}

    // getters, setters, other methods
    // ...
}
</code>```

And every time I am getting this error - com.google.firebase.database.DatabaseException: Serializing Arrays is not supported, please use Lists instead. My objects don't contain any arrays so this error looks quite confusing. I found a way to fix this error - everything works fine if I add the @Exclude annotation to the bodyParts list from my Exercise class but it is obviously not what I am trying to achieve.

So seems that Firebase is unable to persist objects containing inner lists? Are there any straightforward workarounds or best practices here? Thanks!

P.S. I am using firebase-database:9.2.1

答:
Add @Exclude to the functions that FB tries to interpret, like those that return a Drawable.</p>

```<code>@Exclude
public Drawable getUnitColorImage(){
    return TextDrawable.builder().buildRound("", prefColor);
}
</code>```

Body:
I am trying to persist a custom object using the following code:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference curWorkoutExercisesRef = databaseReference.child("workouts")
            .child(mCurrentWorkout.getId())
            .child("workoutExercises");

WorkoutExercise we = new WorkoutExercise(exercise);
curWorkoutExercisesRef.push().setValue(we);

Here's my object:

public class WorkoutExercise {

    private String id;
    private Exercise exercise;

    public WorkoutExercise() {}

    // getters, setters, other methods
    // ...
}

public class Exercise {

    private String id;
    private String title;

    private List<BodyPart> bodyParts;

    public Exercise() {}

    // getters, setters, other methods
    // ...
}

public class BodyPart {

    private String id;
    private String name;

    public BodyPart() {}

    // getters, setters, other methods
    // ...
}

And every time I am getting this error - com.google.firebase.database.DatabaseException: Serializing Arrays is not supported, please use Lists instead. My objects don't contain any arrays so this error looks quite confusing. I found a way to fix this error - everything works fine if I add the @Exclude annotation to the bodyParts list from my Exercise class but it is obviously not what I am trying to achieve.

So seems that Firebase is unable to persist objects containing inner lists? Are there any straightforward workarounds or best practices here? Thanks!

P.S. I am using firebase-database:9.2.1

Body:
Add @Exclude to the functions that FB tries to interpret, like those that return a Drawable.

@Exclude
public Drawable getUnitColorImage(){
    return TextDrawable.builder().buildRound("", prefColor);
}


答:
Since you tagged this as pandas, you might want to do it using DataFrame's groupby() functionality. You'd create a DataFrame from your original array

```<code>import pandas as pd
df = pd.DataFrame(x)
</code>```

and group by the first column; then you can iterate over the resulting GroupBy object to get the groups of the frame which have all the same result in the first column.

```<code>{key: group for key, group in df.groupby(0)}
</code>```

Of course, in this snippet group includes the first column. You can strip it out using indexing:

```<code>{key: group.iloc[:,1:] for key, group in df.groupby(0)}
</code>```

and if you would like to convert the sub-frames back into Numpy arrays, use group.iloc[:,1:].values instead. (If you want them as lists of lists, as indicated in your question, it shouldn't be hard to write a function to make that conversion, but it'll probably be more efficient to keep it in Pandas or at least Numpy if you can.)

An alternative is to use the OG groupby() from itertools which lets you avoid Pandas (if you have some reason for doing so) and use a plain old iterative approach.

```<code>import itertools as it
{key: list(map(list, group))
    for key, group in it.groupby(x, lambda row: row[0])}
</code>```

This, again, includes the key in the resulting rows, but you can trim it out using indexing

```<code>{key: list(map(lambda a: list(a)[1:], group))
    for key, group in it.groupby(x, lambda row: row[0])}
</code>```

You can make the code a tad cleaner by using the groupby_transform() function from the more-itertools module (which is not included in the standard Python library):

```<code>import more_itertools as mt
{key: list(group) for key, group in mt.groupby_transform(
    x, lambda row: row[0], lambda row: list(row[1:])
)}
</code>```

Disclosure: I contributed the groupby_transform() function to more-itertools

Title: Python: How to bin a set of data by a repeated value in one column

Body:
Say, I have a numpy array like this:

import numpy as np

x= np.array(
    [[100, 14, 12, 15],
    [100, 21, 16, 11],
    [100, 19, 10, 13],
    [160, 24, 15, 12],
    [160, 43, 12, 65],
    [160, 17, 53, 23],
    [300, 15, 17, 11],
    [300, 66, 23, 12],
    [300, 44, 70, 19]])

The original array is much bigger, so my question is if there's a way to bin or group rows based on the value on column 1?
for example:

{'100': [[14, 12, 15], [21, 16, 11], [19, 10, 13]],
,'160': [[24, 15, 12], [43, 12, 65], [17, 53, 23]],
,'300': [[15, 17, 11], [66, 23, 12], [44, 70, 19]]}

Body:
Since you tagged this as pandas, you might want to do it using DataFrame's groupby() functionality. You'd create a DataFrame from your original array

import pandas as pd
df = pd.DataFrame(x)

and group by the first column; then you can iterate over the resulting GroupBy object to get the groups of the frame which have all the same result in the first column.

{key: group for key, group in df.groupby(0)}

Of course, in this snippet group includes the first column. You can strip it out using indexing:

{key: group.iloc[:,1:] for key, group in df.groupby(0)}

and if you would like to convert the sub-frames back into Numpy arrays, use group.iloc[:,1:].values instead. (If you want them as lists of lists, as indicated in your question, it shouldn't be hard to write a function to make that conversion, but it'll probably be more efficient to keep it in Pandas or at least Numpy if you can.)

An alternative is to use the OG groupby() from itertools which lets you avoid Pandas (if you have some reason for doing so) and use a plain old iterative approach.

import itertools as it
{key: list(map(list, group))
    for key, group in it.groupby(x, lambda row: row[0])}

This, again, includes the key in the resulting rows, but you can trim it out using indexing

{key: list(map(lambda a: list(a)[1:], group))
    for key, group in it.groupby(x, lambda row: row[0])}

You can make the code a tad cleaner by using the groupby_transform() function from the more-itertools module (which is not included in the standard Python library):

import more_itertools as mt
{key: list(group) for key, group in mt.groupby_transform(
    x, lambda row: row[0], lambda row: list(row[1:])
)}

Disclosure: I contributed the groupby_transform() function to more-itertools


问:
Buttons on form not working
So I'd like to start by saying this is my first time dealing with JS and I am working on a project for my class.

I have to create a form with three buttons, one that will store the form data, one that will display it and one that will clear the form.  I have been researching to all ends to try and figure out what I am doing wrong.  This is an online class so not much info is given other than here's the book and here's your assignment.

Here's what I have so far, any ideas as to why my store and display buttons are not working and also is there a way I can check to see if the store button is correctly storing the data in arrays and it's just the display button not working?!

I'm ripping my hair out, sorry for being terrible.

<DOCTYPE HTML!>

Internet Technologies Membership

<form name ="ratingForm">

Full Name:
<input type="text" id="FullName" name="FullName">
Date:
<input type="date" id="Date" name="Date">
Opinion:
<select name="opinion" id="opinion">
 <option value="excellent">Excellent</option>
 <option value="verygood">Very Good</option>
 <option value="good">Good</option>
 <option value="fair">Fair</option>
 <option value="poor">Poor</option>
 <option value="verybad">Very Bad</option>
</select>

<textarea name="list" id="list" rows="10" cols="100">
</textarea>

<input type="button" value="RATE" onClick="validateData();">
<input type="button" value="DISPLAY" onClick="displayData();">
<input type="reset" value="CLEAR" onClick="clearData();">

</form>

```

答:
You had many errors:

You had an invalid doc type. Your HTML was broken around the H1 Tag. The form tag wasn't closed.

You validation needed clean up in the rate function.

You where missing a + in the display function.

Here is full working code with comments on the fixes and how to go about debugging yourself in the future.

form {
  border-style: inset;
  border-color: blue;
  height: 360px;
  width: 775px;
  margin: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--
broken html.
Use a tool to validate your html and make it "pretty" or "tidy" for you.
-->
<h1 style="text-align:center; border-bottom:1px solid #999999">Internet Technologies Membership</h1>
<!--
An HTML validator would have told you <font> and <center> are depcrecated. Replaced with css.
-->
<form name="ratingForm">
  <table cellpadding="10">
    <td>
      <tr>
        <td>Full Name:</td>
        <td>
          <input type="text" id="FullName" name="FullName">
        </td>
        <td>Date:</td>
        <td>
          <input type="date" id="Date" name="Date">
        </td>
        <td>Opinion:</td>
        <td>
          <select name="opinion" id="opinion">
            <option value="excellent">Excellent</option>
            <option value="verygood">Very Good</option>
            <option value="good">Good</option>
            <option value="fair">Fair</option>
            <option value="poor">Poor</option>
            <option value="verybad">Very Bad</option>
          </select>
        </td>
      </tr>
  </table>
  <br>
  <center>
    <td>
      <textarea name="list" id="list" rows="10" cols="100">
      </textarea>
      <br>
      <br>
      <input type="button" value="RATE" onclick="validateData();">
      <input type="button" value="DISPLAY" onclick="displayData();">
      <input type="reset" value="CLEAR" onclick="clearData();">
      <br>
  </center>
 <!-- add missing end form tag -->
</form>
<!-- when javascript isn't working, put different blocks inside of seperate script tags.
If there is an error in one everything inside the script tag wont work.
Using seperate script tags you find out which block of code isn't working.
Also, look in web developer console for errors in the console tab.

-->
<script>
var fullNames = new Array(100);
var dates = new Array(100);
var opinions = new Array(100);

var numOfRatings = 0;
</script>
<!-- put validateData() in its own script tag to isolate it because it wasn't working. -->
<script>

function validateData() {
  //console.log('validating data'); // use console.log to see what code is executing
  var fullNameStr = document.getElementById("FullName").value;
  var dateStr = document.getElementById("Date").value;
  var opinionStr = document.getElementById("opinion").value;
  //console.log('validating data 1'); // making sure the getters didn't break anything.
  // add validation for name and opinion.
  //If they are null then display won't work because a string + null==null;
  if(!fullNameStr||!opinionStr|| !dateStr) {
   alert("Please complete all fields.");
    return;
  }
  var dateVal = dateStr;
  var dateParts = dateVal.split("/");

  // need to validate the dataParts array has at least two items.
  // also SHOULD be making sure it is a validate date.
  if (dateParts.length<3 || parseInt(dateParts[2]) < "2014") {
    alert("Invalid date!");
  } else {
    fullNames[numOfRatings] = fullNameStr;
    dates[numOfRatings] = dateStr;
    opinions[numOfRatings] = opinionStr;
    numOfRatings++;
    document.getElementById("FullName").value = "";
    document.getElementById("Date").value = "";
    document.getElementById("opinion").value = "";
  }
}
</script>

<!-- put displayData() in its own script tag to isolate it because it wasn't working. -->
<script>

function displayData() {
  var col;
  var pos;

  document.getElementById("list").value = "FULL NAME               DATE            RATING\n";

  for (pos = 0; pos < numOfRatings; pos++) {
    document.getElementById("list").value += fullNames[pos];
    for (col = fullNames[pos].length; col <= 25; col++)
      document.getElementById("list").value += " ";
    document.getElementById("list").value += dates[pos];
    for (col = dates[pos].length; col <= 15; col++)
      document.getElementById("list").value += " ";
      //broken code, add + after opinions[pos]
    document.getElementById("list").value += opinions[pos] +   "\n";
  }
}
</script>

<!-- put clearData() in its own script tag to isolate it because it wasn't working. -->
<script>

//Clear data function
function clearData() {
  var pos;

  for (pos = 0; pos < numOfRatings; pos++) {
    fullNames[pos] = "";
    dates[pos] = "";
    opinions[pos] = "";
  }
  numOfRatings = 0;
}
</script></code>```

Title: Buttons on form not working

Body:
You had many errors:

You had an invalid doc type. Your HTML was broken around the H1 Tag. The form tag wasn't closed.

You validation needed clean up in the rate function.

You where missing a + in the display function.

Here is full working code with comments on the fixes and how to go about debugging yourself in the future.

form {
  border-style: inset;
  border-color: blue;
  height: 360px;
  width: 775px;
  margin: auto;
}

<!--
broken html.
Use a tool to validate your html and make it "pretty" or "tidy" for you.
-->
<h1 style="text-align:center; border-bottom:1px solid #999999">Internet Technologies Membership</h1>
<!--
An HTML validator would have told you <font> and <center> are depcrecated. Replaced with css.
-->
<form name="ratingForm">
  <table cellpadding="10">
    <td>
      <tr>
        <td>Full Name:</td>
        <td>
          <input type="text" id="FullName" name="FullName">
        </td>
        <td>Date:</td>
        <td>
          <input type="date" id="Date" name="Date">
        </td>
        <td>Opinion:</td>
        <td>
          <select name="opinion" id="opinion">
            <option value="excellent">Excellent</option>
            <option value="verygood">Very Good</option>
            <option value="good">Good</option>
            <option value="fair">Fair</option>
            <option value="poor">Poor</option>
            <option value="verybad">Very Bad</option>
          </select>
        </td>
      </tr>
  </table>
  <br>
  <center>
    <td>
      <textarea name="list" id="list" rows="10" cols="100">
      </textarea>
      <br>
      <br>
      <input type="button" value="RATE" onclick="validateData();">
      <input type="button" value="DISPLAY" onclick="displayData();">
      <input type="reset" value="CLEAR" onclick="clearData();">
      <br>
  </center>
 <!-- add missing end form tag -->
</form>
<!-- when javascript isn't working, put different blocks inside of seperate script tags.
If there is an error in one everything inside the script tag wont work.
Using seperate script tags you find out which block of code isn't working.
Also, look in web developer console for errors in the console tab.

-->
<script>
var fullNames = new Array(100);
var dates = new Array(100);
var opinions = new Array(100);

var numOfRatings = 0;
</script>
<!-- put validateData() in its own script tag to isolate it because it wasn't working. -->
<script>

function validateData() {
  //console.log('validating data'); // use console.log to see what code is executing
  var fullNameStr = document.getElementById("FullName").value;
  var dateStr = document.getElementById("Date").value;
  var opinionStr = document.getElementById("opinion").value;
  //console.log('validating data 1'); // making sure the getters didn't break anything.
  // add validation for name and opinion.
  //If they are null then display won't work because a string + null==null;
  if(!fullNameStr||!opinionStr|| !dateStr) {
   alert("Please complete all fields.");
    return;
  }
  var dateVal = dateStr;
  var dateParts = dateVal.split("/");

  // need to validate the dataParts array has at least two items.
  // also SHOULD be making sure it is a validate date.
  if (dateParts.length<3 || parseInt(dateParts[2]) < "2014") {
    alert("Invalid date!");
  } else {
    fullNames[numOfRatings] = fullNameStr;
    dates[numOfRatings] = dateStr;
    opinions[numOfRatings] = opinionStr;
    numOfRatings++;
    document.getElementById("FullName").value = "";
    document.getElementById("Date").value = "";
    document.getElementById("opinion").value = "";
  }
}
</script>

<!-- put displayData() in its own script tag to isolate it because it wasn't working. -->
<script>

function displayData() {
  var col;
  var pos;

  document.getElementById("list").value = "FULL NAME               DATE            RATING\n";

  for (pos = 0; pos < numOfRatings; pos++) {
    document.getElementById("list").value += fullNames[pos];
    for (col = fullNames[pos].length; col <= 25; col++)
      document.getElementById("list").value += " ";
    document.getElementById("list").value += dates[pos];
    for (col = dates[pos].length; col <= 15; col++)
      document.getElementById("list").value += " ";
      //broken code, add + after opinions[pos]
    document.getElementById("list").value += opinions[pos] +   "\n";
  }
}
</script>

<!-- put clearData() in its own script tag to isolate it because it wasn't working. -->
<script>

//Clear data function
function clearData() {
  var pos;

  for (pos = 0; pos < numOfRatings; pos++) {
    fullNames[pos] = "";
    dates[pos] = "";
    opinions[pos] = "";
  }
  numOfRatings = 0;
}
</script>


问:
Visual Studio 2010 Javascript Intellisense not working properly
There's a little problem with Visual Studio 2010 and Javascript Intellisense.

I've implemented a class with some "Properties" and want to implement a "static" function, which returns a new instance of the class after an ajax-request which returns a Json-Object.

Like so:

```<code>/// <reference path="jQuery/jquery-1.4.1-vsdoc.js" />
MyClass = function (options) {
    /// <summary>MyClass Description</summary>
    /// <param name="options" type="Array">Foo1 (string), Foo2(string)</param>
    /// <field name="Foo1" type="String">Foo1 Description</field>
    /// <field name="Foo2" type="String">Foo2 Description</field>

    // [...] Some Code

    // Properties
    this.Foo1 = options.Foo1;
    this.Foo2 = options.Foo2;
}
</code>```

And the function:

intellisense not working:

```<code>MyClass.MyFunction = function () {
    /// <summary>MyFunction Description</summary>
    /// <returns type="MyClass">MyClass</returns>

    $.ajax({
        type: 'GET',
        url: '/Foo/Bar',
        dataType: 'json',
        success: function (result) {
            return new MyClass(result);
        }
    });
}
</code>```

intellisense working:

```<code>MyClass.MyFunction = function () {
    /// <summary>MyFunction Description</summary>
    /// <returns type="MyClass">MyClass</returns>

    var foo = new MyClass({'foo1': 'a', 'foo2': 'b'});
    $.ajax({
        type: 'GET',
        url: '/Foo/Bar',
        dataType: 'json',
        success: function (result) {
            foo = new MyClass(result);
            return foo;
        }
    });

    return foo;
}
</code>```

When I call the function from another function, like:

```<code>$(document).ready(function() {
    var foobar = MyClass.MyFunction(); // returns Object of type "MyClass"
    alert(foobar.Foo1); // At this Point, the intellisense doesn't work correct
});
</code>```

my intellisense isn't working anymore (or works with the double-return), because the return of MyFunction is within the ajax-request. If I place the return at the end of the function, the intellisense is working again. But in this case I have two returns. The first from the function and the second from the ajax-success.

It seems that the <returns...></returns> only works when the return is at the end of the function. That's bad, because I just need one return when the ajax-request is completed.

I don't know how to deal with this problem. Hope you can help me to fix this :)

答:
The return from inside the "success" callback is not going to work anyway. It'll return from that function, but nothing is going to pay attention to the return value, and in particular the return value from the "success" function will not be the return value from "MyFunction".

If what you want is for "MyFunction" to fetch a value and allow some code to work on it, then that code will have to be passed in to "MyFunction" and called in the "success" function.  Thus, instead of:

```<code>var thing = MyClass.MyFunction();
/*
  do stuff with "thing"
*/
</code>```

you'd change "MyFunction" around so that you could do this:

```<code>MyClass.MyFunction(function(thing) {
  /*
    do stuff with "thing"
  */
});
</code>```

The function would look something like this:

```<code>MyClass.MyFunction = function (doStuff) {
  /// <summary>MyFunction Description</summary>

  $.ajax({
    type: 'GET',
    url: '/Foo/Bar',
    dataType: 'json',
    success: function (result) {
        doStuff(new MyClass(result));
    }
  });
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
There's a little problem with Visual Studio 2010 and Javascript Intellisense.

I've implemented a class with some "Properties" and want to implement a "static" function, which returns a new instance of the class after an ajax-request which returns a Json-Object.

Like so:

/// <reference path="jQuery/jquery-1.4.1-vsdoc.js" />
MyClass = function (options) {
    /// MyClass Description
    /// <param name="options" type="Array">Foo1 (string), Foo2(string)</param>
    /// <field name="Foo1" type="String">Foo1 Description</field>
    /// <field name="Foo2" type="String">Foo2 Description</field>

    // [...] Some Code

    // Properties
    this.Foo1 = options.Foo1;
    this.Foo2 = options.Foo2;
}

And the function:

intellisense not working:

MyClass.MyFunction = function () {
    /// MyFunction Description
    /// <returns type="MyClass">MyClass</returns>

    $.ajax({
        type: 'GET',
        url: '/Foo/Bar',
        dataType: 'json',
        success: function (result) {
            return new MyClass(result);
        }
    });
}

intellisense working:

MyClass.MyFunction = function () {
    /// MyFunction Description
    /// <returns type="MyClass">MyClass</returns>

    var foo = new MyClass({'foo1': 'a', 'foo2': 'b'});
    $.ajax({
        type: 'GET',
        url: '/Foo/Bar',
        dataType: 'json',
        success: function (result) {
            foo = new MyClass(result);
            return foo;
        }
    });

    return foo;
}

When I call the function from another function, like:

$(document).ready(function() {
    var foobar = MyClass.MyFunction(); // returns Object of type "MyClass"
    alert(foobar.Foo1); // At this Point, the intellisense doesn't work correct
});

my intellisense isn't working anymore (or works with the double-return), because the return of MyFunction is within the ajax-request. If I place the return at the end of the function, the intellisense is working again. But in this case I have two returns. The first from the function and the second from the ajax-success.

It seems that the <returns...></returns> only works when the return is at the end of the function. That's bad, because I just need one return when the ajax-request is completed.

I don't know how to deal with this problem. Hope you can help me to fix this :)

Body:
The return from inside the "success" callback is not going to work anyway. It'll return from that function, but nothing is going to pay attention to the return value, and in particular the return value from the "success" function will not be the return value from "MyFunction".

If what you want is for "MyFunction" to fetch a value and allow some code to work on it, then that code will have to be passed in to "MyFunction" and called in the "success" function.  Thus, instead of:

var thing = MyClass.MyFunction();
/*
  do stuff with "thing"
*/

you'd change "MyFunction" around so that you could do this:

MyClass.MyFunction(function(thing) {
  /*
    do stuff with "thing"
  */
});

The function would look something like this:

MyClass.MyFunction = function (doStuff) {
  /// <summary>MyFunction Description</summary>

  $.ajax({
    type: 'GET',
    url: '/Foo/Bar',
    dataType: 'json',
    success: function (result) {
        doStuff(new MyClass(result));
    }
  });
}


问:
ReplayKit, status bar won't go away after watching preview
My app has status bar hidden at all times.

Except when viewing a recorded preview, the status bar comes up when watching the preview in the preview controller, but it does not go away when the preview controller is dismissed. I've double checked that prefersStatusBarHidden returns YES for the controller I am using. I really need to keep the status bar hidden at all times.

[[UIApplication sharedApplication] setStatusBarHidden:YES]; does not help. I tried calling this in the handler dismissViewControllerAnimated:completion:.

[self.viewController setNeedsStatusBarAppearanceUpdate]; does not help either. I tried calling this in the handler dismissViewControllerAnimated:completion:.

I noticed that the status bar seems to go away properly if user goes to home screen and back. That's not enough for a fix however.

答:
Seems weird not working in iOS 9.0.2 , but work in other system version?

```<code>- (void)previewControllerDidFinish:
(RPPreviewViewController*)previewController
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (previewController != nil)
        {
            [previewController dismissViewControllerAnimated:YES completion:
nil];
        }
    });
}
</code>```

Setting View controller-based status bar appearance in info.plist to YES and return YES of prefersStatusBarHidden method in viewController work for me

```<code>- (BOOL)prefersStatusBarHidden
{
    return YES;
}
</code>```

and this site may help: https://forums.developer.apple.com/thread/19626

Body:
Seems weird not working in iOS 9.0.2 , but work in other system version?

- (void)previewControllerDidFinish:
(RPPreviewViewController*)previewController
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (previewController != nil)
        {
            [previewController dismissViewControllerAnimated:YES completion:
nil];
        }
    });
}

Setting View controller-based status bar appearance in info.plist to YES and return YES of prefersStatusBarHidden method in viewController work for me

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

and this site may help: https://forums.developer.apple.com/thread/19626


问:
Subclassing DecimalField
I'm trying to create a DecimalField subclass, using the code below

```<code>class PositiveMoneyField(DecimalField):
    def __init__(self, verbose_name=None, name=None, **kwargs):
        super().__init__(self,
            verbose_name, name,
            max_digits=9, decimal_places=2,
            validators=[MinValueValidator(Decimal(0.0)), ],
            **kwargs
    )
</code>```

But it give me this error:

```<code>TypeError: __init__() got multiple values for argument 'max_digits'
</code>```

Any help is appreciated.

Thanks,

Eric

答:
After checking other django fields as SlugField, I found the solution:</p>

```<code>class PositiveMoneyField(DecimalField):

    def __init__(self, *args, max_digits=9, decimal_places=2, **kwargs):
        kwargs.update({'validators': [MinValueValidator(Decimal(0.01)), ]})
        super().__init__(*args, max_digits=max_digits, decimal_places=decimal_places, **kwargs)
</code>```

Title: Subclassing DecimalField

Body:
I'm trying to create a DecimalField subclass, using the code below

class PositiveMoneyField(DecimalField):
    def __init__(self, verbose_name=None, name=None, **kwargs):
        super().__init__(self,
            verbose_name, name,
            max_digits=9, decimal_places=2,
            validators=[MinValueValidator(Decimal(0.0)), ],
            **kwargs
    )

But it give me this error:

TypeError: __init__() got multiple values for argument 'max_digits'

Any help is appreciated.

Thanks,

Eric

Body:
After checking other django fields as SlugField, I found the solution:

class PositiveMoneyField(DecimalField):

    def __init__(self, *args, max_digits=9, decimal_places=2, **kwargs):
        kwargs.update({'validators': [MinValueValidator(Decimal(0.01)), ]})
        super().__init__(*args, max_digits=max_digits, decimal_places=decimal_places, **kwargs)


问:
android: how do I fix onBackPress listener?
I have a UI with a bunch of EditText lines for the user to enter data, c/f/gListenerEditTexts.  When the user enters data on fListenerEditText line and presses the Back key, the DiscardFragment dialog correctly opens.  If the user clicks "Ok" button on the dialog, the dialog closes, the data is discarded and the user is returned to the previous Activity.  My problem is that the gListenerEditText line does not work as expected when the user presses the Back key.  In this case, the DiscardFragment dialog opens for 1 or 2 seconds and then automatically closes and the UI returns to the previous Activity.  This happens without the user clicking on the "Ok" button.  What am I missing here?</p>

```<code>EditActivity.java

public class EditActivity extends AppCompatActivity

private ListenerEditText cListenerEditText,fListenerEditText,GListenerEditText;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_edit);

    cListenerEditText = (ListenerEditText) findViewById(id.CEditText);
    fListenerEditText = (ListenerEditText) findViewById(id.FEditText);
    gListenerEditText = (ListenerEditText) findViewById(id.GEditText);

...
cListenerEditText.setKeyImeChangeListener(new ListenerEditText.KeyImeChange() {
        @Override
        public boolean onKeyIme(int keyCode, KeyEvent event) {

            int stringToDo = cListenerEditText.getText().toString().replace(" ","").length();
            int stringDueDate = fListenerEditText.getText().toString().replace(" ","").length();
            int stringDueTime = gListenerEditText.getText().toString().replace(" ","").length();
            // If the EditText input line has data ("stringToDo") and the user presses the Back button,
            // then launch the DialogFragment to see if they really want to delete the data and
            // go back to the previous activity.
            if (stringToDo > 0) {
                FragmentManager fm3 = getSupportFragmentManager();
                DiscardFragment editNameDialog3 = new DiscardFragment();
                editNameDialog3.show(fm3,"s_dialog");
            }
            // when a date is entered by the user, this test works as expected
            else if (stringToDo == 0 && stringDueDate > 0) {
                FragmentManager fm4 = getSupportFragmentManager();
                DiscardFragment editNameDialog4 = new DiscardFragment();
                editNameDialog4.show(fm4,"s_dialog");
            }
            // when a time is entered by the user, this test is not working as expected
            else if (stringToDo == 0 && stringDueTime > 0) {
                FragmentManager fm5 = getSupportFragmentManager();
                DiscardFragment editNameDialog5 = new DiscardFragment();
                editNameDialog5.show(fm5,"s_dialog");
            }
            else if (stringToDo == 0){
                // close the softkeyboard
                InputMethodManager imm = (InputMethodManager)
                    getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(dListenerEditText.getWindowToken(),0);
            }
            return true;
        }
    });

DiscardFragment.java

public class DiscardFragment extends DialogFragment{

    public DiscardSkycardFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.discardfrag_layout,container,false);
        getDialog().setTitle("Discard");

        // When the user clicks "Cancel" in the "Delete" dialog, return to the CardViewActivity.
        Button btnCancel = (Button) rootView.findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(EditActivity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
            getDialog().cancel();
        }
        });

        // When the user clicks "OK" to delete for the "Delete" dialog.
        Button btnOK = (Button) rootView.findViewById(R.id.btnOK);
        btnOK.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            dismiss();
            // Next line returns to the previous activity (MainActivity) by closing
            // the current activity (CardViewActivity).
            getActivity().finish();
        }
        });

        // handles when the user presses the Back Button when the "Delete" dialog is open.
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if ((keyCode == KeyEvent.KEYCODE_BACK)) {
                // This filters the event as the back button press
                if (event.getAction()!= KeyEvent.ACTION_DOWN)
                    // Next line dismisses the dialogfragment
                    dismiss();
                // Next line returns to the previous activity (MainActivity) by closing the fragment and
                // the current activity (CardViewActivity).
                getActivity().finish();
                return true;
            }
            return false;
        }
        });
        return rootView;
    }
</code>```

<p>}    </p>

答:
try this.</p>

```<code>cListenerEditText.setKeyImeChangeListener(new ListenerEditText.KeyImeChange() {
        @Override
        public boolean onKeyIme(int keyCode, KeyEvent event) {
          if(event.getAction()==KeyEvent.ACTION_UP) {
            int stringToDo = cListenerEditText.getText().toString().replace(" ","").length();
            int stringDueDate = fListenerEditText.getText().toString().replace(" ","").length();
            int stringDueTime = gListenerEditText.getText().toString().replace(" ","").length();
            // If the EditText input line has data ("stringToDo") and the user presses the Back button,
            // then launch the DialogFragment to see if they really want to delete the data and
            // go back to the previous activity.
            if (stringToDo > 0) {
                FragmentManager fm3 = getSupportFragmentManager();
                DiscardFragment editNameDialog3 = new DiscardFragment();
                editNameDialog3.show(fm3,"s_dialog");
            }
            // when a date is entered by the user, this test works as expected
            else if (stringToDo == 0 && stringDueDate > 0) {
                FragmentManager fm4 = getSupportFragmentManager();
                DiscardFragment editNameDialog4 = new DiscardFragment();
                editNameDialog4.show(fm4,"s_dialog");
            }
            // when a time is entered by the user, this test is not working as expected
            else if (stringToDo == 0 && stringDueTime > 0) {
                FragmentManager fm5 = getSupportFragmentManager();
                DiscardFragment editNameDialog5 = new DiscardFragment();
                editNameDialog5.show(fm5,"s_dialog");
            }
            else if (stringToDo == 0){
                // close the softkeyboard
                InputMethodManager imm = (InputMethodManager)
                    getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(dListenerEditText.getWindowToken(),0);
            }
          }
          return true;
        }
    });
</code>```

Body:
I have a UI with a bunch of EditText lines for the user to enter data, c/f/gListenerEditTexts.  When the user enters data on fListenerEditText line and presses the Back key, the DiscardFragment dialog correctly opens.  If the user clicks "Ok" button on the dialog, the dialog closes, the data is discarded and the user is returned to the previous Activity.  My problem is that the gListenerEditText line does not work as expected when the user presses the Back key.  In this case, the DiscardFragment dialog opens for 1 or 2 seconds and then automatically closes and the UI returns to the previous Activity.  This happens without the user clicking on the "Ok" button.  What am I missing here?

EditActivity.java

public class EditActivity extends AppCompatActivity

private ListenerEditText cListenerEditText,fListenerEditText,GListenerEditText;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_edit);

    cListenerEditText = (ListenerEditText) findViewById(id.CEditText);
    fListenerEditText = (ListenerEditText) findViewById(id.FEditText);
    gListenerEditText = (ListenerEditText) findViewById(id.GEditText);

...
cListenerEditText.setKeyImeChangeListener(new ListenerEditText.KeyImeChange() {
        @Override
        public boolean onKeyIme(int keyCode, KeyEvent event) {

            int stringToDo = cListenerEditText.getText().toString().replace(" ","").length();
            int stringDueDate = fListenerEditText.getText().toString().replace(" ","").length();
            int stringDueTime = gListenerEditText.getText().toString().replace(" ","").length();
            // If the EditText input line has data ("stringToDo") and the user presses the Back button,
            // then launch the DialogFragment to see if they really want to delete the data and
            // go back to the previous activity.
            if (stringToDo > 0) {
                FragmentManager fm3 = getSupportFragmentManager();
                DiscardFragment editNameDialog3 = new DiscardFragment();
                editNameDialog3.show(fm3,"s_dialog");
            }
            // when a date is entered by the user, this test works as expected
            else if (stringToDo == 0 && stringDueDate > 0) {
                FragmentManager fm4 = getSupportFragmentManager();
                DiscardFragment editNameDialog4 = new DiscardFragment();
                editNameDialog4.show(fm4,"s_dialog");
            }
            // when a time is entered by the user, this test is not working as expected
            else if (stringToDo == 0 && stringDueTime > 0) {
                FragmentManager fm5 = getSupportFragmentManager();
                DiscardFragment editNameDialog5 = new DiscardFragment();
                editNameDialog5.show(fm5,"s_dialog");
            }
            else if (stringToDo == 0){
                // close the softkeyboard
                InputMethodManager imm = (InputMethodManager)
                    getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(dListenerEditText.getWindowToken(),0);
            }
            return true;
        }
    });

DiscardFragment.java

public class DiscardFragment extends DialogFragment{

    public DiscardSkycardFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.discardfrag_layout,container,false);
        getDialog().setTitle("Discard");

        // When the user clicks "Cancel" in the "Delete" dialog, return to the CardViewActivity.
        Button btnCancel = (Button) rootView.findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(EditActivity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
            getDialog().cancel();
        }
        });

        // When the user clicks "OK" to delete for the "Delete" dialog.
        Button btnOK = (Button) rootView.findViewById(R.id.btnOK);
        btnOK.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            dismiss();
            // Next line returns to the previous activity (MainActivity) by closing
            // the current activity (CardViewActivity).
            getActivity().finish();
        }
        });

        // handles when the user presses the Back Button when the "Delete" dialog is open.
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if ((keyCode == KeyEvent.KEYCODE_BACK)) {
                // This filters the event as the back button press
                if (event.getAction()!= KeyEvent.ACTION_DOWN)
                    // Next line dismisses the dialogfragment
                    dismiss();
                // Next line returns to the previous activity (MainActivity) by closing the fragment and
                // the current activity (CardViewActivity).
                getActivity().finish();
                return true;
            }
            return false;
        }
        });
        return rootView;
    }

}

Body:
try this.

cListenerEditText.setKeyImeChangeListener(new ListenerEditText.KeyImeChange() {
        @Override
        public boolean onKeyIme(int keyCode, KeyEvent event) {
          if(event.getAction()==KeyEvent.ACTION_UP) {
            int stringToDo = cListenerEditText.getText().toString().replace(" ","").length();
            int stringDueDate = fListenerEditText.getText().toString().replace(" ","").length();
            int stringDueTime = gListenerEditText.getText().toString().replace(" ","").length();
            // If the EditText input line has data ("stringToDo") and the user presses the Back button,
            // then launch the DialogFragment to see if they really want to delete the data and
            // go back to the previous activity.
            if (stringToDo > 0) {
                FragmentManager fm3 = getSupportFragmentManager();
                DiscardFragment editNameDialog3 = new DiscardFragment();
                editNameDialog3.show(fm3,"s_dialog");
            }
            // when a date is entered by the user, this test works as expected
            else if (stringToDo == 0 && stringDueDate > 0) {
                FragmentManager fm4 = getSupportFragmentManager();
                DiscardFragment editNameDialog4 = new DiscardFragment();
                editNameDialog4.show(fm4,"s_dialog");
            }
            // when a time is entered by the user, this test is not working as expected
            else if (stringToDo == 0 && stringDueTime > 0) {
                FragmentManager fm5 = getSupportFragmentManager();
                DiscardFragment editNameDialog5 = new DiscardFragment();
                editNameDialog5.show(fm5,"s_dialog");
            }
            else if (stringToDo == 0){
                // close the softkeyboard
                InputMethodManager imm = (InputMethodManager)
                    getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(dListenerEditText.getWindowToken(),0);
            }
          }
          return true;
        }
    });


问:
How to hide text links when viewed in mobile with bootstrap 4
I'd like to hide the text part of the link when viewed in mobile (xs and sm) sizes. How can I accomplish this? Does bootstrap 4 offer anything?

HTML

```<code><li>
  <a href="#"><i class="fa fa-icon"></i> Text Link</a>
</li>
</code>```

In mobile, I should only see the (icon). In desktop or tablet mode, I'll see (icon) Text Link

答:
My suggestion is using CSS3

/*Your smartphone screen width*/
@media screen and (max-width:400px){
  #myText{
    display:none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li>
  <i class="fa fa-icon"></i><span id="myText">Text Link</span>
</li></code>```

Body:
I'd like to hide the text part of the link when viewed in mobile (xs and sm) sizes. How can I accomplish this? Does bootstrap 4 offer anything?

HTML

   Text Link

In mobile, I should only see the (icon). In desktop or tablet mode, I'll see (icon) Text Link

Body:
My suggestion is using CSS3

/*Your smartphone screen width*/
@media screen and (max-width:400px){
  #myText{
    display:none;
  }
}

<li>
  <a href="#"><i class="fa fa-icon"></i><span id="myText">Text Link</span></a>
</li>


问:
sed insert line command OSX
I'm trying to insert text to the third line in a file using sed, and the syntax I've found on other forums is:

```<code>sed -i '' "3i\ text to insert" file
</code>```

When I use this however, I get an error:

```<code>sed: 1: "3i\ text to insert": extra characters after \ at the end of i command
</code>```

I can't seem to figure out what is causing the problem. I'm using OSX, which is why I have an empty ' ' as my extension.

Thanks!

答:
Here's how to do it in one line syntax

```<code>sed -i '' -e "2s/^//p; 2s/^.*/text to insert/" file
</code>```

duplicate second line: 2s/^//p;

replace new line with your text: 2s/^.*/text to insert/

Title: sed insert line command OSX

Body:
I'm trying to insert text to the third line in a file using sed, and the syntax I've found on other forums is:

sed -i '' "3i\ text to insert" file

When I use this however, I get an error:

sed: 1: "3i\ text to insert": extra characters after \ at the end of i command

I can't seem to figure out what is causing the problem. I'm using OSX, which is why I have an empty ' ' as my extension.

Thanks!

Body:
Here's how to do it in one line syntax

sed -i '' -e "2s/^//p; 2s/^.*/text to insert/" file

duplicate second line: 2s/^//p;

replace new line with your text: 2s/^.*/text to insert/


问:
Webpack Breaks Mocha in Node.js App
I have a node.js app that uses Mocha and Expect for testing. All the tests work great, until I installed webpack for react. Now when I run "npm test" I get the following error:

```<code>Error: Cannot find module 'should'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\watchpack\test\DirectoryWatcher.test.js:2:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:230:27
    at Array.forEach (native)
    at Mocha.loadFiles (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:227:14)
    at Mocha.run (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:495:10)
    at Object.<anonymous> (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\bin\_mocha:469:18)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:508:3
npm ERR! Test failed.  See above for more details.
</code>```

Below is my package.json:

```<code>{
  "name": "cool-map",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node server.js",
    "test": "export NODE_ENV=test || SET \"NODE_ENV=test\" && mocha **/*.test.js",
    "test-watch": "nodemon --exec \"npm test\""
  },
  "engines": {
    "node": "6.2.2"
  },
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.3.0",
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "jsonwebtoken": "^7.1.9",
    "lodash": "^4.15.0",
    "mongodb": "^2.2.5",
    "mongoose": "^4.5.9",
    "validator": "^5.6.0",
    "hbs": "^4.0.0",
    "babel-preset-stage-0": "^6.24.1",
    "express": "^4.15.2",
    "react": "^0.14.7",
    "react-dom": "^0.14.7"
  },
  "devDependencies": {
    "expect": "^1.20.2",
    "mocha": "^3.0.2",
    "nodemon": "^1.10.2",
    "supertest": "^2.0.0",
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "webpack": "^1.12.13"
  }
}
</code>```

I'm not sure if webpack.config is necessary to post, but just in case:

```<code>module.exports = {
    entry: './app/app.jsx',
    output: {
        path: __dirname,
        filename: './public/bundle.js'
    },
    resolve: {
        root: __dirname,
        alias: {
            AdminUserTable: 'app/components/AdminUserTable.jsx'
        },
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            {
                    loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015']
                },
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/
            }
        ]
    }
};
</code>```

Running the command npm test works great when I uninstall webpack, I'm not sure why It's breaking mocha.

答:
should is an expressive, readable, framework-agnostic assertion library. The main goals of this library are to be expressive and to be helpful. It keeps your test code clean, and your error messages helpful.
By default (when you require('should')) should extends the Object.prototype with a single non-enumerable getter that allows you to express how that object should behave. It also returns itself when required with require.
It is also possible to use should.js without getter (it will not even try to extend Object.prototype), just require('should/as-function'). Or if you already use version that auto add getter, you can call .noConflict function.
Results of (something).should getter and should(something) in most situations are the same

Better u install node dependency should with npm as below

```<code>npm install --save should
</code>```

should-reference

Title: Webpack Breaks Mocha in Node.js App

Body:
I have a node.js app that uses Mocha and Expect for testing. All the tests work great, until I installed webpack for react. Now when I run "npm test" I get the following error:

Error: Cannot find module 'should'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\watchpack\test\DirectoryWatcher.test.js:2:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:230:27
    at Array.forEach (native)
    at Mocha.loadFiles (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:227:14)
    at Mocha.run (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\lib\mocha.js:495:10)
    at Object.<anonymous> (C:\Users\Brian\version-control\tysons-tech-map-redone\node_modules\mocha\bin\_mocha:469:18)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:393:7)
    at startup (bootstrap_node.js:150:9)
    at bootstrap_node.js:508:3
npm ERR! Test failed.  See above for more details.

Below is my package.json:

{
  "name": "cool-map",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node server.js",
    "test": "export NODE_ENV=test || SET \"NODE_ENV=test\" && mocha **/*.test.js",
    "test-watch": "nodemon --exec \"npm test\""
  },
  "engines": {
    "node": "6.2.2"
  },
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.3.0",
    "body-parser": "^1.15.2",
    "express": "^4.14.0",
    "jsonwebtoken": "^7.1.9",
    "lodash": "^4.15.0",
    "mongodb": "^2.2.5",
    "mongoose": "^4.5.9",
    "validator": "^5.6.0",
    "hbs": "^4.0.0",
    "babel-preset-stage-0": "^6.24.1",
    "express": "^4.15.2",
    "react": "^0.14.7",
    "react-dom": "^0.14.7"
  },
  "devDependencies": {
    "expect": "^1.20.2",
    "mocha": "^3.0.2",
    "nodemon": "^1.10.2",
    "supertest": "^2.0.0",
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "webpack": "^1.12.13"
  }
}

I'm not sure if webpack.config is necessary to post, but just in case:

module.exports = {
    entry: './app/app.jsx',
    output: {
        path: __dirname,
        filename: './public/bundle.js'
    },
    resolve: {
        root: __dirname,
        alias: {
            AdminUserTable: 'app/components/AdminUserTable.jsx'
        },
        extensions: ['', '.js', '.jsx']
    },
    module: {
        loaders: [
            {
                    loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015']
                },
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/
            }
        ]
    }
};

Running the command npm test works great when I uninstall webpack, I'm not sure why It's breaking mocha.

Body:
should is an expressive, readable, framework-agnostic assertion library. The main goals of this library are to be expressive and to be helpful. It keeps your test code clean, and your error messages helpful.
By default (when you require('should')) should extends the Object.prototype with a single non-enumerable getter that allows you to express how that object should behave. It also returns itself when required with require.
It is also possible to use should.js without getter (it will not even try to extend Object.prototype), just require('should/as-function'). Or if you already use version that auto add getter, you can call .noConflict function.
Results of (something).should getter and should(something) in most situations are the same

Better u install node dependency should with npm as below

npm install --save should

should-reference


问:
How to use public class frome .java file in other processing tabs?
My problem seems to be trivial, but after 2 hours of googling I came with nothing. I have Processing sketch. The first, main tab contains:

```<code>Foo bar;

void setup() {
}

void draw() {
}
</code>```

The second is Foo.java file:

```<code>package processing.core;
import java.io.Serializable;
import processing.core.PApplet;

public class Foo implements Serializable {
}
</code>```

After I try to run this program I get at the first line of the first file:

```<code>Cannot find a class or type "Foo"
</code>```

The second file is Foo.java, the first has some random name, not even simmilar, so it's not a conflict. And the file is in the same directory as the main pde file.

I work in the Processing IDE.

What should I do to make the .java file class visible? And yes - I need .java file, since I need to use some much more complicated .java file...

Thank you in advance!

答:
This next is a working example that shows how to interact with the canvas as well:

Sketch.pde

```<code>Foo bar;

void setup() {
  fill(255);
  background(0);
  textAlign(CENTER,CENTER);
}

void draw() {
}

void mouseReleased(){
  bar = new Foo(this);
}
</code>```

Foo.java

```<code>import java.io.Serializable;
import processing.core.PApplet;

public class Foo implements Serializable {

  protected final PApplet parent;
  Foo(PApplet pa) {
    parent=pa;
    pa.text("Foo created",parent.width/2,parent.height/2);
    pa.noLoop();
  }
}
</code>```

An explanation related to this layout can be found here. The good bits are quoted here next as explained by GoToLoop:

Processing framework, in its most basic form, is the PApplet class plus a drawing canvas.

Functions setup(), draw(), mousePressed(), etc. are callbacks for its "Animation" Thread.

The "sketch" itself extends PApplet and it's a full Java class instance.

In order to access the canvas, we need that instance's reference/pointer.

Therefore, in order for a library or some other top class to be able to draw anything, it gotta request that reference.

I hope this helps,

Kf

Body:
My problem seems to be trivial, but after 2 hours of googling I came with nothing. I have Processing sketch. The first, main tab contains:

Foo bar;

void setup() {
}

void draw() {
}

The second is Foo.java file:

package processing.core;
import java.io.Serializable;
import processing.core.PApplet;

public class Foo implements Serializable {
}

After I try to run this program I get at the first line of the first file:

Cannot find a class or type "Foo"

The second file is Foo.java, the first has some random name, not even simmilar, so it's not a conflict. And the file is in the same directory as the main pde file.

I work in the Processing IDE.

What should I do to make the .java file class visible? And yes - I need .java file, since I need to use some much more complicated .java file...

Thank you in advance!

Body:
This next is a working example that shows how to interact with the canvas as well:

Sketch.pde

Foo bar;

void setup() {
  fill(255);
  background(0);
  textAlign(CENTER,CENTER);
}

void draw() {
}

void mouseReleased(){
  bar = new Foo(this);
}

Foo.java

import java.io.Serializable;
import processing.core.PApplet;

public class Foo implements Serializable {

  protected final PApplet parent;
  Foo(PApplet pa) {
    parent=pa;
    pa.text("Foo created",parent.width/2,parent.height/2);
    pa.noLoop();
  }
}

An explanation related to this layout can be found here. The good bits are quoted here next as explained by GoToLoop:

Processing framework, in its most basic form, is the PApplet class plus a drawing canvas.

Functions setup(), draw(), mousePressed(), etc. are callbacks for its "Animation" Thread.

The "sketch" itself extends PApplet and it's a full Java class instance.

In order to access the canvas, we need that instance's reference/pointer.

Therefore, in order for a library or some other top class to be able to draw anything, it gotta request that reference.

I hope this helps,

Kf


问:
How to read text on a web page in swift for ios
I have a web page that only shows simple text information but I am unsure how to get the text using swift. I am open to using any method as I think this is an easy problem, I am just unsure what to search for to find an answer.

Here is the webpage in question where the last part, "player=bob" can be modified depending on the user. Thanks

http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=bob

答:
Do you want to get string from UIWebView or WKWebView?

If you use UIWebView,the first thing you must set UIWebView delegate.

```- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *newString = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"];
}```

The 'newString' is the HTML String in webView.If you want to use real show on page,you need to translate strings.
I hope that can help you.
If you use WKWebView,this may not work.

Body:
Do you want to get string from UIWebView or WKWebView?

If you use UIWebView,the first thing you must set UIWebView delegate.

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *newString = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"];
}

The 'newString' is the HTML String in webView.If you want to use real show on page,you need to translate strings.
I hope that can help you.
If you use WKWebView,this may not work.


问:
Get all videos of a YouTube Playlist in Java
Context I'm working with Android Studio (Java). I want to obtain all the videos of a given playlist (or 50, I will get all the other after).

Problem I see people using url like
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLiEwZfNgb4fVrRzTonlVEMj6DB2Nmzg2M&key=AIzaSyC2_YRcTE9916fsmA0_KRnef43GbLzz8m0
 but I don't know how to implement this in Java. I follow some tuto and I got a way to get information totally different like :

```<code>YouTube.Search.List query;
query = youtube.search().list("id,snippet");
      query.setKey(MY_API_KEY);
      query.setMaxResults((long)20);
      query.setType("video");
      query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url)");
</code>```

And I really don't understand how do I get something else than a search.
Most of documentation is in english only...

EDIT
Ok, so I continued to try, I think I got a near solution, but I got an error.

```<code>private YouTube youtube;
private YouTube.PlaylistItems.List playlistItemRequest;
private String PLAYLIST_ID = "PLiEwZfNgb4fVrRzTonlVEMj6DB2Nmzg2M";
public static final String KEY = "AIzaSyC2_YRcTE9916fsmA0_KRnef43GbLzz8m0";

// Constructor
public YoutubeConnector(Context context)
{
    youtube = new YouTube.Builder(new NetHttpTransport(),
            new JacksonFactory(), new HttpRequestInitializer()
    {
        @Override
        public void initialize(HttpRequest hr) throws IOException {}
    }).setApplicationName(context.getString(R.string.app_name)).build();
}

public List<VideoItem> result()
{
    List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
    try
    {
    /* HERE MUST BE MY PROBLEM ! */
        playlistItemRequest = youtube.playlistItems().list("snippet");
        playlistItemRequest.setPlaylistId(PLAYLIST_ID);
        playlistItemRequest.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url),nextPageToken,pageInfo");
        playlistItemRequest.setKey(KEY);
        String nextToken = "";
        do {
            playlistItemRequest.setPageToken(nextToken);
            PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();

            playlistItemList.addAll(playlistItemResult.getItems());

            nextToken = playlistItemResult.getNextPageToken();
        } while (nextToken != null);
    }catch(IOException e)
    {
        Log.d("YC", "Could not initialize: "+e);
    }
//[...]
}
</code>```

Here is the error I got :

{
"code" : 400,
    "errors" : [ {
        "domain" : "global",
        "location" : "fields",
        "locationType" : "parameter",
        "message" : "Invalid field selection videoId",
        "reason" : "invalidParameter"
     } ],
     "message" : "Invalid field selection videoId"
}

EDIT 2 Thanks to : Martijn Woudstra.
Correct line was :

```<code>playlistItemRequest = youtube.playlistItems().list("snippet,contentDetails");
//[...]
playlistItemRequest.setFields("items(snippet/title,snippet/description,snippet/thumbnails/default/url,contentDetails/videoId),nextPageToken,pageInfo");
//[...]
videoItem.setId(item.getContentDetails().getVideoId());
</code>```

答:
I know that is an old question but It is important to identify which resources are we using to understand how to get the proper information. There are many resources in the YouTube API v3, but we usually use the search, video, playlist and playlistItems.

According to the documentation the following JSON structure shows the format of a playlistItems resource:

```<code>{
  "kind": "youtube#playlistItem",
  "etag": etag,
  "id": string,
  "snippet": {
    "publishedAt": datetime,
    "channelId": string,
    "title": string,
    "description": string,
    "thumbnails": {
      (key): {
        "url": string,
        "width": unsigned integer,
        "height": unsigned integer
      }
    },
    "channelTitle": string,
    "playlistId": string,
    "position": unsigned integer,
    "resourceId": {
      "kind": string,
      "videoId": string,
    }
  },
  "contentDetails": {
    "videoId": string,
    "startAt": string,
    "endAt": string,
    "note": string,
    "videoPublishedAt": datetime
  },
  "status": {
    "privacyStatus": string
  }
}
</code>```

From this structure, we may suppose that there are three ways to get the videoId. But first it is important to know how we going to define the PARTS and the FIELDS of the resource.

To define the PARTS we use this code:

```<code>YouTube.PlaylistItems.List list = youtube.playlistItems().list("snippet");
</code>```

In the previous line, "snippet" identifies a property that contains numerous fields (or child properties), including the title, description, position, and resourceId, so when we set "snippet" the API's response will contain all of those child properties.

Now, we also can limit the previous properties if we define the FIELDS. For example, in this code:

```<code>list.setFields("items(id/videoId,snippet/title,snippet/description," +
    "snippet/thumbnails/default/url)");
</code>```

If we call list.execute(), it will show an error because we didn't define id in the PARTS properties. Also, according to the JSON structure, id is a String and does not contains videoId as a child property. Ah!, but we can extract videoId from the resourceId? -Well, the answers is YES/NO. -Why so? Come on Teo, the JSON structure shows it clearly. -Yes, I can see that, but the documentation says:

If the snippet.resourceId.kind property's value is youtube#video, then this property will be present and its value will contain the ID that YouTube uses to uniquely identify the video in the playlist.

This means that sometimes may not be available. -Then, how we can get the videoId? -Well, we can add id or contentDetails to the PARTS resources. If we add id then defines fields like this:

```<code>YouTube.PlaylistItems.List list = youtube.playlistItems().list("id,snippet");
list.setFields("items(id,snippet/title,snippet/description," +
    "snippet/thumbnails/default/url)");
</code>```

If we add contentDetails then defines fields like this:

```<code>YouTube.PlaylistItems.List list = youtube.playlistItems()
    .list("snippet,contentDetails");
list.setFields("items(contentDetails/videoId,snippet/title,snippet/description," +
    "snippet/thumbnails/default/url)");
</code>```

I hope this helps you guys.

Body:
Context I'm working with Android Studio (Java). I want to obtain all the videos of a given playlist (or 50, I will get all the other after).

Problem I see people using url like
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PLiEwZfNgb4fVrRzTonlVEMj6DB2Nmzg2M&key=AIzaSyC2_YRcTE9916fsmA0_KRnef43GbLzz8m0
 but I don't know how to implement this in Java. I follow some tuto and I got a way to get information totally different like :

YouTube.Search.List query;
query = youtube.search().list("id,snippet");
      query.setKey(MY_API_KEY);
      query.setMaxResults((long)20);
      query.setType("video");
      query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url)");

And I really don't understand how do I get something else than a search.
Most of documentation is in english only...

EDIT
Ok, so I continued to try, I think I got a near solution, but I got an error.

private YouTube youtube;
private YouTube.PlaylistItems.List playlistItemRequest;
private String PLAYLIST_ID = "PLiEwZfNgb4fVrRzTonlVEMj6DB2Nmzg2M";
public static final String KEY = "AIzaSyC2_YRcTE9916fsmA0_KRnef43GbLzz8m0";

// Constructor
public YoutubeConnector(Context context)
{
    youtube = new YouTube.Builder(new NetHttpTransport(),
            new JacksonFactory(), new HttpRequestInitializer()
    {
        @Override
        public void initialize(HttpRequest hr) throws IOException {}
    }).setApplicationName(context.getString(R.string.app_name)).build();
}

public List<VideoItem> result()
{
    List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
    try
    {
    /* HERE MUST BE MY PROBLEM ! */
        playlistItemRequest = youtube.playlistItems().list("snippet");
        playlistItemRequest.setPlaylistId(PLAYLIST_ID);
        playlistItemRequest.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url),nextPageToken,pageInfo");
        playlistItemRequest.setKey(KEY);
        String nextToken = "";
        do {
            playlistItemRequest.setPageToken(nextToken);
            PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();

            playlistItemList.addAll(playlistItemResult.getItems());

            nextToken = playlistItemResult.getNextPageToken();
        } while (nextToken != null);
    }catch(IOException e)
    {
        Log.d("YC", "Could not initialize: "+e);
    }
//[...]
}

Here is the error I got :

{
"code" : 400,
    "errors" : [ {
        "domain" : "global",
        "location" : "fields",
        "locationType" : "parameter",
        "message" : "Invalid field selection videoId",
        "reason" : "invalidParameter"
     } ],
     "message" : "Invalid field selection videoId"
}

EDIT 2 Thanks to : Martijn Woudstra.
Correct line was :

playlistItemRequest = youtube.playlistItems().list("snippet,contentDetails");
//[...]
playlistItemRequest.setFields("items(snippet/title,snippet/description,snippet/thumbnails/default/url,contentDetails/videoId),nextPageToken,pageInfo");
//[...]
videoItem.setId(item.getContentDetails().getVideoId());

Body:
I know that is an old question but It is important to identify which resources are we using to understand how to get the proper information. There are many resources in the YouTube API v3, but we usually use the search, video, playlist and playlistItems.

According to the documentation the following JSON structure shows the format of a playlistItems resource:

{
  "kind": "youtube#playlistItem",
  "etag": etag,
  "id": string,
  "snippet": {
    "publishedAt": datetime,
    "channelId": string,
    "title": string,
    "description": string,
    "thumbnails": {
      (key): {
        "url": string,
        "width": unsigned integer,
        "height": unsigned integer
      }
    },
    "channelTitle": string,
    "playlistId": string,
    "position": unsigned integer,
    "resourceId": {
      "kind": string,
      "videoId": string,
    }
  },
  "contentDetails": {
    "videoId": string,
    "startAt": string,
    "endAt": string,
    "note": string,
    "videoPublishedAt": datetime
  },
  "status": {
    "privacyStatus": string
  }
}

From this structure, we may suppose that there are three ways to get the videoId. But first it is important to know how we going to define the PARTS and the FIELDS of the resource.

To define the PARTS we use this code:

YouTube.PlaylistItems.List list = youtube.playlistItems().list("snippet");

In the previous line, "snippet" identifies a property that contains numerous fields (or child properties), including the title, description, position, and resourceId, so when we set "snippet" the API's response will contain all of those child properties.

Now, we also can limit the previous properties if we define the FIELDS. For example, in this code:

list.setFields("items(id/videoId,snippet/title,snippet/description," +
    "snippet/thumbnails/default/url)");

If we call list.execute(), it will show an error because we didn't define id in the PARTS properties. Also, according to the JSON structure, id is a String and does not contains videoId as a child property. Ah!, but we can extract videoId from the resourceId? -Well, the answers is YES/NO. -Why so? Come on Teo, the JSON structure shows it clearly. -Yes, I can see that, but the documentation says:

If the snippet.resourceId.kind property's value is youtube#video, then this property will be present and its value will contain the ID that YouTube uses to uniquely identify the video in the playlist.

This means that sometimes may not be available. -Then, how we can get the videoId? -Well, we can add id or contentDetails to the PARTS resources. If we add id then defines fields like this:

YouTube.PlaylistItems.List list = youtube.playlistItems().list("id,snippet");
list.setFields("items(id,snippet/title,snippet/description," +
    "snippet/thumbnails/default/url)");

If we add contentDetails then defines fields like this:

YouTube.PlaylistItems.List list = youtube.playlistItems()
    .list("snippet,contentDetails");
list.setFields("items(contentDetails/videoId,snippet/title,snippet/description," +
    "snippet/thumbnails/default/url)");

I hope this helps you guys.


问:
How to compare a value of all contracts made within particular month to it's current value in foreing currency
I want to compare value of loan contracts made in a day with coresponding currency rate (CZK/EUR) within particular month and say what value the contracts have as to current month (say June).

E.g.:

```<code>1.5.2017 60,000 CZK, CZK/EUR = 27.125;
1.5.2017 180,000 CZK, CZK/EUR = 27.129;
2.5.2017 90,000 CZK, CZK/EUR = 27.019

...
= SUM(CZK), SUM(EUR) in May, EUR in June
</code>```

So far, I've come with:

```<code>;WITH orig AS (
       SELECT
          origEUR = SUM(ApprovedLoanAmount / cr.Rate)
          ,sumCZK = SUM(ApprovedLoanAmount)
       FROM dim.Contract con
          JOIN dim.Calendar cal ON con.CreateDateID = cal.DateID
          JOIN s96.CurrencyRates cr ON cr.Date = cal.Date
       WHERE (YEAR(cal.Date)=2017) AND (MONTH(cal.Date)=5) AND (CurrencyID = 1)
)

SELECT
    diff = orig.origEUR - (sumCZK / cr.Rate) --as to the current rate at the end of June
FROM orig orig
    JOIN s96.CurrencyRates cr --???
WHERE (YEAR(Date)=2017) AND (MONTH(Date)=6) AND (DAY(Date)=30) AND (CurrencyID = 1)
</code>```

I hope, I've made my idea clear :-)

答:
You can have constants as part of ON conditions

```<code>;WITH orig AS (
       SELECT
          origEUR = SUM(ApprovedLoanAmount / cr.Rate)
          ,sumCZK = SUM(ApprovedLoanAmount)
       FROM dim.Contract con
          JOIN dim.Calendar cal ON con.CreateDateID = cal.DateID
          JOIN s96.CurrencyRates cr ON cr.Date = cal.Date
       WHERE (YEAR(cal.Date)=2017) AND (MONTH(cal.Date)=5) AND (CurrencyID = 1)
)

SELECT
    diff = orig.origEUR - (sumCZK / cr.Rate) --as to the current rate at the end of June
FROM orig orig
    JOIN s96.CurrencyRates cr ON cr.Date = CONVERT( DATETIME, '[Pick a date]' ) -- e.g. CONVERT( DATETIME, '2017-07-01' )
WHERE (YEAR(Date)=2017) AND (MONTH(Date)=6) AND (DAY(Date)=30) AND (CurrencyID = 1)
</code>```

Body:
I want to compare value of loan contracts made in a day with coresponding currency rate (CZK/EUR) within particular month and say what value the contracts have as to current month (say June).

E.g.:

1.5.2017 60,000 CZK, CZK/EUR = 27.125;
1.5.2017 180,000 CZK, CZK/EUR = 27.129;
2.5.2017 90,000 CZK, CZK/EUR = 27.019

...
= SUM(CZK), SUM(EUR) in May, EUR in June

So far, I've come with:

;WITH orig AS (
       SELECT
          origEUR = SUM(ApprovedLoanAmount / cr.Rate)
          ,sumCZK = SUM(ApprovedLoanAmount)
       FROM dim.Contract con
          JOIN dim.Calendar cal ON con.CreateDateID = cal.DateID
          JOIN s96.CurrencyRates cr ON cr.Date = cal.Date
       WHERE (YEAR(cal.Date)=2017) AND (MONTH(cal.Date)=5) AND (CurrencyID = 1)
)

SELECT
    diff = orig.origEUR - (sumCZK / cr.Rate) --as to the current rate at the end of June
FROM orig orig
    JOIN s96.CurrencyRates cr --???
WHERE (YEAR(Date)=2017) AND (MONTH(Date)=6) AND (DAY(Date)=30) AND (CurrencyID = 1)

I hope, I've made my idea clear :-)

Body:
You can have constants as part of ON conditions

;WITH orig AS (
       SELECT
          origEUR = SUM(ApprovedLoanAmount / cr.Rate)
          ,sumCZK = SUM(ApprovedLoanAmount)
       FROM dim.Contract con
          JOIN dim.Calendar cal ON con.CreateDateID = cal.DateID
          JOIN s96.CurrencyRates cr ON cr.Date = cal.Date
       WHERE (YEAR(cal.Date)=2017) AND (MONTH(cal.Date)=5) AND (CurrencyID = 1)
)

SELECT
    diff = orig.origEUR - (sumCZK / cr.Rate) --as to the current rate at the end of June
FROM orig orig
    JOIN s96.CurrencyRates cr ON cr.Date = CONVERT( DATETIME, '[Pick a date]' ) -- e.g. CONVERT( DATETIME, '2017-07-01' )
WHERE (YEAR(Date)=2017) AND (MONTH(Date)=6) AND (DAY(Date)=30) AND (CurrencyID = 1)


问:
How to adjust the Caret (blinking cursor) size inside searchbar with css
I tried to google it, and surprisingly found no result related...
I wonder how can I use css to adjust the blinking cursor inside the search box with CSS?
I adjusted the size of the search box, but seem the blinking cursor's size is still original small text size.</p>

答:
```<code><style>
.input_strips {
font-family: monospace;

<!--change the font size this will change the input cursor and the text box-->
font-size: 30px;
}
</style>
</code>```


问:
JSP import class causing error
This is my first attempt for JSP. I am using TOMCAT8 and Geany to write on. I placed the application folder in /var/lib/tomcat8/webapps/Jproject and classes in /var/lib/tomcat8/webapps/Jproject/WEB-INF/classes.

my class file /var/lib/tomcat8/webapps/Jproject/WEB-INF/classes/test.class is;

```<code>public class test
{
public static void PP()
{
System.out.println("yoyo");
}
}
</code>```

and my index.jsp (/var/lib/tomcat8/webapps/Jproject/index.jsp) is;

```<code><%@ page import="Jproject.test.*" %>
<DOCTYPE! html>
<html>
<head>
<title>Project</title>
</head>
<body>
<%  String x = "java";
    out.println("Hello " + x + "Worlds");
test.PP(); %>
</body>
</html>
</code>```

when i run it on a browser http://localhost:8080/Jproject/ i get the following error;

```<code>HTTP Status 500 - Unable to compile class for JSP:

type Exception report

message Unable to compile class for JSP:

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 12 in the jsp file: /index.jsp
test cannot be resolved
9:  String x = "java";
10:
11:     out.println("Hello " + x + "Worlds");
12:     test.PP();
13: %>
14: </body>
15: </html>

Stacktrace:
    org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
    org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:198)
    org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:449)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:361)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:336)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:323)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:585)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:363)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:401)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:345)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.32 (Ubuntu) logs.

Apache Tomcat/8.0.32 (Ubuntu)
</code>```

What am I doing wrong? Thanks for your help!

答: you must create classes under src folder not a WEB-INF folder and jsp file create under webapp folder.

Title: JSP import class causing error

Body:
This is my first attempt for JSP. I am using TOMCAT8 and Geany to write on. I placed the application folder in /var/lib/tomcat8/webapps/Jproject and classes in /var/lib/tomcat8/webapps/Jproject/WEB-INF/classes.

my class file /var/lib/tomcat8/webapps/Jproject/WEB-INF/classes/test.class is;

public class test
{
public static void PP()
{
System.out.println("yoyo");
}
}

and my index.jsp (/var/lib/tomcat8/webapps/Jproject/index.jsp) is;

<%@ page import="Jproject.test.*" %>
<DOCTYPE! html>

<title>Project</title>

<%  String x = "java";
    out.println("Hello " + x + "Worlds");
test.PP(); %>

when i run it on a browser http://localhost:8080/Jproject/ i get the following error;

HTTP Status 500 - Unable to compile class for JSP:

type Exception report

message Unable to compile class for JSP:

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 12 in the jsp file: /index.jsp
test cannot be resolved
9:  String x = "java";
10:
11:     out.println("Hello " + x + "Worlds");
12:     test.PP();
13: %>
14:
15:

Stacktrace:
    org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
    org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:198)
    org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:449)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:361)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:336)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:323)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:585)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:363)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:401)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:345)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.32 (Ubuntu) logs.

Apache Tomcat/8.0.32 (Ubuntu)

What am I doing wrong? Thanks for your help!


问:
Is there a mechanism for integration testing JAX-RS services without deploying (a la MockMVC)?
I have successfully built no-deployment-needed integration test frameworks for Spring MVC REST services using Mock MVC.  I am struggling to do the same with JAX-RS services.

REST Assured looks promising, but it seems to require deployment.  The test suite  can start up a CXF server, but can it wire it up with a servlet container?

It seems that the unique value provided by Mock MVC is in its mock servlet container.  Does any other technology provide this.

The JAX-RS testing page of the CXF documentation provides a pattern for injecting a mock HttpServletRequest into a CXF invoker.  Which got me thinking ...

Spring MVC's mock servlet elements (MockHttpServletRequest, etc.) come from the spring-test module, is independent of Mock MVC.  Would we be able to inject these objects into a CXF invoker?  Or will this be a rabbit hole?

Has anyone come up with a solution to this problem?

.

答:
Daniel - I'm the developer of Karate and something I've been experimenting with is to use a combination of Mockito and the Spring mocks for the HTTPServletRe**** to call a servlet directly and avoid having to boot an app-server.

Since Karate has this swappable abstraction of an http-client, I was thinking of adding this option in the near future.

Just sharing in case it helps you with ideas, or if you want to compare notes. Feel free to open a thread on GitHub.

Update: I made very good progress on this - please look at this thread for a working example.


问:
Lisp - Type Error in Do Form When Reading from File
[SBCL] I'm trying to read char-by-char from a text file that looks like this:

```<code>:table
E E E E E
E C C C E
E E E E E
</code>```

My code (some omitted for clarity):

```<code>(defun read-txt (path)
   (with-open-file str path :direction :input
                   :if-exists :supersede)
     (let ((a nil)
           (form read-line str))
        (case form
          (otherwise (do* ((char (read-char str nil) (read-char str nil))
                           (count 0 (if (char= char #\Newline) (1+ count) count)))
                          ((null char) a)))))))
</code>```

Gives me an error along the lines of "The value NIL is not of type CHARACTER." The backtrace isn't useful at all, even after setting debug to 3. All it tells me is that I called read-txt and its argument is a file path.

When I print each character in the file, none of them are NIL. I don't get an error if I use char= in do's main body. The code compiles without errors or warnings.

答:
original response

A do form's variable list is evaluated before its end form each iteration. The last char in the file was nil. Since I was calling char= in the varlist, nil was passed to it just before do would have terminated.

Do's body is evaluated after the end form, which is why a char= in the body didn't cause an error.

Body:
[SBCL] I'm trying to read char-by-char from a text file that looks like this:

:table
E E E E E
E C C C E
E E E E E

My code (some omitted for clarity):

(defun read-txt (path)
   (with-open-file str path :direction :input
                   :if-exists :supersede)
     (let ((a nil)
           (form read-line str))
        (case form
          (otherwise (do* ((char (read-char str nil) (read-char str nil))
                           (count 0 (if (char= char #\Newline) (1+ count) count)))
                          ((null char) a)))))))

Gives me an error along the lines of "The value NIL is not of type CHARACTER." The backtrace isn't useful at all, even after setting debug to 3. All it tells me is that I called read-txt and its argument is a file path.

When I print each character in the file, none of them are NIL. I don't get an error if I use char= in do's main body. The code compiles without errors or warnings.