问:
passing data from javascript to servlet
I have values of checkbox and as soon as I click delete the values and the type must be sent to a servlet called DeleteServlet. Please help me how to send the values?

```<code><html>
    <head>
    <script type="text/javascript">
     function get_check_value(chkbox){
           if(chkbox.checked){
          var Values=chkbox.value;
          //send this Values to servlet

             }

    }
    function doDelete(theClick){
    var type=theClick;
//send this type to servlet
    alert(type);

    }

    </script>
    </head>
    <%String user=request.getParameter("Users"); %>
    <body>
    <%

    String User[]=user.trim().split(" ");

    for(int i=0;i<User.length;i++){%>
     <center>
        <form name='list' action='AddUserServlet'>

     <%  out.println("<input type='checkbox' name='user" + i + "' value='"+ User[i] + "' onClick='return get_check_value(this)'>" + User[i]+ "</input>" ); %>

    </form>

    <%}%>

        <input type="submit" value="ADD" name="b1" >
        <input type="submit" value="MODIFY" name="b1">
     <input type="submit" value="DELETE" name="b1" onClick="return doDelete(value)" >

      </center>

    </body>
    </html>
</code>```

I tried this  "document.list.user.value" in an alert box it comes as undefined object. To send to a servlet I tried the following line but nothing is read

```<code>chk_val=chkbox.value;
document.add.action = "AddUserServlet?type=delete&name="+chk_val;
 document.add.submit();
</code>```

答:
You don't need Javascript for this at all.

Just change your code so that the HTML form is generated as follows:

```<code><form action="AddUserServlet" method="post">
    <input type="checkbox" name="user" value="1">
    <input type="checkbox" name="user" value="2">
    <input type="checkbox" name="user" value="3">
    <input type="checkbox" name="user" value="4">
    <input type="checkbox" name="user" value="5">

    <input type="submit" name="b1" value="ADD">
    <input type="submit" name="b1" value="MODIFY">
    <input type="submit" name="b1" value="DELETE">
</form>
</code>```

(the checkbox value must be the unique user ID)

Then use request.getParameterValues() in your AddUserServlet:

```<code>String b1 = request.getParameter("b1");
if ("DELETE".equals(b1)) {
    String[] users = request.getParameterValues("user");
    // ...
}
</code>```

The users array will contain the checked values (1, 2, 3, 4 and/or 5).

Title: passing data from javascript to servlet

Body:
I have values of checkbox and as soon as I click delete the values and the type must be sent to a servlet called DeleteServlet. Please help me how to send the values?

    <%String user=request.getParameter("Users"); %>

    <%

    String User[]=user.trim().split(" ");

    for(int i=0;i<User.length;i++){%>

        <form name='list' action='AddUserServlet'>

     <%  out.println("<input type='checkbox' name='user" + i + "' value='"+ User[i] + "' onClick='return get_check_value(this)'>" + User[i]+ "</input>" ); %>

    </form>

    <%}%>

        <input type="submit" value="ADD" name="b1" >
        <input type="submit" value="MODIFY" name="b1">
     <input type="submit" value="DELETE" name="b1" onClick="return doDelete(value)" >

I tried this  "document.list.user.value" in an alert box it comes as undefined object. To send to a servlet I tried the following line but nothing is read

chk_val=chkbox.value;
document.add.action = "AddUserServlet?type=delete&name="+chk_val;
 document.add.submit();

Body:
You don't need Javascript for this at all.

Just change your code so that the HTML form is generated as follows:

<form action="AddUserServlet" method="post">
    <input type="checkbox" name="user" value="1">
    <input type="checkbox" name="user" value="2">
    <input type="checkbox" name="user" value="3">
    <input type="checkbox" name="user" value="4">
    <input type="checkbox" name="user" value="5">

    <input type="submit" name="b1" value="ADD">
    <input type="submit" name="b1" value="MODIFY">
    <input type="submit" name="b1" value="DELETE">
</form>

(the checkbox value must be the unique user ID)

Then use request.getParameterValues() in your AddUserServlet:

String b1 = request.getParameter("b1");
if ("DELETE".equals(b1)) {
    String[] users = request.getParameterValues("user");
    // ...
}

The users array will contain the checked values (1, 2, 3, 4 and/or 5).


来源: stackexchange

问:
How to create an edge list from pandas dataframe?
I have a pandas dataframe (df) of the form-

```<code>    Col1
A  [Green,Red,Purple]
B  [Red, Yellow, Blue]
C  [Brown, Green, Yellow, Blue]
</code>```

I need to convert this to an edge list i.e. a dataframe of the form:

```<code>Source    Target    Weight
  A         B         1
  A         C         1
  B         C         2
</code>```

EDIT
Note that the new dataframe has rows equal to the total number of possible pairwise combinations. Also, to compute the 'Weight' column, we simply find the intersection between the two lists. For instance, for B&C, the elements share two colors: Blue and Yellow. Therefore, the 'Weight' for the corresponding row is 2.

What is the fastest way to do this? The original dataframe contains about 28,000 elements.

答:
get an array of sets

get pairwise indices representing all combinations using np.triu_indices

use & operator to get the pairwise intersections and get lengths via a comprehension

```<code>c = df.Col1.apply(set).values

i, j = np.triu_indices(c.size, 1)

pd.DataFrame(dict(
        Source=df.index[i],
        Target=df.index[j],
        Weight=[len(s) for s in c[i] & c[j]]
    ))

  Source Target  Weight
0      A      B       1
1      A      C       1
2      B      C       2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a pandas dataframe (df) of the form-

    Col1
A  [Green,Red,Purple]
B  [Red, Yellow, Blue]
C  [Brown, Green, Yellow, Blue]

I need to convert this to an edge list i.e. a dataframe of the form:

Source    Target    Weight
  A         B         1
  A         C         1
  B         C         2

EDIT
Note that the new dataframe has rows equal to the total number of possible pairwise combinations. Also, to compute the 'Weight' column, we simply find the intersection between the two lists. For instance, for B&C, the elements share two colors: Blue and Yellow. Therefore, the 'Weight' for the corresponding row is 2.

What is the fastest way to do this? The original dataframe contains about 28,000 elements.

Body:
get an array of sets

get pairwise indices representing all combinations using np.triu_indices

use & operator to get the pairwise intersections and get lengths via a comprehension

c = df.Col1.apply(set).values

i, j = np.triu_indices(c.size, 1)

pd.DataFrame(dict(
        Source=df.index[i],
        Target=df.index[j],
        Weight=[len(s) for s in c[i] & c[j]]
    ))

  Source Target  Weight
0      A      B       1
1      A      C       1
2      B      C       2


问:
Try Catch doesnt try the second condition
i have 2 condition inside try which is ||. The first condition will not try to catch. But the second one, it does.

```<code>    private void ButtonExecute_Click(object sender, EventArgs e)
    {
        try
        {
            if (fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)
            {
                SearchingPhoto();
            }
        }
        catch(NullReferenceException)
        { return; }
    }
</code>```

Method in try will run if and only if fbd[0].SelectedPath is not equal to null.

case 1: if(fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)OK

case 2: if(fbd[0].SelectedPath == null || fbd[1].SelectedPath != null)not OK

case 3: if(fbd[0].SelectedPath != null || fbd[1].SelectedPath == null)OK

case 4: if(fbd[0].SelectedPath == null || fbd[1].SelectedPath == null)not OK

//i want to run a method inside case 2:

答:
You are not getting a NullReferenceException, that's why the catch does not "catch".

You will receive null reference exception if you are using a property of that instance and it is null for example:

```<code>fbd[0].SelectedPath.SomeProp //Will cause exception if fbd[0].SelectedPath is null
</code>```

If you want to find out if one of them is null why not simply:

```<code>fbd[0].SelectedPath == null || fbd[1].SelectedPath == null
</code>```

Of course fbd[i] can also be null and you will get exception if you are trying to read the property SelectedPath from it.

Added:

Always good practice is to check if the instance you are using is not null if there is a chance it will be.

```<code>if (fbd[0]!=null && fbd[0].SelectedPath != null ||
    fbd[1]!=null && fbd[1].SelectedPath != null)
    {
      //Safe to use
    }
</code>```

Body:
i have 2 condition inside try which is ||. The first condition will not try to catch. But the second one, it does.

    private void ButtonExecute_Click(object sender, EventArgs e)
    {
        try
        {
            if (fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)
            {
                SearchingPhoto();
            }
        }
        catch(NullReferenceException)
        { return; }
    }

Method in try will run if and only if fbd[0].SelectedPath is not equal to null.

case 1: if(fbd[0].SelectedPath != null || fbd[1].SelectedPath != null)OK

case 2: if(fbd[0].SelectedPath == null || fbd[1].SelectedPath != null)not OK

case 3: if(fbd[0].SelectedPath != null || fbd[1].SelectedPath == null)OK

case 4: if(fbd[0].SelectedPath == null || fbd[1].SelectedPath == null)not OK

//i want to run a method inside case 2:

Body:
You are not getting a NullReferenceException, that's why the catch does not "catch".

You will receive null reference exception if you are using a property of that instance and it is null for example:

fbd[0].SelectedPath.SomeProp //Will cause exception if fbd[0].SelectedPath is null

If you want to find out if one of them is null why not simply:

fbd[0].SelectedPath == null || fbd[1].SelectedPath == null

Of course fbd[i] can also be null and you will get exception if you are trying to read the property SelectedPath from it.

Added:

Always good practice is to check if the instance you are using is not null if there is a chance it will be.

if (fbd[0]!=null && fbd[0].SelectedPath != null ||
    fbd[1]!=null && fbd[1].SelectedPath != null)
    {
      //Safe to use
    }


问:
How to make an object move in relation to image_angle?
Note: I'm using GameMaker 1.4, not 2. I don't know if this makes a difference, but I'm pointing it out just in case.

Okay, so I'm having an issue in my GameMaker game where I'm making an object move up and down in relation to image_angle. For some reason, it really wants to move across the y axis as normal and completetly disregards the image_angle. This is really annoying and could change the game entirely if not fixed.

My code is for the step event is:

```<code>// Mouse controls.
image_angle = point_direction(x, y, mouse_x, mouse_y);

if(keyboard_check(ord('W')))
{
    y -= playerSpeed;
}

if(keyboard_check(ord('S')))
{
    y += playerSpeed;
}
</code>```

My code for the create event is:

```<code>globalvar fuelRemaining;
fuelRemaining = 60;

playerSpeed = 3;
</code>```

答:
@Gamio code is almost correct (should be _released instead of _release, confused the sign for W and S keys). Here are few improvements:

```<code>image_angle = point_direction(x, y, mouse_x, mouse_y);
direction = image_angle;

if point_distance(x, y, mouse_x, mouse_y) < spd
{
   speed = 0;
}
else
{
    var spd = 0;

    if keyboard_check(ord("W"))
        spd += playerSpeed; // If pressed both W and S, then will stop

    if keyboard_check(ord("S"))
        spd -= playerSpeed;

    speed = spd;

    if keyboard_check_released(ord("W")) or keyboard_check_released(ord("S"))
        speed = 0;
}
</code>```

Place the code in Step End event (not Step).

If you want change coords directly, without speed, it is also possible, but little more difficult (you need calculate both x and y deltas using lengthdir_x and lengthdir_y functions and then add these deltas to current coords).

Body:
Note: I'm using GameMaker 1.4, not 2. I don't know if this makes a difference, but I'm pointing it out just in case.

Okay, so I'm having an issue in my GameMaker game where I'm making an object move up and down in relation to image_angle. For some reason, it really wants to move across the y axis as normal and completetly disregards the image_angle. This is really annoying and could change the game entirely if not fixed.

My code is for the step event is:

// Mouse controls.
image_angle = point_direction(x, y, mouse_x, mouse_y);

if(keyboard_check(ord('W')))
{
    y -= playerSpeed;
}

if(keyboard_check(ord('S')))
{
    y += playerSpeed;
}

My code for the create event is:

globalvar fuelRemaining;
fuelRemaining = 60;

playerSpeed = 3;

Body:
@Gamio code is almost correct (should be _released instead of _release, confused the sign for W and S keys). Here are few improvements:

image_angle = point_direction(x, y, mouse_x, mouse_y);
direction = image_angle;

if point_distance(x, y, mouse_x, mouse_y) < spd
{
   speed = 0;
}
else
{
    var spd = 0;

    if keyboard_check(ord("W"))
        spd += playerSpeed; // If pressed both W and S, then will stop

    if keyboard_check(ord("S"))
        spd -= playerSpeed;

    speed = spd;

    if keyboard_check_released(ord("W")) or keyboard_check_released(ord("S"))
        speed = 0;
}

Place the code in Step End event (not Step).

If you want change coords directly, without speed, it is also possible, but little more difficult (you need calculate both x and y deltas using lengthdir_x and lengthdir_y functions and then add these deltas to current coords).


问:
Turbo C++ compile error "too many types in declaration"
whenever I compile this program, I get an error saying "Too many types in decleration on line 13". I do not see any possible syntax errors but still I am facing this issue.

```<code>#include<iostream.h>
#include<conio.h>

class currency
{
    private:
    int rupee,paise;
    int total;
    public:
    void getdata(int r,int p);
    void display();

}
void currency::getdata(int r, int p){

    rupee=r;
    paise=p;
    total=r*100+p;

}
void currency::display(){

cout<<rupee<<" Rupees"<<" and "<<paise<<"Paise"<<endl;
cout<<"Converted value="<<total;

}

int main(){

    currency c;
        c.getdata(5,25);
        c.display();
        getch();
        return 0;

}
</code>```

答:
At a guess, I'd say the root problem is the missing semicolon after the body of class currency.

Recall than in C/C++, you can define an object like as part of a class or struct definition, like this:

```<code>struct foo
{
    int bar;
} FooObj;
</code>```

This creates an variable FooObj of type struct foo.

So in your code, the following:

```<code>class currency
{
    /* ... */
}
void currency::getdata(int r, int p){
    /* ... */
}
</code>```

... is equivalent to this:

```<code>class currency
{
    /* ... */
} void currency::getdata(int r, int p){
    /* ... */
}
</code>```

...which is equivalent to this:

```<code>class currency
{
    /* ... */
};

currency void currency::getdata(int r, int p){
    /* ... */
}
</code>```

So it looks like you've given function getdata two return types, which would explain the error.

ContentLicense: CC BY-SA 4.0

Body:
whenever I compile this program, I get an error saying "Too many types in decleration on line 13". I do not see any possible syntax errors but still I am facing this issue.

#include<iostream.h>
#include<conio.h>

class currency
{
    private:
    int rupee,paise;
    int total;
    public:
    void getdata(int r,int p);
    void display();

}
void currency::getdata(int r, int p){

    rupee=r;
    paise=p;
    total=r*100+p;

}
void currency::display(){

cout<<rupee<<" Rupees"<<" and "<<paise<<"Paise"<<endl;
cout<<"Converted value="<<total;

}

int main(){

    currency c;
        c.getdata(5,25);
        c.display();
        getch();
        return 0;

}

Body:
At a guess, I'd say the root problem is the missing semicolon after the body of class currency.

Recall than in C/C++, you can define an object like as part of a class or struct definition, like this:

struct foo
{
    int bar;
} FooObj;

This creates an variable FooObj of type struct foo.

So in your code, the following:

class currency
{
    /* ... */
}
void currency::getdata(int r, int p){
    /* ... */
}

... is equivalent to this:

class currency
{
    /* ... */
} void currency::getdata(int r, int p){
    /* ... */
}

...which is equivalent to this:

class currency
{
    /* ... */
};

currency void currency::getdata(int r, int p){
    /* ... */
}

So it looks like you've given function getdata two return types, which would explain the error.


问:
C program to input date as dd-mm-yy and display date as January 3rd, 1999
I'm trying to write a program in C, read data from the keyboard in the form dd-mm-yy and want to display the date as January 3rd, 1999.
How can i do it?

答:
Try it, hope helps to solve your problem

```<code>#include <stdio.h>
#include <time.h>

int main()
{
   struct tm tm_info;
   char buffer[255];
   char days[32][5] = {" ","1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th","21st","22nd","23rd","24th","25th","26th","27th","28th","29th","30th","31st"};

    strptime("09-07-2017", "%d-%m-%Y ", &tm_info);
    strftime(buffer, 26, "%B", &tm_info);
    printf("%s ",buffer);

    strftime(buffer, 26, "%d", &tm_info);
    int day = int(buffer[0]-'0')*10 + int(buffer[1]-'0');
    printf("%s, ",days[day]);

    strftime(buffer, 26, "%Y", &tm_info);
    printf("%s ",buffer);
}
</code>```

Body:
Try it, hope helps to solve your problem

#include <stdio.h>
#include <time.h>

int main()
{
   struct tm tm_info;
   char buffer[255];
   char days[32][5] = {" ","1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th","21st","22nd","23rd","24th","25th","26th","27th","28th","29th","30th","31st"};

    strptime("09-07-2017", "%d-%m-%Y ", &tm_info);
    strftime(buffer, 26, "%B", &tm_info);
    printf("%s ",buffer);

    strftime(buffer, 26, "%d", &tm_info);
    int day = int(buffer[0]-'0')*10 + int(buffer[1]-'0');
    printf("%s, ",days[day]);

    strftime(buffer, 26, "%Y", &tm_info);
    printf("%s ",buffer);
}


问:
Adding required to HTML input when checkbox is checked
I have an hidden div which will contain some HTML inputs which some are needed to be required as part of a form. the div is visible by checking the checkbox and the code looks like this:

$(function() {
  var checkbox = $("#checkbox01");
  var hidden = $("#div01");
  hidden.hide();
  checkbox.change(function() {
    if (checkbox.is(':checked')) {
      hidden.show();
    } else {
      hidden.hide();
      $("#username").val("");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label><input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label>
<div id="div01">
  <input name="username" type="text" required>
</div></code>```

You can see the code in action on JSfiddle
As you can see the div is hidden when the checkbox is unchecked and also the username is cleaned when the div is hidden (checkbox unchecked).

How can I make the required be added to HTML only if checkbox is checked, so user won't get prompt to enter value when the div is hidden by Jquery... ?

答:
Try this: (JavaScript)

$(function() {
  var checkbox = $("#checkbox01");
  var hidden = $("#div01");
  hidden.hide();
  checkbox.change(function() {

    if (checkbox.is(':checked')) {
      hidden.show();

      document.getElementById("username").required = true;
    } else {
      hidden.hide();
      $("#username").val("");
      document.getElementById("username").required = false;
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label>
<div id="div01">
  <input name="username" id="username" type="text">
</div></code>```

jQuery

```<code>$("#username").prop('required',true);          //to add
$("#username").prop('required',false);         //to remove
</code>```

Body:
I have an hidden div which will contain some HTML inputs which some are needed to be required as part of a form. the div is visible by checking the checkbox and the code looks like this:

$(function() {
  var checkbox = $("#checkbox01");
  var hidden = $("#div01");
  hidden.hide();
  checkbox.change(function() {
    if (checkbox.is(':checked')) {
      hidden.show();
    } else {
      hidden.hide();
      $("#username").val("");
    }
  });
});

<input id="checkbox01" name="checkbox01" type="checkbox">show/hide

  <input name="username" type="text" required>

You can see the code in action on JSfiddle
As you can see the div is hidden when the checkbox is unchecked and also the username is cleaned when the div is hidden (checkbox unchecked).

How can I make the required be added to HTML only if checkbox is checked, so user won't get prompt to enter value when the div is hidden by Jquery... ?

Body:
Try this: (JavaScript)

$(function() {
  var checkbox = $("#checkbox01");
  var hidden = $("#div01");
  hidden.hide();
  checkbox.change(function() {

    if (checkbox.is(':checked')) {
      hidden.show();

      document.getElementById("username").required = true;
    } else {
      hidden.hide();
      $("#username").val("");
      document.getElementById("username").required = false;
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label>
<div id="div01">
  <input name="username" id="username" type="text">
</div>

jQuery

$("#username").prop('required',true);          //to add
$("#username").prop('required',false);         //to remove


答:
I guess you missed a semicolon after the class definition;
Classes are not like functions, but similar to struct definitions in C, you need to put a semicolon after the <code>}</code>.
Such as: </p>

```<code>class A {};
</code>```

Title: Turbo C++ compile error "too many types in declaration"

Body:
I guess you missed a semicolon after the class definition;
Classes are not like functions, but similar to struct definitions in C, you need to put a semicolon after the }.
Such as:

class A {};


问:
Layers within a layer in Caffe
I have a custom loss layer which I wrote, this layer applies softmax and sigmoid activation to part of the bottom[0] blob.

```<code>Ex: `bottom[0]` is of shape (say): `[20, 7, 7, 50]` (`NHWC` format)
I would like to apply `softmax` to `[20, 7, 7, 25]` (first 25 channels) and
`sigmoid` to `[20, 7, 7, 1]` (just one channel) and the remaining 24 channels are taken in as it is.
</code>```

How do I effectively allocate memory to the input blobs of these two softmax and sigmoid layers and also free this memory ?

答:
Instead of allocating data internally, you can simply use a "Slice" layer externally and slice the input blob using caffe "off-the-shelf" layers:

```<code>layer {
  name: "slice"
  type: "Slice"
  bottom: "input_to_loss"
  top: "to_softmax"
  top: "to_sigmoid"
  top: "leftovers"
  slice_param {
    axis: -1  # slice the last axis
    slice_point: 25
    slice_point: 26
  }
}
</code>```

Title: Layers within a layer in Caffe

Body:
I have a custom loss layer which I wrote, this layer applies softmax and sigmoid activation to part of the bottom[0] blob.

Ex: `bottom[0]` is of shape (say): `[20, 7, 7, 50]` (`NHWC` format)
I would like to apply `softmax` to `[20, 7, 7, 25]` (first 25 channels) and
`sigmoid` to `[20, 7, 7, 1]` (just one channel) and the remaining 24 channels are taken in as it is.

How do I effectively allocate memory to the input blobs of these two softmax and sigmoid layers and also free this memory ?

Body:
Instead of allocating data internally, you can simply use a "Slice" layer externally and slice the input blob using caffe "off-the-shelf" layers:

layer {
  name: "slice"
  type: "Slice"
  bottom: "input_to_loss"
  top: "to_softmax"
  top: "to_sigmoid"
  top: "leftovers"
  slice_param {
    axis: -1  # slice the last axis
    slice_point: 25
    slice_point: 26
  }
}


问:
cURL error 60: SSL certificate prblm: unable to get local issuer certificate
I want to collect a list of videos uploaded on a specific channel using the YouTube data API. However, before implementing online I am trying to get my code running on an offline environment (WAMPserver, PHP 5.5.12, Apache 2.4.9). I am using the following code:

```<code>require_once 'google-api-php-client-2.0.0-RC5/vendor/autoload.php';

$client = new Google_Client();
$client->setApplicationName("SRC_Thor");
$client->setDeveloperKey("xxxxxxxxxxx");

$youtube = new Google_Service_YouTube($client);

$channelResponse = $youtube->channels->listChannels('contentDetails', []);
var_dump($channelResponse);
</code>```

However it gives the following error:

Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException' with message 'cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)'

I have tried adding the latest version of cacert.pem as most topics on SO offer as a solution, however to no avail.

答:
for the essence of development and testing, You have two options to a quick fix

Use

```<code>$client = new GuzzleHttp\Client();
$request = $client->request('GET',$url, ['verify' => false]); //where $url is your http address
</code>```

follow @Pham Huy Anh answer's above then do this

```<code>$client = new GuzzleHttp\Client();
$request = $client->request('GET',$url, ['verify' => 'C:\xampp\php\extras\ssl\cacert.pem']);
</code>```

Hope it helps someone.

Body:
I want to collect a list of videos uploaded on a specific channel using the YouTube data API. However, before implementing online I am trying to get my code running on an offline environment (WAMPserver, PHP 5.5.12, Apache 2.4.9). I am using the following code:

require_once 'google-api-php-client-2.0.0-RC5/vendor/autoload.php';

$client = new Google_Client();
$client->setApplicationName("SRC_Thor");
$client->setDeveloperKey("xxxxxxxxxxx");

$youtube = new Google_Service_YouTube($client);

$channelResponse = $youtube->channels->listChannels('contentDetails', []);
var_dump($channelResponse);

However it gives the following error:

Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException' with message 'cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)'

I have tried adding the latest version of cacert.pem as most topics on SO offer as a solution, however to no avail.

Body:
for the essence of development and testing, You have two options to a quick fix

Use

$client = new GuzzleHttp\Client();
$request = $client->request('GET',$url, ['verify' => false]); //where $url is your http address

follow @Pham Huy Anh answer's above then do this

$client = new GuzzleHttp\Client();
$request = $client->request('GET',$url, ['verify' => 'C:\xampp\php\extras\ssl\cacert.pem']);

Hope it helps someone.


问:
Print only each character and number once
I want to not use HashMap or Set when printing Duplicate characters in a String. But in solution I'm using I'm printing all the characters even if they are duplicates. I want to print each character once and with number of times it occurs in the string. Here's my example:

```<code>  public static void printDups(String s1) {
    int count = 0;
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s1.length(); j++) {
            if (s1.charAt(i) == s1.charAt(j)) {
                count++;
            }
        }

        System.out.println(s1.charAt(i) + " --> " + count);

        count = 0;
    }
}
</code>```

public static void main(String[] args) {
    printDups("AABBCCDDD){}
}

And this is the output:

```<code>A --> 2
A --> 2
B --> 2
B --> 2
C --> 2
C --> 2
D --> 3
D --> 3
</code>```

I want to print it like that:

```<code>A --> 2
B --> 2
C --> 2
D --> 3
</code>```

I know I can add this: if (s1.charAt(i) != s1.charAt(i+1))         System.out.println(s1.charAt(i) + " --> " + count);
But then I'll have StringIndexOutOfBoundsException:

If I change my loop to this for (int i = 0; i < s1.length()-1; i++)

It'll skip the last character in the string.

How can I achieve this?

答:
I know I can add this: if (s1.charAt(i) != s1.charAt(i+1))         System.out.println(s1.charAt(i) + " --> " + count); But then I'll have StringIndexOutOfBoundsException:

What you can do is add another condition to it so it does not go out of bounds.

if ( s1.length() < (i+1) && s1.charAt(i) != s1.charAt(i+1))

Body:
I want to not use HashMap or Set when printing Duplicate characters in a String. But in solution I'm using I'm printing all the characters even if they are duplicates. I want to print each character once and with number of times it occurs in the string. Here's my example:

  public static void printDups(String s1) {
    int count = 0;
    for (int i = 0; i < s1.length(); i++) {
        for (int j = 0; j < s1.length(); j++) {
            if (s1.charAt(i) == s1.charAt(j)) {
                count++;
            }
        }

        System.out.println(s1.charAt(i) + " --> " + count);

        count = 0;
    }
}

public static void main(String[] args) {
    printDups("AABBCCDDD){}
}

And this is the output:

A --> 2
A --> 2
B --> 2
B --> 2
C --> 2
C --> 2
D --> 3
D --> 3

I want to print it like that:

A --> 2
B --> 2
C --> 2
D --> 3

I know I can add this: if (s1.charAt(i) != s1.charAt(i+1))         System.out.println(s1.charAt(i) + " --> " + count);
But then I'll have StringIndexOutOfBoundsException:

If I change my loop to this for (int i = 0; i < s1.length()-1; i++)

It'll skip the last character in the string.

How can I achieve this?


答:
Add required attribute on check and remove it when unchecked.

```<code>    $(function() {
      var checkbox = $("#checkbox01");
      var hidden = $("#div01");
      hidden.hide();
      checkbox.change(function() {
        if (checkbox.is(':checked')) {
          hidden.show();
          $("#name").attr('required'); //add required attr
        } else {
          hidden.hide();
          $("#username").val("");
          $("#name").removeAttr('required'); // remove required attr
        }
      });
    });
</code>```

Here is your fiddle https://jsfiddle.net/xj7ps2La/

Title: Adding required to HTML input when checkbox is checked

Body:
Add required attribute on check and remove it when unchecked.

    $(function() {
      var checkbox = $("#checkbox01");
      var hidden = $("#div01");
      hidden.hide();
      checkbox.change(function() {
        if (checkbox.is(':checked')) {
          hidden.show();
          $("#name").attr('required'); //add required attr
        } else {
          hidden.hide();
          $("#username").val("");
          $("#name").removeAttr('required'); // remove required attr
        }
      });
    });

Here is your fiddle https://jsfiddle.net/xj7ps2La/


问:
How do I order a mixed text and integer field in a pivot table in Google Sheets?
Let's say that we have two columns on a sheet:

```<code>Name     Room
-------------
Steve    A1
Jill     A1
Sam      A1
Steve    A2
...
Lisa     A10
Sally    A11
Jim      A11
</code>```

My actual dataset has up to a hundred of these rooms.

The issue I'm running into is with pivot tables. When I want to get a list of rooms and the count (counta is the one I'm using) it works, but the order is not what I wanted. It comes out as:

```<code>Room     Count
--------------
A1       3
A10      1
A11      2
...
A2       1
</code>```

I guess I can kind of see why it would be doing that. I'd much rather have it list it out in order. A1, A2, A3... A10, A11, A12, etc.

Is there an easy way to do this without some sort of data manipulation?

答:
I suggest you transform the string elements into number values using a lookup table.
I've created a sample spreadsheet here.

The input data in the 'input' sheet has the keys as you described.

The next sheet is the "lookup table" to translate each key into a value number. I suggest choosing large numbers to leave room for future intermediate numbers if needed

Pivot 1 is based on the original data as you described

Pivot 2 is based on the re-calculated room name using the lookup table.

The formula I used for the re-calculation is:
=VALUE(SUBSTITUTE(A2,MID(A2,1,1),VLOOKUP(MID(A2,1,1),'Lookup table'!$A$1:$B$2,2)))

I was a little lazy with the string lookup in the original name (MID), assuming your string is the first character and is 1 character long. This can be mended specifically with pattern matching.

Body:
Let's say that we have two columns on a sheet:

Name     Room
-------------
Steve    A1
Jill     A1
Sam      A1
Steve    A2
...
Lisa     A10
Sally    A11
Jim      A11

My actual dataset has up to a hundred of these rooms.

The issue I'm running into is with pivot tables. When I want to get a list of rooms and the count (counta is the one I'm using) it works, but the order is not what I wanted. It comes out as:

Room     Count
--------------
A1       3
A10      1
A11      2
...
A2       1

I guess I can kind of see why it would be doing that. I'd much rather have it list it out in order. A1, A2, A3... A10, A11, A12, etc.

Is there an easy way to do this without some sort of data manipulation?


问:
Grouping and summarizing by keeping other columns in R
I have a dataframe which I am grouping using the group_by function, and summarizing it with using the summarize function in R.

```<code>MM_group<-group_by(SYC,Method,Maturity)
</code>```

My dataset looks like this,

```<code> Year           Group  County Seed.Brand Seed.Variety Seed.Maturity
1 2014 Group 0 No-till Yankton     Asgrow       AG0832           0.8
2 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
3 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
4 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
5 2014 Group 0 No-till   Brown    Pioneer        90Y90           0.9
6 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9

Yield  Method Maturity digits
1 73.23 No-till        0      0
2 65.14 No-till        0      0
3 63.63 No-till        0      0
4 61.57 No-till        0      0
5 60.20 No-till        0      0
</code>```

I am grouping by Method & Maturity. I am trying to get County and Year for maximum yield for the Method & Maturity combination.

I have done the following:

```<code>summarize(MM_group,Max_Yield=max(Yield))

       Method Maturity Max_Yield
           <chr>    <chr>     <dbl>
1      Irrigated        0    69.600
2      Irrigated        1    86.013
3      Irrigated        2    88.750
4      Irrigated        3    79.650
5        No-till        0    79.470
6        No-till        1    79.856
7        No-till        2    85.860
8        No-till        3    68.530
9  Non-irrigated        0    83.210
10 Non-irrigated        1    81.916
11 Non-irrigated        2   103.740
12 Non-irrigated        3    94.410
</code>```

But, this doesn't give me the county name and year. I know I can use cbind or joins to get that data but wondering if there is another easier way of doing this.

Expected Output:

```<code>          Method Maturity Max_Yield  Year                  Group
           <chr>    <chr>     <dbl> <int>                 <fctr>
1      Irrigated        0    69.600  2012 Group 0 or 1 Irrigated
2      Irrigated        1    86.013  2012 Group 0 or 1 Irrigated
3      Irrigated        2    88.750  2013 Group 2 or 3 Irrigated
4      Irrigated        3    79.650  2013 Group 2 or 3 Irrigated
5        No-till        0    79.470  2013        Group 0 No-till
6        No-till        1    79.856  2012        Group 1 No-till
7        No-till        2    85.860  2013        Group 2 No-till
8        No-till        3    68.530  2014        Group 3 No-till
9  Non-irrigated        0    83.210  2013  Group 0 Non-irrigated
10 Non-irrigated        1    81.916  2012  Group 1 Non-irrigated
11 Non-irrigated        2   103.740  2014  Group 2 Non-irrigated
12 Non-irrigated        3    94.410  2014  Group 3 Non-irrigated
</code>```

答:
We can use</p>

```<code>SYC %>%
   group_by(Method, Maturity) %>%
   slice(which.max(Yield)) %>%
   rename(Max_Yield = Yield) %>%
   select(Method, Maturity, Max_Yield, Year, Group)
</code>```

Body:
I have a dataframe which I am grouping using the group_by function, and summarizing it with using the summarize function in R.

MM_group<-group_by(SYC,Method,Maturity)

My dataset looks like this,

 Year           Group  County Seed.Brand Seed.Variety Seed.Maturity
1 2014 Group 0 No-till Yankton     Asgrow       AG0832           0.8
2 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
3 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
4 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9
5 2014 Group 0 No-till   Brown    Pioneer        90Y90           0.9
6 2014 Group 0 No-till   Brown     Asgrow       AG0934           0.9

Yield  Method Maturity digits
1 73.23 No-till        0      0
2 65.14 No-till        0      0
3 63.63 No-till        0      0
4 61.57 No-till        0      0
5 60.20 No-till        0      0

I am grouping by Method & Maturity. I am trying to get County and Year for maximum yield for the Method & Maturity combination.

I have done the following:

summarize(MM_group,Max_Yield=max(Yield))

       Method Maturity Max_Yield
           <chr>    <chr>     <dbl>
1      Irrigated        0    69.600
2      Irrigated        1    86.013
3      Irrigated        2    88.750
4      Irrigated        3    79.650
5        No-till        0    79.470
6        No-till        1    79.856
7        No-till        2    85.860
8        No-till        3    68.530
9  Non-irrigated        0    83.210
10 Non-irrigated        1    81.916
11 Non-irrigated        2   103.740
12 Non-irrigated        3    94.410

But, this doesn't give me the county name and year. I know I can use cbind or joins to get that data but wondering if there is another easier way of doing this.

Expected Output:

          Method Maturity Max_Yield  Year                  Group
           <chr>    <chr>     <dbl> <int>                 <fctr>
1      Irrigated        0    69.600  2012 Group 0 or 1 Irrigated
2      Irrigated        1    86.013  2012 Group 0 or 1 Irrigated
3      Irrigated        2    88.750  2013 Group 2 or 3 Irrigated
4      Irrigated        3    79.650  2013 Group 2 or 3 Irrigated
5        No-till        0    79.470  2013        Group 0 No-till
6        No-till        1    79.856  2012        Group 1 No-till
7        No-till        2    85.860  2013        Group 2 No-till
8        No-till        3    68.530  2014        Group 3 No-till
9  Non-irrigated        0    83.210  2013  Group 0 Non-irrigated
10 Non-irrigated        1    81.916  2012  Group 1 Non-irrigated
11 Non-irrigated        2   103.740  2014  Group 2 Non-irrigated
12 Non-irrigated        3    94.410  2014  Group 3 Non-irrigated

Body:
We can use

SYC %>%
   group_by(Method, Maturity) %>%
   slice(which.max(Yield)) %>%
   rename(Max_Yield = Yield) %>%
   select(Method, Maturity, Max_Yield, Year, Group)


问:
Animate the rotation of the Marker in google map v2
i am using google maps v2.
i have a marker on map, this marker changes rotation every while.
I want to animate the rotation of my maker to rotate smoothly.
Can anyone help please </p>

答:
```<code>boolean isRotating = false;
public void rotateMarker(final Marker marker, final float toRotation) {
    if(!isRotating) {
        isRotating = true;
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        final float startRotation = marker.getRotation();
        final long duration = 1000;
        float deltaRotation = Math.abs(toRotation - startRotation) % 360;
        final float rotation = (deltaRotation > 180 ? 360 - deltaRotation : deltaRotation) *
                ((toRotation - startRotation >= 0 && toRotation - startRotation <= 180) || (toRotation - startRotation <= -180 && toRotation - startRotation >= -360) ? 1 : -1);

        final LinearInterpolator interpolator = new LinearInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed / duration);
                marker.setRotation((startRotation + t * rotation) % 360);
                if (t < 1.0) {
                    // Post again 16ms later.
                    handler.postDelayed(this, 16);
                } else {
                    isRotating = false;
                }
            }
        });
    }
}
</code>```

This is how I rotate the marker, I don't know this is the best code or not.
But I think it will prevent wrong rotation. EDIT: Add var isRotating (Thanks @Trần Văn Huy)

Update Explanation:

Body:
boolean isRotating = false;
public void rotateMarker(final Marker marker, final float toRotation) {
    if(!isRotating) {
        isRotating = true;
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        final float startRotation = marker.getRotation();
        final long duration = 1000;
        float deltaRotation = Math.abs(toRotation - startRotation) % 360;
        final float rotation = (deltaRotation > 180 ? 360 - deltaRotation : deltaRotation) *
                ((toRotation - startRotation >= 0 && toRotation - startRotation <= 180) || (toRotation - startRotation <= -180 && toRotation - startRotation >= -360) ? 1 : -1);

        final LinearInterpolator interpolator = new LinearInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed / duration);
                marker.setRotation((startRotation + t * rotation) % 360);
                if (t < 1.0) {
                    // Post again 16ms later.
                    handler.postDelayed(this, 16);
                } else {
                    isRotating = false;
                }
            }
        });
    }
}

This is how I rotate the marker, I don't know this is the best code or not.
But I think it will prevent wrong rotation. EDIT: Add var isRotating (Thanks @Trần Văn Huy)

Update Explanation:


问:
How to expand property references in jar resources?
I'm using Gradle to build a jar containing an xml file in META-INF. This file has a row like

```<code><property name="databasePlatform" value="${sqlDialect}" />
</code>```

to allow for different SQL databases for different environments. I want to tell gradle to expand ${sqlDialect} from the project properties.

I tried this:

```<code>jar {
    expand project.properties
}
</code>```

but it fails with a GroovyRuntimeException that seems to me like the Jar task attempts to expand properties in .class files as well. So then I tried

```<code>jar {
    from(sourceSets.main.resources) {
        expand project.properties
    }
}
</code>```

which does not throw the above exception, but instead results in all resources being copied twice - once with property expansion and once without. I managed to work around this with

```<code>jar {
    eachFile {
        if(it.relativePath.segments[0] in ['META-INF']) {
            expand project.properties
        }
    }
}
</code>```

which does what I want, since in my use case I only need to expand properties of files in the META-INF directory. But this feels like a pretty ugly hack, is there a better way to do this?

答:
here is what worked for me (Gradle 4.0.1) in a multi-module project:

in /webshared/build.gradle:

```<code>import org.apache.tools.ant.filters.*

afterEvaluate {
    configure(allProcessResourcesTasks()) {
        filter(ReplaceTokens,
                tokens: [myAppVersion: MY_APP_VERSION])
    }
}

def allProcessResourcesTasks() {
    sourceSets*.processResourcesTaskName.collect {
        tasks[it]
    }
}
</code>```

and my MY_APP_VERSION variable is defined in top-level build.gradle file:

```<code>ext {

    // application release version.
    // it is used in the ZIP file name and is shown in "About" dialog.
    MY_APP_VERSION = "1.0.0-SNAPSHOT"
}
</code>```

and my resource file is in /webshared/src/main/resources/version.properties :

```<code># Do NOT set application version here, set it in "build.gradle" file
# This file is transformed/populated during the Gradle build.
version=@myAppVersion@
</code>```

Body:
I'm using Gradle to build a jar containing an xml file in META-INF. This file has a row like

<property name="databasePlatform" value="${sqlDialect}" />

to allow for different SQL databases for different environments. I want to tell gradle to expand ${sqlDialect} from the project properties.

I tried this:

jar {
    expand project.properties
}

but it fails with a GroovyRuntimeException that seems to me like the Jar task attempts to expand properties in .class files as well. So then I tried

jar {
    from(sourceSets.main.resources) {
        expand project.properties
    }
}

which does not throw the above exception, but instead results in all resources being copied twice - once with property expansion and once without. I managed to work around this with

jar {
    eachFile {
        if(it.relativePath.segments[0] in ['META-INF']) {
            expand project.properties
        }
    }
}

which does what I want, since in my use case I only need to expand properties of files in the META-INF directory. But this feels like a pretty ugly hack, is there a better way to do this?

Body:
here is what worked for me (Gradle 4.0.1) in a multi-module project:

in /webshared/build.gradle:

import org.apache.tools.ant.filters.*

afterEvaluate {
    configure(allProcessResourcesTasks()) {
        filter(ReplaceTokens,
                tokens: [myAppVersion: MY_APP_VERSION])
    }
}

def allProcessResourcesTasks() {
    sourceSets*.processResourcesTaskName.collect {
        tasks[it]
    }
}

and my MY_APP_VERSION variable is defined in top-level build.gradle file:

ext {

    // application release version.
    // it is used in the ZIP file name and is shown in "About" dialog.
    MY_APP_VERSION = "1.0.0-SNAPSHOT"
}

and my resource file is in /webshared/src/main/resources/version.properties :

# Do NOT set application version here, set it in "build.gradle" file
# This file is transformed/populated during the Gradle build.
version=@myAppVersion@


问:
Moving data from one column to another in PostgreSQL
Sometimes, one might want to move some data from one column to another.  By moving (in constrast to copying), I mean that the new column was originally null before doing the operation, and the old column should be set to null after doing the operation.

I have a table defined as such:

CREATE TABLE photos(id BIGSERIAL PRIMARY KEY, photo1 BYTEA, photo2 BYTEA);

Suppose there is an entry in the table where photo1 contains some data, and photo2 is NULL.  I would like to make an UPDATE query wuch that photo1 becomes NULL and photo2 contains the data that was originally in photo1.

I issue the following SQL command (WHERE clause left out for brevity):

UPDATE photos SET photo2 = photo1, photo1 = NULL;

It seems to work.

I also tried it this way:

UPDATE photos SET photo1 = NULL, photo2 = photo1;

It also seems to work.

But is it guaranteed to work?  Specifically, could photo1 be set to NULL before photo2 is set to photo1, thereby causing me to end up with NULL in both columns?

As an aside, this standard UPDATE syntax seems inefficient when my BYTEAs are large, as photo2 has to be copied byte-by-byte from photo1, when a simple swapping of pointers might have sufficed.  Maybe there is a more efficient way that I don't know about?

答:
This is definitely safe.

Column-references in the UPDATE refer to the old columns, not the new values. There is in fact no way to reference a computed new value from another column.

See, e.g.

```<code>CREATE TABLE x (a integer, b integer);
INSERT INTO x (a,b) VALUES (1,1), (2,2);

UPDATE x SET a = a + 1, b = a + b;
</code>```

results in

```<code>test=> SELECT * FROM x;
 a | b
---+---
 2 | 2
 3 | 4
</code>```

... and the ordering of assignments is not significant. If you try to multiply-assign a value, you'll get

```<code>test=> UPDATE x SET a = a + 1, a = a + 1;
ERROR:  multiple assignments to same column "a"
</code>```

because it makes no sense to assign to the same column multiple times, given that both expressions reference the old tuple values, and order is not significant.

However, to avoid a full table rewrite in this case, I would just ALTER TABLE ... ALTER COLUMN ... RENAME ... then CREATE the new column with the old name.

Body:
This is definitely safe.

Column-references in the UPDATE refer to the old columns, not the new values. There is in fact no way to reference a computed new value from another column.

See, e.g.

CREATE TABLE x (a integer, b integer);
INSERT INTO x (a,b) VALUES (1,1), (2,2);

UPDATE x SET a = a + 1, b = a + b;

results in

test=> SELECT * FROM x;
 a | b
---+---
 2 | 2
 3 | 4

... and the ordering of assignments is not significant. If you try to multiply-assign a value, you'll get

test=> UPDATE x SET a = a + 1, a = a + 1;
ERROR:  multiple assignments to same column "a"

because it makes no sense to assign to the same column multiple times, given that both expressions reference the old tuple values, and order is not significant.

However, to avoid a full table rewrite in this case, I would just ALTER TABLE ... ALTER COLUMN ... RENAME ... then CREATE the new column with the old name.


问:
Displaying JSON typeMismatch error in android studio
I want to fetch the data from the database from server....but i am getting the JSON.type mismatch error............here is my code..........any help will be appreciated.. .............

```<code>public class MainActivity extends AppCompatActivity {

private static final String URL_DATA = "https://........php";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
String jsonData;

private List<ListItem> listitems;

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

    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    listitems = new ArrayList<>();

    loadRecyclerViewData();
}

    private void loadRecyclerViewData()
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading data...");
        progressDialog.show();

        StringRequest  stringRequest = new StringRequest(Request.Method.GET,
                URL_DATA,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String s)
                    {
                        progressDialog.dismiss();
                        try {
                               JSONObject jsonObject = new JSONObject(s);
                            JSONArray array = jsonObject.getJSONArray(jsonData);

                            for(int i=0;i<array.length();i++) {
                                JSONObject o = array.getJSONObject(i);
                                ListItem item = new ListItem(
                                        o.getString("Name"),
                                        o.getString("Address")
                                );

                                listitems.add(item);
                            }
                            adapter = new MyAdapter(listitems,getApplicationContext());
                            recyclerView.setAdapter(adapter);
                        }
                        catch(JSONException e)
                        {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        progressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), volleyError.getMessage(),Toast.LENGTH_LONG).show();
                    }

                    });

                    RequestQueue requestQueue = Volley.newRequestQueue(this);
                    requestQueue.add(stringRequest);

    }
}
</code>```

And here is the logcat

```<code> 07-09 10:22:10.735 25053-25053/sensor.recyclercardview2 W/System.err:
 at org.json.JSON.typeMismatch(JSON.java:111)
 07-09 10:22:10.735 25053-25053/sensor.recyclercardview2 W/System.err:
 at org.json.JSONObject.<init>(JSONObject.java:160)
 07-09 10:22:10.735 25053-25053/sensor.recyclercardview2 W/System.err:
 at org.json.JSONObject.<init>(JSONObject.java:173)
 07-09 10:22:10.735 25053-25053/sensor.recyclercardview2 W/System.err:
 at sensor.recyclercardview2.MainActivity$1.onResponse(MainActivity.java:63)
 07-09 10:22:10.735 25053-25053/sensor.recyclercardview2 W/System.err:
 at sensor.recyclercardview2.MainActivity$1.onResponse(MainActivity.java:57)
</code>```

答:
Replace these two lines

```<code>JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray(jsonData);
</code>```

with this

```<code>JSONArray array = new JSONArray(s);
</code>```

Body:
I want to fetch the data from the database from server....but i am getting the JSON.type mismatch error............here is my code..........any help will be appreciated.. .............

public class MainActivity extends AppCompatActivity {

private static final String URL_DATA = "https://........php";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
String jsonData;

private List<ListItem> listitems;

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

    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    listitems = new ArrayList<>();

    loadRecyclerViewData();
}

    private void loadRecyclerViewData()
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading data...");
        progressDialog.show();

        StringRequest  stringRequest = new StringRequest(Request.Method.GET,
                URL_DATA,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String s)
                    {
                        progressDialog.dismiss();
                        try {
                               JSONObject jsonObject = new JSONObject(s);
                            JSONArray array = jsonObject.getJSONArray(jsonData);

                            for(int i=0;i<array.length();i++) {
                                JSONObject o = array.getJSONObject(i);
                                ListItem item = new ListItem(
                                        o.getString("Name"),
                                        o.getString("Address")
                                );

                                listitems.add(item);
                            }
                            adapter = new MyAdapter(listitems,getApplicationContext());
                            recyclerView.setAdapter(adapter);
                        }
                        catch(JSONException e)
                        {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        progressDialog.dismiss();
                        Toast.makeText(getApplicationContext(), volleyError.getMessage(),Toast.LENGTH_LONG).show();
                    }

                    });

                    RequestQueue requestQueue = Volley.newRequestQueue(this);
                    requestQueue.add(stringRequest);

    }
}

And here is the logcat

 07-09 10:22:10.735 25053-25053/sensor.recyclercardview2 W/System.err:
 at org.json.JSON.typeMismatch(JSON.java:111)
 07-09 10:22:10.735 25053-25053/sensor.recyclercardview2 W/System.err:
 at org.json.JSONObject.<init>(JSONObject.java:160)
 07-09 10:22:10.735 25053-25053/sensor.recyclercardview2 W/System.err:
 at org.json.JSONObject.<init>(JSONObject.java:173)
 07-09 10:22:10.735 25053-25053/sensor.recyclercardview2 W/System.err:
 at sensor.recyclercardview2.MainActivity$1.onResponse(MainActivity.java:63)
 07-09 10:22:10.735 25053-25053/sensor.recyclercardview2 W/System.err:
 at sensor.recyclercardview2.MainActivity$1.onResponse(MainActivity.java:57)

Body:
Replace these two lines

JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray(jsonData);

with this

JSONArray array = new JSONArray(s);


答:
you can use .prop() to added required attribute to input everytime you show it and remove the attribute everytime you hide it.

$(function() {
  var checkbox = $("#checkbox01");
  var hidden = $("#div01");
  hidden.hide();
  checkbox.change(function() {
    if (checkbox.is(':checked')) {
      hidden.show();
      $('#username').prop('required', true); //to add required
    } else {
      hidden.hide();
      $("#username").val("");
      $('#username').prop('required', false); //to remove required
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label><input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label>
<div id="div01">
  <input name="username" type="text" required>
</div></code>```

Body:
I have an hidden div which will contain some HTML inputs which some are needed to be required as part of a form. the div is visible by checking the checkbox and the code looks like this:

$(function() {
  var checkbox = $("#checkbox01");
  var hidden = $("#div01");
  hidden.hide();
  checkbox.change(function() {
    if (checkbox.is(':checked')) {
      hidden.show();
    } else {
      hidden.hide();
      $("#username").val("");
    }
  });
});

<input id="checkbox01" name="checkbox01" type="checkbox">show/hide

  <input name="username" type="text" required>

You can see the code in action on JSfiddle
As you can see the div is hidden when the checkbox is unchecked and also the username is cleaned when the div is hidden (checkbox unchecked).

How can I make the required be added to HTML only if checkbox is checked, so user won't get prompt to enter value when the div is hidden by Jquery... ?

Body:
you can use .prop() to added required attribute to input everytime you show it and remove the attribute everytime you hide it.

$(function() {
  var checkbox = $("#checkbox01");
  var hidden = $("#div01");
  hidden.hide();
  checkbox.change(function() {
    if (checkbox.is(':checked')) {
      hidden.show();
      $('#username').prop('required', true); //to add required
    } else {
      hidden.hide();
      $("#username").val("");
      $('#username').prop('required', false); //to remove required
    }
  });
});

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

<label><input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label>
<div id="div01">
  <input name="username" type="text" required>
</div>


答:
Update your js to this:</p>

```<code>    $(function() {
          var checkbox = $("#checkbox01");
          var hidden = $("#div01");
          hidden.hide();
          checkbox.change(function() {
            if (checkbox.is(':checked')) {
              checkbox.attr("required",true);
              hidden.show();
            } else {
              hidden.hide();
              checkbox.attr("required",false);
              $("#username").val("");
            }
          });
        });
</code>```

Body:
Update your js to this:

    $(function() {
          var checkbox = $("#checkbox01");
          var hidden = $("#div01");
          hidden.hide();
          checkbox.change(function() {
            if (checkbox.is(':checked')) {
              checkbox.attr("required",true);
              hidden.show();
            } else {
              hidden.hide();
              checkbox.attr("required",false);
              $("#username").val("");
            }
          });
        });


问:
Why am I not able to access the result of multiple networking calls?
In my Node app I am trying to get shipment data for packages. I need a way to get the json data and append it to an object or something so that I can pass it to my render page (using pug).

This is my code:

```<code>    var test;

    for(var i = 0; i < result.length; i++) {
        var currentNumber = result[i].trackingNumber;
        ups.track(currentNumber, function(err, tracking) {
            test += tracking
        });
    }

    res.send(result)
</code>```

It seems that anything I do inside of the ups.track has no scope into the var test, and I can't think of a better way to do this. Any help would be appreciated.

答:
First off, ups.track() is an asynchronous function.  That means that it will call its callback some indeterminate time in the future.  So, your for loop runs to its completion, launching result.length calls to ups.track() and then you do res.send(result) before any of them have completed, before any of them have called their callback.

Secondly, you aren't initializing your test variable so test += ... won't produce a good result.

So, you can't know the results until all of them have completed.  There are various ways to do that.

Low-tech Counter

The "low-tech" way to do that is to keep a counter:

```<code>var test = "";

var cntr = 0;
for(var i = 0; i < result.length; i++) {
    var currentNumber = result[i].trackingNumber;
    ups.track(currentNumber, function(err, tracking) {
        test += tracking;
        // see if we are done with all the ups.track() calls yet
        if (++cntr === result.length) {
            res.send(test);
        }
    });
}
</code>```

Using Promises

The higher-tech way is to use promises (this has larger benefits to learn for lots of other reasons).  While promises show only modest benefits here, they provide huge benefits as soon as you have sequences of asynchronous operations you need to coordinate and they also make error handling (something you are ignoring in your code example) much simpler too.

First, you make a "promisified" version of ups.track() which is a function that returns a promise that resolves or rejects when ups.track() finishes.

```<code>function upsTrack(num) {
    return new Promise(function(resolve, reject) {
        ups.track(num, function(err, tracking) {
           err ? reject(err) : resolve(tracking);
        });
    });
}
</code>```

Now, we'll use a combination of .map() to create an array or promises from all your calls to upsTrack() and Promise.all() to tell us when all those promises have completed.

```<code>Promise.all(result.map(function(item) {
    return upsTrack(item.trackingNumber);
})).then(function(allResults) {
    // allResults is an array of tracking results
    // process that array into your final result and send it
    res.send(allResults.join(","));
}).catch(function(err) {
    // handle error here
    res.status(500).end();
});
</code>```

Note that this structure also gets rid of multiple variables defined in the previous low-tech way of doing this as there is no need for test, cntr or i any more.  Looping structures and functions that process arrays or handle arrays of results take care of all that for us.

Using the Bluebird Promise library

And, you can take even a few more shortcuts by using a smarter promise library like Bluebird:

```<code>const Promise = require('bluebird');
ups = Promise.promisifyAll(ups);

Promise.map(result, function(item) {
    return ups.trackAsync(item.trackingNumber);
}).then(function(allResults) {
    // allResults is an array of tracking results
    // process that array into your final result and send it
    res.send(allResults.join(","));
}).catch(function(err) {
    // handle error here
    res.status(500).end();
});
</code>```

The Bluebird promise library has two useful things here.  It has a promisifyAll() method which will make promisified methods of all the ups object methods for you automatically and it also has Promise.map() which just combines array.map() and Promise.all() in one step (since it's a commonly used structure).

If you're interested in Promises and Promise libraries, you may find this useful:

Are there still reasons to use promise libraries like Q or BlueBird now that we have ES6 promises?

Body:
In my Node app I am trying to get shipment data for packages. I need a way to get the json data and append it to an object or something so that I can pass it to my render page (using pug).

This is my code:

    var test;

    for(var i = 0; i < result.length; i++) {
        var currentNumber = result[i].trackingNumber;
        ups.track(currentNumber, function(err, tracking) {
            test += tracking
        });
    }

    res.send(result)

It seems that anything I do inside of the ups.track has no scope into the var test, and I can't think of a better way to do this. Any help would be appreciated.

Body:
First off, ups.track() is an asynchronous function.  That means that it will call its callback some indeterminate time in the future.  So, your for loop runs to its completion, launching result.length calls to ups.track() and then you do res.send(result) before any of them have completed, before any of them have called their callback.

Secondly, you aren't initializing your test variable so test += ... won't produce a good result.

So, you can't know the results until all of them have completed.  There are various ways to do that.

Low-tech Counter

The "low-tech" way to do that is to keep a counter:

var test = "";

var cntr = 0;
for(var i = 0; i < result.length; i++) {
    var currentNumber = result[i].trackingNumber;
    ups.track(currentNumber, function(err, tracking) {
        test += tracking;
        // see if we are done with all the ups.track() calls yet
        if (++cntr === result.length) {
            res.send(test);
        }
    });
}

Using Promises

The higher-tech way is to use promises (this has larger benefits to learn for lots of other reasons).  While promises show only modest benefits here, they provide huge benefits as soon as you have sequences of asynchronous operations you need to coordinate and they also make error handling (something you are ignoring in your code example) much simpler too.

First, you make a "promisified" version of ups.track() which is a function that returns a promise that resolves or rejects when ups.track() finishes.

function upsTrack(num) {
    return new Promise(function(resolve, reject) {
        ups.track(num, function(err, tracking) {
           err ? reject(err) : resolve(tracking);
        });
    });
}

Now, we'll use a combination of .map() to create an array or promises from all your calls to upsTrack() and Promise.all() to tell us when all those promises have completed.

Promise.all(result.map(function(item) {
    return upsTrack(item.trackingNumber);
})).then(function(allResults) {
    // allResults is an array of tracking results
    // process that array into your final result and send it
    res.send(allResults.join(","));
}).catch(function(err) {
    // handle error here
    res.status(500).end();
});

Note that this structure also gets rid of multiple variables defined in the previous low-tech way of doing this as there is no need for test, cntr or i any more.  Looping structures and functions that process arrays or handle arrays of results take care of all that for us.

Using the Bluebird Promise library

And, you can take even a few more shortcuts by using a smarter promise library like Bluebird:

const Promise = require('bluebird');
ups = Promise.promisifyAll(ups);

Promise.map(result, function(item) {
    return ups.trackAsync(item.trackingNumber);
}).then(function(allResults) {
    // allResults is an array of tracking results
    // process that array into your final result and send it
    res.send(allResults.join(","));
}).catch(function(err) {
    // handle error here
    res.status(500).end();
});

The Bluebird promise library has two useful things here.  It has a promisifyAll() method which will make promisified methods of all the ups object methods for you automatically and it also has Promise.map() which just combines array.map() and Promise.all() in one step (since it's a commonly used structure).

If you're interested in Promises and Promise libraries, you may find this useful:

Are there still reasons to use promise libraries like Q or BlueBird now that we have ES6 promises?


问:
Is there concept of panel in BlackBerry?
As we have the concepts of panel in Swings and AWT to which we can add controls, do we have any concept of panel in BlackBerry?

I have to create icons in BB and place it at the bottom of the screen to give a look of toolbar. I know we have the Toolbar package in BB 6.0 but since all the simulators (like 8520 curve) don't support it, I can't use that.

答:
we have Managers in blackberry. to implement a toolbar on blackberry screen you can use VerticalFieldManager and HorizontalFieldManager. also if you want your toolbar to always show at bottom you can use VerticalFieldmanager that contains One fixed size VerticalFieldManager and one HorizontalFieldManager. you can have toolbar buttons in HorizontalFieldManager and add it to Parent manager.. something like this.</p>

```<code>VerticalFieldManager parent =
    new VerticalFieldManager(Manager.USE_ALL_HEIGHT|Manager.USE_ALL_WIDTH);
VerticalFieldManager vfm = new VerticalFieldManager(){
    public void sublayout(int width, int height) {
        super.sublayout(Display.getWidth(), 300);
        //Force the extent of our manager.
        //This will force the height of the object
        //where the above super.sublayout() call will
        //set the width.
        setExtent(Display.getWidth(), 300);
    }
};

/*
 * add all fields to vfm
 * ButtonField button = new ButtonField("button");
 * vfm.add(button);
 * ...
 */
parent.add(vfm);
HorizontalFieldManager hfm = new HorizontalFieldManager();
/*
 * add all toolbar buttons to hfm
 * hfm.add(icon1);
 * hfm.add(icon2);
 * ...
 *
 */
parent.add(hfm);
</code>```

Body:
we have Managers in blackberry. to implement a toolbar on blackberry screen you can use VerticalFieldManager and HorizontalFieldManager. also if you want your toolbar to always show at bottom you can use VerticalFieldmanager that contains One fixed size VerticalFieldManager and one HorizontalFieldManager. you can have toolbar buttons in HorizontalFieldManager and add it to Parent manager.. something like this.

VerticalFieldManager parent =
    new VerticalFieldManager(Manager.USE_ALL_HEIGHT|Manager.USE_ALL_WIDTH);
VerticalFieldManager vfm = new VerticalFieldManager(){
    public void sublayout(int width, int height) {
        super.sublayout(Display.getWidth(), 300);
        //Force the extent of our manager.
        //This will force the height of the object
        //where the above super.sublayout() call will
        //set the width.
        setExtent(Display.getWidth(), 300);
    }
};

/*
 * add all fields to vfm
 * ButtonField button = new ButtonField("button");
 * vfm.add(button);
 * ...
 */
parent.add(vfm);
HorizontalFieldManager hfm = new HorizontalFieldManager();
/*
 * add all toolbar buttons to hfm
 * hfm.add(icon1);
 * hfm.add(icon2);
 * ...
 *
 */
parent.add(hfm);

ContentLicense: CC BY-SA 2.5


问:
Go package with a loaded once set of data
I am writing a post code location lookup package, it loads in all uk postcodes from a csv, I would like to only load the data once I would like to know what is the best pattern to achieve this with Go.

```<code>type Location struct {
    Latitude float64
    Longitude float64
}

var postCodeCache = make(map[string]Location)
</code>```

These are my data types, currently I have a function called LoadData and LookupPostCode(). Ideally I would want to import my package and it would automatically load the data if it was not already loaded.

答:
You can use init() function in your package to do this.

Or, if it does not change frequently, you can convert your CSV into a Go Map definition in a separate .go file and it will be 'loaded' at the compile time.

Body:
I am writing a post code location lookup package, it loads in all uk postcodes from a csv, I would like to only load the data once I would like to know what is the best pattern to achieve this with Go.

type Location struct {
    Latitude float64
    Longitude float64
}

var postCodeCache = make(map[string]Location)

These are my data types, currently I have a function called LoadData and LookupPostCode(). Ideally I would want to import my package and it would automatically load the data if it was not already loaded.


问:
How to calculate the width of a text string of a specific font and font-size?
I have a UILabel that displays some chars. Like "x", "y" or "rpm". How can I calculate the width of the text in the label (it does not ues the whole available space)? This is for automatic layouting, where another view will have a bigger frame rectangle if that UILabel has a smaller text inside. Are there methods to calculate that width of the text when a UIFont and font size is specified? There's also no line-break and just one single line.</p>

答:
This simple extension in Swift works well.

```<code>extension String {
    func size(OfFont font: UIFont) -> CGSize {
        return (self as NSString).size(attributes: [NSFontAttributeName: font])
    }
}
</code>```

Usage:

```<code>let string = "hello world!"
let font = UIFont.systemFont(ofSize: 12)
let width = string.size(OfFont: font).width // size: {w: 98.912 h: 14.32}
</code>```

OwnerDisplayName: HelloMoon

Body:
This simple extension in Swift works well.

extension String {
    func size(OfFont font: UIFont) -> CGSize {
        return (self as NSString).size(attributes: [NSFontAttributeName: font])
    }
}

Usage:

let string = "hello world!"
let font = UIFont.systemFont(ofSize: 12)
let width = string.size(OfFont: font).width // size: {w: 98.912 h: 14.32}


问:
CastError: Cast to ObjectId failed for value " X" at path "_id" for model "Blog"
Hey guys could really use some help with a DELETE route. I'm working with RESTful routing, trying to follow the conventions and when adding the delete route I get the error:

CastError: Cast to ObjectId failed for value " X" at path "_id" for model "Blog"

I've searched for the issue on stackoverflow and the best I could come up with was the version of mongoose had a bug. I rolled it back to V 4.10.0 and am still getting the issue. My code follows:

```<code>var express    = require("express"),
app        = express(),
bodyParser = require("body-parser"),
mongoose   = require("mongoose"),
methodOverride = require("method-override");

           // APP CONFIG
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride("_method"));

mongoose.connect("mongodb://localhost/restful_blog_app");

// Create a new Blog Schema defines what the object will be

var Blog = new mongoose.Schema ({
    title: String,
    image: String, //{type: String, default: "placeholder.jpg"} for a default image
    body: String,
    created: {type: Date, default: Date.now}
});

// Mongoose compiles the Schema into a model, useable object
var Blog = mongoose.model("Blog", Blog);

// DELETE ROUTE

app.delete("/blogs/:id", function(req, res){
    Blog.findByIdAndRemove(req.params.id, function(err){
        if(err){
            console.log(err)
        }

    })
})
</code>```

答: Found the error, it was in my ejs file. I noticed that the error message had a space between the first quotation and the actual id itself so " 92384759" rather than "92384759". I removed the space and it works perfectly. The second fault on my part is for editing the error message in my original question (I should have just copied and pasted the objectid rather than abbreviate with " X"). – Andy 9 hours ago    </p>

Body:
Hey guys could really use some help with a DELETE route. I'm working with RESTful routing, trying to follow the conventions and when adding the delete route I get the error:

CastError: Cast to ObjectId failed for value " X" at path "_id" for model "Blog"

I've searched for the issue on stackoverflow and the best I could come up with was the version of mongoose had a bug. I rolled it back to V 4.10.0 and am still getting the issue. My code follows:

var express    = require("express"),
app        = express(),
bodyParser = require("body-parser"),
mongoose   = require("mongoose"),
methodOverride = require("method-override");

           // APP CONFIG
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride("_method"));

mongoose.connect("mongodb://localhost/restful_blog_app");

// Create a new Blog Schema defines what the object will be

var Blog = new mongoose.Schema ({
    title: String,
    image: String, //{type: String, default: "placeholder.jpg"} for a default image
    body: String,
    created: {type: Date, default: Date.now}
});

// Mongoose compiles the Schema into a model, useable object
var Blog = mongoose.model("Blog", Blog);

// DELETE ROUTE

app.delete("/blogs/:id", function(req, res){
    Blog.findByIdAndRemove(req.params.id, function(err){
        if(err){
            console.log(err)
        }

    })
})


问:
How to select from one column or the other?
Let's say I have a table with friends and their friendship status (0-rejected, 1-accepted)

```<code>userA   userB  status
-------------------
john    chris   1
chris   bob     1
mike    chris   1
</code>```

How do I select all of chris' friends to get an output like this?

```<code>john
bob
mike
</code>```

答:
Using  full outer joins </p>

```<code>SELECT column-name-list FROM table-name1
FULL OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
</code>```

Body:
Let's say I have a table with friends and their friendship status (0-rejected, 1-accepted)

userA   userB  status
-------------------
john    chris   1
chris   bob     1
mike    chris   1

How do I select all of chris' friends to get an output like this?

john
bob
mike

Body:
Using  full outer joins

SELECT column-name-list FROM table-name1
FULL OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;


问:
Help with strange memory behavior. Looking for leaks both in my brain and in my code
I spent the last few days trying to find memory leaks in a program we are developing.

First of all, I tried using some leak detectors. After fixing a few issues, they do not find any leaks any more. However, I am also monitoring my application using perfmon.exe. Performance Monitor reports that 'Private Bytes' and 'Working Set - Private' are steadily rising when the app is used. To me, this suggests that the program is using more and more memory the longer it runs. Internal resources seem to be stable however, so this sounds like leaking to me.

The program is loading a DLL at runtime. I suspect that these leaks or whatever they are occur in that library and get purged when the library is unloaded, hence they won't get picked up by the leak detectors. I used both DevPartner BoundsChecker and Virtual Leak Detector to look for memory leaks. Both supposedly catch leaks in DLLs.

Also, the memory consumption is increasing in steps and those steps roughly, but not exactly, coincide with certain GUI actions I perform in the application. If these were errors in our code, they should get triggered every single time the actions are performed and not just most of the time.

Whenever I am confronted with so much strangeness, I begin to question my basic assumptions. So I turn to you, who know everything, for suggestions. Is there a flaw in my assumptions? Do you have an idea of how to go about troubleshooting a problem like this?

Edit:

I am currently using Microsoft Visual C++ (x86) on Windows 7 64.

Edit2:

I just used IBM Purify to hunt for leaks. First of all, it lists a full 30% of the program as leaked memory. This can not be true. I guess it is identifying the whole DLL as leaked or something like that. However, if I search for new leaks every few actions, it reports leaks that correspond with the size increase reported by Performance Monitor. This could be a lead to a leak. Sadly, I am only using the trial version of Purify, so it won't show me the actual location of those leaks. (These leaks only show up at runtime. When the program exits, there are no leaks whatsoever reported by any tool.)

答:
Perfmon is fine for letting you know if you're leaking, but it's primitive.  There are commercial products that will do much better.  I use AQTime for C++ code and it's excellent: http://www.automatedqa.com/products/aqtime/

It will tell you the line of code that allocated the memory that was leaked.


问:
How to insert html in a child component in angular?
I'm trying to insert html into a child component. Basically something like this:

<custom-container>
Parnet content
</custom-container>

I can find references for passing data to child component but not able to find how to pass actual html inside my selector?

答: ng-content tag can be used in the template of the child component. That tag will take in anything that you put in between your component selector.</p>


问:
Why can't I insert a row at index 0 in MySQL?
I have a simple table with an id column as the primary key (int). When I run this statement, it creates a new row, but with an auto incremented id value:

```<code>INSERT INTO `test_table` (`id`,`id_user`,`someString`) VALUES (0, 0, 'Hello World')
</code>```

Produces:

```<code>id (pk) | id_user | someString
1       | 0       | Hello World
2       | 0       | Hello World
3       | 0       | Hello World
</code>```

Why does this happen? Shouldn't I be able to have an index of 0?

答:
Haven't tried this but i suspect you can
https://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html if "No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign 0 to the column to generate sequence numbers, unless the NO_AUTO_VALUE_ON_ZERO SQL mode is enabled"
If you do specify a value then mysql will accept it (as long as it does not cause a primary key error) and subsequent inserts will increment as normal where you do not specify it. So it is entirely possibly that you could create discontinuities should you wish to do so.

For example

```<code>ariaDB [sandbox]> DROP TABLE IF EXISTS T;
Query OK, 0 rows affected (0.11 sec)

MariaDB [sandbox]> CREATE TABLE T (ID INT AUTO_INCREMENT PRIMARY KEY, VAL VARCHAR(3));
Query OK, 0 rows affected (0.17 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO T (ID,VAL) VALUES (3,'AAA');
Query OK, 1 row affected (0.02 sec)

MariaDB [sandbox]> INSERT INTO T (ID,VAL) VALUES (2,'CCC');
Query OK, 1 row affected (0.02 sec)

MariaDB [sandbox]> INSERT INTO T (ID,VAL) VALUES(1,'BBB');
Query OK, 1 row affected (0.04 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO T (VAL) VALUES ('DDD');
Query OK, 1 row affected (0.04 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO T (ID,VAL) VALUES (10,'EEE');
Query OK, 1 row affected (0.01 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO T (VAL) VALUES ('FFF');
Query OK, 1 row affected (0.02 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> SELECT * FROM T;
+----+------+
| ID | VAL  |
+----+------+
|  1 | BBB  |
|  2 | CCC  |
|  3 | AAA  |
|  4 | DDD  |
| 10 | EEE  |
| 11 | FFF  |
+----+------+
6 rows in set (0.00 sec)
</code>```

Body:
I have a simple table with an id column as the primary key (int). When I run this statement, it creates a new row, but with an auto incremented id value:

INSERT INTO `test_table` (`id`,`id_user`,`someString`) VALUES (0, 0, 'Hello World')

Produces:

id (pk) | id_user | someString
1       | 0       | Hello World
2       | 0       | Hello World
3       | 0       | Hello World

Why does this happen? Shouldn't I be able to have an index of 0?

Body:
Haven't tried this but i suspect you can
https://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html if "No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign 0 to the column to generate sequence numbers, unless the NO_AUTO_VALUE_ON_ZERO SQL mode is enabled"
If you do specify a value then mysql will accept it (as long as it does not cause a primary key error) and subsequent inserts will increment as normal where you do not specify it. So it is entirely possibly that you could create discontinuities should you wish to do so.

For example

ariaDB [sandbox]> DROP TABLE IF EXISTS T;
Query OK, 0 rows affected (0.11 sec)

MariaDB [sandbox]> CREATE TABLE T (ID INT AUTO_INCREMENT PRIMARY KEY, VAL VARCHAR(3));
Query OK, 0 rows affected (0.17 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO T (ID,VAL) VALUES (3,'AAA');
Query OK, 1 row affected (0.02 sec)

MariaDB [sandbox]> INSERT INTO T (ID,VAL) VALUES (2,'CCC');
Query OK, 1 row affected (0.02 sec)

MariaDB [sandbox]> INSERT INTO T (ID,VAL) VALUES(1,'BBB');
Query OK, 1 row affected (0.04 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO T (VAL) VALUES ('DDD');
Query OK, 1 row affected (0.04 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO T (ID,VAL) VALUES (10,'EEE');
Query OK, 1 row affected (0.01 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO T (VAL) VALUES ('FFF');
Query OK, 1 row affected (0.02 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> SELECT * FROM T;
+----+------+
| ID | VAL  |
+----+------+
|  1 | BBB  |
|  2 | CCC  |
|  3 | AAA  |
|  4 | DDD  |
| 10 | EEE  |
| 11 | FFF  |
+----+------+
6 rows in set (0.00 sec)


问:
SQL queries from database with Laravel
I'm using Laravel and trying to do an SQL query from my Controller in a public function, but I'm really confused where I would put my table in the argument and if quotes go around the argument. Here is my code

```<code> public function selectMethod(){
    $results = DB::select('select firstname from people where id = 1');
    print_r($results);
    return view('pages.selectMethod');
}
</code>```

table is called people

My .env is configured to my database correctly and I get this error

FatalErrorException in AboutController.php line 90:
Class 'App\Http\Controllers\DB' not found

Thanks !

答:
Your error clearly states: Class 'App\Http\Controllers\DB' not found

Hence just use DB in your class. Add:

```<code>use DB;
</code>```

At the top of the file just below the namespace line.

Also, I would suggest you to use Eloquent for your queries. It will make your life a lot easier and your code a lot beautiful.

Title: SQL queries from database with Laravel

Body:
I'm using Laravel and trying to do an SQL query from my Controller in a public function, but I'm really confused where I would put my table in the argument and if quotes go around the argument. Here is my code

 public function selectMethod(){
    $results = DB::select('select firstname from people where id = 1');
    print_r($results);
    return view('pages.selectMethod');
}

table is called people

My .env is configured to my database correctly and I get this error

FatalErrorException in AboutController.php line 90:
Class 'App\Http\Controllers\DB' not found

Thanks !

Body:
Your error clearly states: Class 'App\Http\Controllers\DB' not found

Hence just use DB in your class. Add:

use DB;

At the top of the file just below the namespace line.

Also, I would suggest you to use Eloquent for your queries. It will make your life a lot easier and your code a lot beautiful.


问:
Bootstrap Alert - show then hide - cannot show again
I have a simple hidden dismissible bootstrap alert:

  <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

<button type="button" id="getSelectedAssets" class="btn btn-primary">Show Selected Assets</button>```
</div>
</div>
</p>

<p>A button is set to run a script that displays the hidden alert:</p>

```$("#selectedAssetsDetails").html('Selected Assets: '+values);
$("#selectedAssets").show();
```

<p>This works successfully the first time to show the alert, but if the user closes the alert it won't display the alert again by clicking the button to show the alert. I assumed:</p>

```$("#selectedAssets").show();
```

would always show the alert?

答:
Bootstrap documentation for alerts states that:

Just add data-dismiss="alert" to your close button to automatically give an alert close functionality. Closing an alert removes it from the DOM.

(my emphasis)

So that is why show() does not work the second time - because the element is no longer there.

So a solution is to remove the data-dismiss="alert" attribute and handle the close event yourself. With the code below, I added an id to the close button and another event handler to your original code:

let values = 'foo';

$('#closeAlert1').on('click', function() {
  $("#selectedAssets").hide();
});

$('#getSelectedAssets').on('click', function() {
  $("#selectedAssetsDetails").html('Selected Assets: '+values);
  $("#selectedAssets").show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="selectedAssets" class="alert alert-info text-center alert-dismissible" role="alert" style="display:none">
  <button type="button" id="closeAlert1" class="close" aria-label="Close"><span aria-hidden="true">×</span></button>
  <div id="selectedAssetsDetails"> </div>
</div>

<button type="button" id="getSelectedAssets" class="btn btn-primary">Show Selected Assets</button></code>```

Body:
I have a simple hidden dismissible bootstrap alert:

  <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

<button type="button" id="getSelectedAssets" class="btn btn-primary">Show Selected Assets</button>

A button is set to run a script that displays the hidden alert:

$("#selectedAssetsDetails").html('Selected Assets: '+values);
$("#selectedAssets").show();

This works successfully the first time to show the alert, but if the user closes the alert it won't display the alert again by clicking the button to show the alert. I assumed:

$("#selectedAssets").show();

would always show the alert?

Body:
Bootstrap documentation for alerts states that:

Just add data-dismiss="alert" to your close button to automatically give an alert close functionality. Closing an alert removes it from the DOM.

(my emphasis)

So that is why show() does not work the second time - because the element is no longer there.

So a solution is to remove the data-dismiss="alert" attribute and handle the close event yourself. With the code below, I added an id to the close button and another event handler to your original code:

let values = 'foo';

$('#closeAlert1').on('click', function() {
  $("#selectedAssets").hide();
});

$('#getSelectedAssets').on('click', function() {
  $("#selectedAssetsDetails").html('Selected Assets: '+values);
  $("#selectedAssets").show();
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="selectedAssets" class="alert alert-info text-center alert-dismissible" role="alert" style="display:none">
  <button type="button" id="closeAlert1" class="close" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  <div id="selectedAssetsDetails"> </div>
</div>

<button type="button" id="getSelectedAssets" class="btn btn-primary">Show Selected Assets</button>


问:
Can two Kestrel processes listen on different URLs in the same domain?
Let's say I have two apps called "a"and "b". How can I get them to both run at the same time on the same domain under different virtual directories?

Identity should listen on http://localhost:8080/a/

```<code>var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseUrls($"http://*:8080/a/")
    .UseStartup<Startup>()
    .Build();
host.Run();
</code>```

Userprofiles should listen on http://localhost:8080/userprofiles/

```<code>var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseUrls($"http://*:8080/b/")
    .UseStartup<Startup>()
    .Build();
host.Run();
</code>```

The apps run individually but when I start them both at the same time I get this error

```<code>crit: Microsoft.AspNetCore.Server.Kestrel[0]
Unable to start Kestrel.
System.IO.IOException: Failed to bind to address http:/ /*:8080/userprofiles: address already in use. ---> System.AggregateException: One or more errors occurred.
(Error -4091 EADDRINUSE address already in use) ---> Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvException: Error -4091 EADDRINUSE address already in use
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.Libuv.ThrowError(Int32 statusCode)
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.Libuv.tcp_getsockname(UvTcpHandle handle, SockAddr& addr, Int32& namelen)
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvTcpHandle.GetSockIPEndPoint()
</code>```

答: Kestrel can't share ports natively. You can run it behind IIS and do this, or you can use WebListener instead.</p>

Body:
Let's say I have two apps called "a"and "b". How can I get them to both run at the same time on the same domain under different virtual directories?

Identity should listen on http://localhost:8080/a/

var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseUrls($"http://*:8080/a/")
    .UseStartup<Startup>()
    .Build();
host.Run();

Userprofiles should listen on http://localhost:8080/userprofiles/

var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseUrls($"http://*:8080/b/")
    .UseStartup<Startup>()
    .Build();
host.Run();

The apps run individually but when I start them both at the same time I get this error

crit: Microsoft.AspNetCore.Server.Kestrel[0]
Unable to start Kestrel.
System.IO.IOException: Failed to bind to address http:/ /*:8080/userprofiles: address already in use. ---> System.AggregateException: One or more errors occurred.
(Error -4091 EADDRINUSE address already in use) ---> Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvException: Error -4091 EADDRINUSE address already in use
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.Libuv.ThrowError(Int32 statusCode)
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.Libuv.tcp_getsockname(UvTcpHandle handle, SockAddr& addr, Int32& namelen)
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvTcpHandle.GetSockIPEndPoint()


问:
If I create a web app with ReactJS, can I reuse the code to build a mobile app with React Native?
Do I get an advantage by using ReactJS for frontend if I'm planning to create mobile apps with React Native (maybe much faster development since some of the code can be reused)?

Or it does it not matter if it is ReactJS, Vue or Angular 2, as long I use Javascript so that I still can reuse the code for React native?

答:
Yes you can, but you have to adopt Higher Order Components (HOC) Stateless Functional Components in order to fully reuse your code.

The Difference:

Basically, ReactJS and React Native are almost identical, except for their component. Therefore, the best way to reuse code is to create separate independent components using HOC which can be called from both side using stateless functional component.

https://hackernoon.com/code-reuse-using-higher-order-hoc-and-stateless-functional-components-in-react-and-react-native-6eeb503c665


问:
Maximum 20 cookie per domain - Why?
I've just come across an interesting fact, apparently a website can have up to 20 seperate cookies.

Ok - fair enough.

But why on earth would you store more than say "UserID", and why would you possibly need 20 cookies?

答:
Some that I can think of:

persistent login cookie

session cookie

user-independent settings

user-tracking-cookie

Title: Maximum 20 cookie per domain - Why?


问:
Can Scala classes be used in Java
```<code>class Wish{
    val s = "Hello! User.  Wish you a Great day."
}

object Wish{
    def main(args: Array[String]){
        val w = new Wish()
        println("Value - " + w.s )
   }
}
</code>```

Java classes can be used in Scala.  Similarly,  can Scala classes be used in Java?

答:
Yes. If you want to do this, there are a few things you might want to remember:

Do not use operators in your method names or provide a wordy alternative. Operator names can be called from Java but are mangled into somethings very ugly.

Java users might expect Java style getters and setters. You can produce those automatically by adding @BeanProperty annotation to fields.

In the same way Java user might be accustomed to factory methods called ClassName.of where Scala uses .apply. Those you have to provide by hand, if you want to provide that service.

Title: Can Scala classes be used in Java

Body:
class Wish{
    val s = "Hello! User.  Wish you a Great day."
}

object Wish{
    def main(args: Array[String]){
        val w = new Wish()
        println("Value - " + w.s )
   }
}

Java classes can be used in Scala.  Similarly,  can Scala classes be used in Java?