问:
Rewrite rule for name.123456.js in htaccess
I have this file in my webserver:

```<code>http://example.com/static/js/min/common.min.js
</code>```

Since all files inside /static/ are cached with CloudFlare's Edge Cache, I need a way to change the url with something like this, so if the file is modified, the new version will be automatically fresh served:

```<code>http://example.com/static/js/min/common.min.1234567890.js
</code>```

Where 1234567890 is the timestamp of the file's date modification. I already generate the filename according to the modification date, the issue I'm having is in the .htaccess file.

This works fine:

```<code>RewriteRule ^(.*)\.[\d]{10}\.(js)$ $1.$2 [L]
</code>```

That means that:

```<code>http://example.com/static/js/min/common.min.1234567890.js
</code>```

Is redirected to:

```<code>http://example.com/static/js/min/common.min.js
</code>```

But, that will catch all .js requests from the domain, I just want to catch .js requests from within /static/js/min/*.js -- but this is failing:

```<code>RewriteRule ^static/js/min/(.*)\.[\d]{10}\.(js)$ $1.$2 [L]
</code>```

What should the rule be like?

答:
From your question,

You want to redirect

```<code>http://example.com/static/js/min/common.min.1234567890.js
</code>```

to

```<code>http://example.com/static/js/min/common.min.js
</code>```

So, How to do that

the .htaccess

First add

```<code> RewriteEngine On
</code>```

To turn on the rewrite engine

Then the next important line comes

```<code>RewriteRule ^static/js/min/([^\d]*)(\d{10}).js$ static/js/min/$1js [L]
</code>```

Explanation

Set the path as static/js/min/

Then we use RegEx to take the string until a non digit. ([^\d]*).

That is common.min. is captured.

Now $1 is common.min.

Then to match the url, we use (\d{10}) to capture the digits.

That is 1234567890 is captured.

Now $2 is 1234567890 which we don't want anymore

Then redirect to

```<code>static/js/min/$1js
</code>```

Not that here we didn't added the . after the $1 because $1 ending with a . (common.min.)

So, the code will be

```<code>RewriteEngine On
RewriteRule ^static/js/min/([^\d]*)(\d{10}).js$ static/js/min/$1js [L]
</code>```

Working Screenshot

My File Structure

The Address in Browser

Body:
I have this file in my webserver:

http://example.com/static/js/min/common.min.js

Since all files inside /static/ are cached with CloudFlare's Edge Cache, I need a way to change the url with something like this, so if the file is modified, the new version will be automatically fresh served:

http://example.com/static/js/min/common.min.1234567890.js

Where 1234567890 is the timestamp of the file's date modification. I already generate the filename according to the modification date, the issue I'm having is in the .htaccess file.

This works fine:

RewriteRule ^(.*)\.[\d]{10}\.(js)$ $1.$2 [L]

That means that:

http://example.com/static/js/min/common.min.1234567890.js

Is redirected to:

http://example.com/static/js/min/common.min.js

But, that will catch all .js requests from the domain, I just want to catch .js requests from within /static/js/min/*.js -- but this is failing:

RewriteRule ^static/js/min/(.*)\.[\d]{10}\.(js)$ $1.$2 [L]

What should the rule be like?

Body:
From your question,

You want to redirect

http://example.com/static/js/min/common.min.1234567890.js

to

http://example.com/static/js/min/common.min.js

So, How to do that

the .htaccess

First add

 RewriteEngine On

To turn on the rewrite engine

Then the next important line comes

RewriteRule ^static/js/min/([^\d]*)(\d{10}).js$ static/js/min/$1js [L]

Explanation

Set the path as static/js/min/

Then we use RegEx to take the string until a non digit. ([^\d]*).

That is common.min. is captured.

Now $1 is common.min.

Then to match the url, we use (\d{10}) to capture the digits.

That is 1234567890 is captured.

Now $2 is 1234567890 which we don't want anymore

Then redirect to

static/js/min/$1js

Not that here we didn't added the . after the $1 because $1 ending with a . (common.min.)

So, the code will be

RewriteEngine On
RewriteRule ^static/js/min/([^\d]*)(\d{10}).js$ static/js/min/$1js [L]

Working Screenshot

My File Structure

The Address in Browser


来源: stackexchange

问:
Text wrap on image using graphics?
How I can wrap the text based on text size

```<code>g.drawString("Hello, please help me in wrapping the text", 100, 100);
</code>```

output - Text in straight line:

Required output - Wrapped text based on text length:

How to achieve the required output? wasted lot of time in figuring it but no use, with explanation is much appreciated.

答:
Wrapping words using HTML is the easiest way to approach to this problem.

```<code>import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class LabelRenderTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                String title = "<html><body style='"
                        + "text-align: center; width: 100px; padding: 5px;'>"
                        + "<p>Hello, please help me in<br>wrapping the text";

                BufferedImage image = new BufferedImage(
                        200,
                        100,
                        BufferedImage.TYPE_INT_RGB);

                JLabel textLabel = new JLabel(title);
                textLabel.setSize(textLabel.getPreferredSize());
                textLabel.setForeground(Color.WHITE);

                Graphics2D g = image.createGraphics();
                textLabel.paint(g);
                g.dispose();

                JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(image)));
            }
        });
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Text wrap on image using graphics?

Body:
How I can wrap the text based on text size

g.drawString("Hello, please help me in wrapping the text", 100, 100);

output - Text in straight line:

Required output - Wrapped text based on text length:

How to achieve the required output? wasted lot of time in figuring it but no use, with explanation is much appreciated.

Body:
Wrapping words using HTML is the easiest way to approach to this problem.

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class LabelRenderTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                String title = "<html><body style='"
                        + "text-align: center; width: 100px; padding: 5px;'>"
                        + "<p>Hello, please help me in<br>wrapping the text";

                BufferedImage image = new BufferedImage(
                        200,
                        100,
                        BufferedImage.TYPE_INT_RGB);

                JLabel textLabel = new JLabel(title);
                textLabel.setSize(textLabel.getPreferredSize());
                textLabel.setForeground(Color.WHITE);

                Graphics2D g = image.createGraphics();
                textLabel.paint(g);
                g.dispose();

                JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(image)));
            }
        });
    }
}


问:
html dropdown menu dependant on json data
I would like to change the file depending on the first option selected eg. if they pick "X" i want to access the "x.json file" if they select "V" then the "V.json file". do i do a filename= $(this) as below?

```<code>HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
     "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

</SCRIPT>
</HEAD>
<BODY>

<select id="first-choice">
  <option selected value="base">Please Select</option>
  <option value="beverages">Beverages</option>
  <option value="snacks">Snacks</option>
</select>

<br>

<select id="second-choice">
  <option>Please choose from above</option>
</select>

<SCRIPT type="text/javascript">

$("#first-choice").change(function() {

    var $dropdown = $(this);

    $.getJSON("data.json", function(data) {

        var key = $dropdown.val();
        var vals = [];

        switch(key) {
            case 'beverages':
                vals = data.beverages.split(",");
                break;
            case 'snacks':
                vals = data.snacks.split(",");
                break;
            case 'base':
                vals = ['Please choose from above'];
        }

        var $secondChoice = $("#second-choice");
        $secondChoice.empty();
        $.each(vals, function(index, value) {
            $secondChoice.append("<option>" + value + "</option>");
        });

    });
});

</SCRIPT>
</BODY>
</HTML>
</code>```

JSON: (want to seperate into two files)

```<code>{
  "beverages": "Coffee,Coke",
  "snacks": "Chips,Cookies"
}
</code>```

答:
I check your code and done some edit , Please check working code below.

HTML-:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<script src="https://code.jquery.com/jquery-2.2.4.js" ></script>
</SCRIPT>
</HEAD>
<BODY>
<select id="first-choice">
<option selected value="base">Please Select</option>
<option value="beverages">Beverages</option>
<option value="snacks">Snacks</option>
</select>
<br>
<select id="second-choice">
<option>Please choose from above</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$("#first-choice").change(function() {
var $dropdown = $(this);

$.getJSON("data.json", function(data) {

    var key = $dropdown.val();
    var vals = [];

    switch(key) {
        case 'beverages':
            vals = data.beverages.join().split(",");
            break;
        case 'snacks':
            vals = data.snacks.join().split(",");
            break;
        case 'base':
            vals = ['Please choose from above'];
    }

    var $secondChoice = $("#second-choice");
    $secondChoice.empty();
    $.each(vals, function(index, value) {
        $secondChoice.append("<option>" + value + "</option>");
      });

    });
   });
});
</SCRIPT>
</BODY>
</HTML>
</code>```

json.data -:

```<code>{
   "beverages": ["b1", "b2", "b3"],
   "snacks": ["s1", "s2", "s3"]
}
</code>```

You can change it as per your requirement.

Output-:

I hope now your issue is solved . Enjoy

Body:
I would like to change the file depending on the first option selected eg. if they pick "X" i want to access the "x.json file" if they select "V" then the "V.json file". do i do a filename= $(this) as below?

HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
     "http://www.w3.org/TR/html4/strict.dtd">

<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">

</SCRIPT>

<select id="first-choice">
  <option selected value="base">Please Select</option>
  <option value="beverages">Beverages</option>
  <option value="snacks">Snacks</option>
</select>

<select id="second-choice">
  <option>Please choose from above</option>
</select>

JSON: (want to seperate into two files)

{
  "beverages": "Coffee,Coke",
  "snacks": "Chips,Cookies"
}

Body:
I check your code and done some edit , Please check working code below.

HTML-:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<script src="https://code.jquery.com/jquery-2.2.4.js" ></script>
</SCRIPT>
</HEAD>
<BODY>
<select id="first-choice">
<option selected value="base">Please Select</option>
<option value="beverages">Beverages</option>
<option value="snacks">Snacks</option>
</select>
<br>
<select id="second-choice">
<option>Please choose from above</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$("#first-choice").change(function() {
var $dropdown = $(this);

$.getJSON("data.json", function(data) {

    var key = $dropdown.val();
    var vals = [];

    switch(key) {
        case 'beverages':
            vals = data.beverages.join().split(",");
            break;
        case 'snacks':
            vals = data.snacks.join().split(",");
            break;
        case 'base':
            vals = ['Please choose from above'];
    }

    var $secondChoice = $("#second-choice");
    $secondChoice.empty();
    $.each(vals, function(index, value) {
        $secondChoice.append("<option>" + value + "</option>");
      });

    });
   });
});
</SCRIPT>
</BODY>
</HTML>

json.data -:

{
   "beverages": ["b1", "b2", "b3"],
   "snacks": ["s1", "s2", "s3"]
}

You can change it as per your requirement.

Output-:

I hope now your issue is solved . Enjoy


问:
Better way of returning the values of a column in Active Record?
Quick one, but thought I'd ask.

Is there a better way of getting the column values from a model's column than something like this?

```<code>Item.count(:all, :group => 'status').reject! { |i, e| i.blank? }.collect { |i,e| i}
</code>```

答:
Is it the same thing as the following code?

```<code>Item.count(:all, :group => "status", :conditions => "status != ''"}
</code>```

.. maybe not ..

but then could you please specify more criteria you want? i.e. status is blank? count is blank?

OwnerDisplayName: The Pied Pipes

ContentLicense: CC BY-SA 2.5

Body:
Quick one, but thought I'd ask.

Is there a better way of getting the column values from a model's column than something like this?

Item.count(:all, :group => 'status').reject! { |i, e| i.blank? }.collect { |i,e| i}

Body:
Is it the same thing as the following code?

Item.count(:all, :group => "status", :conditions => "status != ''"}

.. maybe not ..

but then could you please specify more criteria you want? i.e. status is blank? count is blank?

OwnerDisplayName: Sikachu

LastEditorDisplayName: Sikachu


问:
Create new entry if not empty and no duplicates exist
I want to create a note with a title and a text if

the title is not empty

the title does not already exist

When I check for duplicates in my array, it always returns true, even if there are duplicates.

My code:

```<code>CreateNote(title, text){
    if (title.length > 0 && // title is empty?
 $.inArray(title, this.store.notes) < 0) // check the array for duplicates, returns always true, even with duplicates in the store
      this.store.AddNote(new Note(title, text));
  }
</code>```

So what is wrong with the second check =?

Thanks

答:
Check the value in {console.log($.inArray(title, this.store.notes))}.
or use other way of condition $.inArray(title, this.store.notes) === -1.
Hope this might solve the issue.</p>

Body:
I want to create a note with a title and a text if

the title is not empty

the title does not already exist

When I check for duplicates in my array, it always returns true, even if there are duplicates.

My code:

CreateNote(title, text){
    if (title.length > 0 && // title is empty?
 $.inArray(title, this.store.notes) < 0) // check the array for duplicates, returns always true, even with duplicates in the store
      this.store.AddNote(new Note(title, text));
  }

So what is wrong with the second check =?

Thanks


问:
Codeigniter HVMC modular seperation extension URL rewrite / routing
Ive been using HVMC modular extension, and its working great, but Im having trouble figuring out how to use, and if it is possible to use URL routing with HVMC.

Basically, I have a module called “site”, which is my main default site controller. All of the other modules I am not using directly, I am only using them by calling echo modules::run(‘controller/method’);—So basically I just want to remove “site” from the URL so that all the methods within the site module/controller appear without the word “site” in it.

Can anyone tell me if this can be done with HVMC modular extensions?

Any help much appreciated!

答:
I also worked since 3 years in CI HMVC, and some of my routing examples is there, it may help you.

I define 2 types of module here one is site and another is admin.

1>Routing for admin:

```<code>/*ADMIN is a constant, you can define anything like admin or backend etc. */
/*Example: admin/login*/
$route[ADMIN.'/([a-zA-Z]+)'] = function($controller){
    return 'admin/'.strtolower($controller);
};

/*Example: admin/user/listing*/
$route[ADMIN.'/([a-zA-Z]+)/(:any)'] = function($controller, $function){
    return 'admin/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function));
};

/*Example: admin/user/edit/LU1010201352*/
$route[ADMIN.'/([a-zA-Z]+)/(:any)/(:any)'] = function($controller,$function,$param) {
    return 'admin/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param;
};

/*Example: admin/user/assign-group/LU1010201352/G2010201311*/
$route[ADMIN.'/([a-zA-Z]+)/(:any)/(:any)/(:any)'] = function($controller,$function,$param,$param1){
    return 'admin/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param.'/'.$param1;
};
</code>```

2>Routing for site:

```<code>$route['([a-zA-Z]+)'] = function($controller) {
    return 'site/'.strtolower($controller);
};

$route['([a-zA-Z]+)/(:any)'] = function($controller,$function){
    return 'site/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function));
};

$route['([a-zA-Z]+)/(:any)/(:any)'] = function($controller,$function,$param) {
    return 'site/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param;
};

$route['([a-zA-Z]+)/(:any)/(:any)/(:any)'] = function($controller,$function,$param,$param1) {
    return 'site/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param.'/'.$param1;
};
</code>```

It is totally dynamic. You can create lots of controller inside any module. If you want to add more module then you just make another block of routing like 1 or 2.

Body:
I also worked since 3 years in CI HMVC, and some of my routing examples is there, it may help you.

I define 2 types of module here one is site and another is admin.

1>Routing for admin:

/*ADMIN is a constant, you can define anything like admin or backend etc. */
/*Example: admin/login*/
$route[ADMIN.'/([a-zA-Z]+)'] = function($controller){
    return 'admin/'.strtolower($controller);
};

/*Example: admin/user/listing*/
$route[ADMIN.'/([a-zA-Z]+)/(:any)'] = function($controller, $function){
    return 'admin/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function));
};

/*Example: admin/user/edit/LU1010201352*/
$route[ADMIN.'/([a-zA-Z]+)/(:any)/(:any)'] = function($controller,$function,$param) {
    return 'admin/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param;
};

/*Example: admin/user/assign-group/LU1010201352/G2010201311*/
$route[ADMIN.'/([a-zA-Z]+)/(:any)/(:any)/(:any)'] = function($controller,$function,$param,$param1){
    return 'admin/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param.'/'.$param1;
};

2>Routing for site:

$route['([a-zA-Z]+)'] = function($controller) {
    return 'site/'.strtolower($controller);
};

$route['([a-zA-Z]+)/(:any)'] = function($controller,$function){
    return 'site/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function));
};

$route['([a-zA-Z]+)/(:any)/(:any)'] = function($controller,$function,$param) {
    return 'site/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param;
};

$route['([a-zA-Z]+)/(:any)/(:any)/(:any)'] = function($controller,$function,$param,$param1) {
    return 'site/'.strtolower($controller).'/'.str_replace("-","_",strtolower($function)).'/'.$param.'/'.$param1;
};

It is totally dynamic. You can create lots of controller inside any module. If you want to add more module then you just make another block of routing like 1 or 2.


问:
If checkbox checked need to send "Yes" else send "No" to database with angular2?
```<code>**Here is my code**
<td>
    <label class="col-md-2">
      <input type="checkbox" class="form-control" [ngModel]="row.create" name="create" [checked]="(row.create==='Y')" (change)="onChecked(operation, appName, 'create', $event.target.checked)">
    </label>
   <label class="col-md-2">
    <input type="checkbox" class="form-control" [ngModel]="row.read" name="read" [checked]="(row.read==='Y')" (change)="onChecked(operation, appName, 'read', $event.target.checked)">
  </label>
    <label class="col-md-2">
      <input type="checkbox" class="form-control" [ngModel]="row.exportFile" name="exportFile" [checked]="(row.exportFile==='Y')" (change)="onChecked(operation, appName, 'exportFile', $event.target.checked)">
    </label>
    <label class="col-md-2">
      <input type="checkbox" class="form-control" [ngModel]="row.exportData" name="exportData" [checked]="(row.exportData==='Y')" (change)="onChecked(operation, appName, 'exportData', $event.target.checked)">
    </label>
</td>

 **Here is component.ts**
private onChecked(operation:any, appName: any, checked:boolean){
    let appaccess = this.appData.find(
   appaccess=>appaccess.appName===appName
   );
  let cbindex = this.appData.indexOf(appaccess);

    if(checked){
        switch(operation)
        {
            case 'create':
                this.appData[cbindex].create = 'Y';
                break;
            case 'read':
                this.appData[cbindex].read = 'Y';
                break;
            case 'exportFile':
                this.appData[cbindex].exportFile = 'Y';
                break;
            case 'exportData':
                this.appData[cbindex].exportData = 'Y';
                break;
            case 'publish':
                this.appData[cbindex].publish = 'Y';
                break;
        }
        console.log('option checked is '+ operation);
    }
    else{
        switch(operation)
        {
            case 'create':
                this.appData[cbindex].create = 'N';
                break;
            case 'read':
                this.appData[cbindex].read = 'N';
                break;
            case 'exportFile':
                this.appData[cbindex].exportFile = 'N';
                break;
            case 'exportData':
                this.appData[cbindex].exportData = 'N';
                break;
            case 'publish':
                this.appData[cbindex].publish = 'N';
                break;
        }
        console.log('option unchecked is '+ operation);
    }
}
</code>```

I have some data in database with value of "Yes" and "No". When i checked need to send yes value and when unchecked send no. Please any write function for that. and I need to compare same in to database also. Please help me on this. Thanks in advance.

答:
Template side :

```<code><input type="checkbox" class="form-control" name="" id=""  (change)="onChecked($event.target.value)">
</code>```

Component Side :

```<code>onChecked(value : boolean)
{
    // value will always be true/false
    // as per your database call pass the value
    if(value)
    {
        // make a call for checked
    }
    else
    {
        // make a call for unchecked
    }
}
</code>```

Body:
**Here is my code**

      <input type="checkbox" class="form-control" [ngModel]="row.create" name="create" [checked]="(row.create==='Y')" (change)="onChecked(operation, appName, 'create', $event.target.checked)">

    <input type="checkbox" class="form-control" [ngModel]="row.read" name="read" [checked]="(row.read==='Y')" (change)="onChecked(operation, appName, 'read', $event.target.checked)">

      <input type="checkbox" class="form-control" [ngModel]="row.exportFile" name="exportFile" [checked]="(row.exportFile==='Y')" (change)="onChecked(operation, appName, 'exportFile', $event.target.checked)">

      <input type="checkbox" class="form-control" [ngModel]="row.exportData" name="exportData" [checked]="(row.exportData==='Y')" (change)="onChecked(operation, appName, 'exportData', $event.target.checked)">

 **Here is component.ts**
private onChecked(operation:any, appName: any, checked:boolean){
    let appaccess = this.appData.find(
   appaccess=>appaccess.appName===appName
   );
  let cbindex = this.appData.indexOf(appaccess);

    if(checked){
        switch(operation)
        {
            case 'create':
                this.appData[cbindex].create = 'Y';
                break;
            case 'read':
                this.appData[cbindex].read = 'Y';
                break;
            case 'exportFile':
                this.appData[cbindex].exportFile = 'Y';
                break;
            case 'exportData':
                this.appData[cbindex].exportData = 'Y';
                break;
            case 'publish':
                this.appData[cbindex].publish = 'Y';
                break;
        }
        console.log('option checked is '+ operation);
    }
    else{
        switch(operation)
        {
            case 'create':
                this.appData[cbindex].create = 'N';
                break;
            case 'read':
                this.appData[cbindex].read = 'N';
                break;
            case 'exportFile':
                this.appData[cbindex].exportFile = 'N';
                break;
            case 'exportData':
                this.appData[cbindex].exportData = 'N';
                break;
            case 'publish':
                this.appData[cbindex].publish = 'N';
                break;
        }
        console.log('option unchecked is '+ operation);
    }
}

I have some data in database with value of "Yes" and "No". When i checked need to send yes value and when unchecked send no. Please any write function for that. and I need to compare same in to database also. Please help me on this. Thanks in advance.

Body:
Template side :

<input type="checkbox" class="form-control" name="" id=""  (change)="onChecked($event.target.value)">

Component Side :

onChecked(value : boolean)
{
    // value will always be true/false
    // as per your database call pass the value
    if(value)
    {
        // make a call for checked
    }
    else
    {
        // make a call for unchecked
    }
}


问:
"Add JUnit library" in Eclipes does not have "Junit 5" option
Can anyone help me to add Junit 5 in eclipse? When I create java project and add junit library it only shows Junit3 and junit4. I did not find junit5 and do not know how to set up things so that I can use Junit5 in project. I also gone through this guide, but did not understand where to setup these codes in eclipse.

Can anyone help me step by step how to implement Junit5 Test in eclipse-neon?

答: In addition to greg's answer, I want to point out that you can already use Oxygen with JUnit 5. The steps to set it up are documented in the Eclipse Wiki. (I'd rather not repeat them here because it is likely that they will change, in which case this answer would be outdated.)</p>

ContentLicense: CC BY-SA 4.0


问:
Change ion-android-star-outline to ion-android-star on click
I tried using onClick but not sure what function to go with it. I am not able to make it clickable.

```<code><i className="ion-android-star-outline" ></i>
</code>```

I used an  tag.  How should I proceed from here?

答:
Are you looking for something like this ?

$('i').click(function(){
    $(this).toggleClass("ion-android-star-outline ion-android-star");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>i{
  font-size: 50px;
  cursor: pointer;
}</code>```

<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet"/>

```

Body:
I tried using onClick but not sure what function to go with it. I am not able to make it clickable.

I used an  tag.  How should I proceed from here?

Body:
Are you looking for something like this ?

$('i').click(function(){
    $(this).toggleClass("ion-android-star-outline ion-android-star");
});

i{
  font-size: 50px;
  cursor: pointer;
}

<link href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<i class="ion-android-star-outline"></i>


问:
How to handle exceptions raised from sympy integrate
I am starting to learn sympy. I tried one integration problem using sympy, and I get this exception:

```<code>File "/home/me/anaconda3/lib/python3.6/site-
      packages/sympy/polys/domains/domain.py",
      line 146,
    in convert raise CoercionFailed("can't convert %s of type %s to %s" %
    (element, type(element), self))

sympy.polys.polyerrors.CoercionFailed: can't convert (_x4*a + a)**0.5 of
 type
<class 'sympy.core.power.Pow'> to RR(a,f,n,A,B)
   [_A0,_A1,_A2,_A3,_A4,_A5,_A6,_A7,_A8,_A9,_A10,_A11,
   _A12,_A13,_A14,_A15,_A16,_A17
 ...
 raise ValueError("expected an expression convertible to a polynomial in %s,
   got %s" % (self, expr))
  ValueError: expected an expression convertible to a polynomial in
  Polynomial ring in
</code>```

The full message is very long. There is a good chance I am doing something wrong? as I just started learning sympy.  This is the code I used

```<code>from sympy import *
import traceback
import logging

logging.basicConfig(filename='sympy_err.log')

x, A, B, f, e, c, d, a, b, n = symbols('x A B f e c d a b n', real=True)
try:
    integrate((d*sin(f*x+e))**n*(a+a*sin(f*x+e))**(5/2)*(A+B*sin(f*x+e)),x)
except Exception as e:
    logging.error(traceback.format_exc())
</code>```

The expected antiderivative is

```<code>-((2*a^3*(2*B*(115 + 203*n + 104*n^2 + 16*n^3) + A*
 (301 + 478*n + 224*n^2 + 32*n^3))*
 Cos[e + f*x]*Hypergeometric2F1[1/2, -n, 3/2, 1 - Sin[e + f*x]]*
 (d*Sin[e + f*x])^n)/
     Sin[e + f*x]^n/(f*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*
  Sqrt[a + a*Sin[e + f*x]])) -
  (2*a^3*(2*B*(35 + 23*n + 4*n^2) + A*(77 + 50*n + 8*n^2))*
  Cos[e + f*x]*
    (d*Sin[e + f*x])^(1 + n))/(d*f*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*
  Sqrt[a + a*Sin[e + f*x]]) -
  (2*a^2*(2*B*(5 + n) + A*(7 + 2*n))*Cos[e + f*x]*
  (d*Sin[e + f*x])^(1 + n)*
    Sqrt[a + a*Sin[e + f*x]])/(d*f*(5 + 2*n)*
   (7 + 2*n)) - (2*a*B*Cos[e + f*x]*(d*Sin[e + f*x])^(1 + n)*
  (a + a*Sin[e + f*x])^(3/2))/(d*f*(7 + 2*n))
</code>```

My question is:  Is the way I am catching exceptions from sympy above OK? Since I do not know what exceptions will be raied. And is this something to be expected if sympy unable to solve an integral, to throw an exception?

I am using Linux, just installed latest Anaconda 64bit on Linux.

```<code>code>conda list sympy
# packages in environment at /home/me/anaconda3:
#
sympy                     1.0                      py36_0
</code>```

答:
The exception you're seeing should be considered a bug in SymPy.

But note that the 5/2 in the expression is being evaluated to a floating point number by Python, which makes SymPy have a harder time with it. It is usually a good idea to use rational powers in SymPy instead of floating point ones. So the right version would be integrate((d*sin(f*x+e))**n*(a+a*sin(f*x+e))**Rational(5, 2)*(A+B*sin(f*x+e)),x). However, SymPy currently hangs on this integral (don't bother letting it finish; it won't find the answer).

So the short of it is: the exception you're seeing is a bug, and SymPy can't compute the integral currently anyway.

Body:
I am starting to learn sympy. I tried one integration problem using sympy, and I get this exception:

File "/home/me/anaconda3/lib/python3.6/site-
      packages/sympy/polys/domains/domain.py",
      line 146,
    in convert raise CoercionFailed("can't convert %s of type %s to %s" %
    (element, type(element), self))

sympy.polys.polyerrors.CoercionFailed: can't convert (_x4*a + a)**0.5 of
 type
<class 'sympy.core.power.Pow'> to RR(a,f,n,A,B)
   [_A0,_A1,_A2,_A3,_A4,_A5,_A6,_A7,_A8,_A9,_A10,_A11,
   _A12,_A13,_A14,_A15,_A16,_A17
 ...
 raise ValueError("expected an expression convertible to a polynomial in %s,
   got %s" % (self, expr))
  ValueError: expected an expression convertible to a polynomial in
  Polynomial ring in

The full message is very long. There is a good chance I am doing something wrong? as I just started learning sympy.  This is the code I used

from sympy import *
import traceback
import logging

logging.basicConfig(filename='sympy_err.log')

x, A, B, f, e, c, d, a, b, n = symbols('x A B f e c d a b n', real=True)
try:
    integrate((d*sin(f*x+e))**n*(a+a*sin(f*x+e))**(5/2)*(A+B*sin(f*x+e)),x)
except Exception as e:
    logging.error(traceback.format_exc())

The expected antiderivative is

-((2*a^3*(2*B*(115 + 203*n + 104*n^2 + 16*n^3) + A*
 (301 + 478*n + 224*n^2 + 32*n^3))*
 Cos[e + f*x]*Hypergeometric2F1[1/2, -n, 3/2, 1 - Sin[e + f*x]]*
 (d*Sin[e + f*x])^n)/
     Sin[e + f*x]^n/(f*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*
  Sqrt[a + a*Sin[e + f*x]])) -
  (2*a^3*(2*B*(35 + 23*n + 4*n^2) + A*(77 + 50*n + 8*n^2))*
  Cos[e + f*x]*
    (d*Sin[e + f*x])^(1 + n))/(d*f*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*
  Sqrt[a + a*Sin[e + f*x]]) -
  (2*a^2*(2*B*(5 + n) + A*(7 + 2*n))*Cos[e + f*x]*
  (d*Sin[e + f*x])^(1 + n)*
    Sqrt[a + a*Sin[e + f*x]])/(d*f*(5 + 2*n)*
   (7 + 2*n)) - (2*a*B*Cos[e + f*x]*(d*Sin[e + f*x])^(1 + n)*
  (a + a*Sin[e + f*x])^(3/2))/(d*f*(7 + 2*n))

My question is:  Is the way I am catching exceptions from sympy above OK? Since I do not know what exceptions will be raied. And is this something to be expected if sympy unable to solve an integral, to throw an exception?

I am using Linux, just installed latest Anaconda 64bit on Linux.

code>conda list sympy
# packages in environment at /home/me/anaconda3:
#
sympy                     1.0                      py36_0


问:
New to NLP, Question about annotation
I am new to NLP and I am looking for a starting point, in terms of some tutorials, documentation or example code.
I have been told to research the possibilities of processing natural text to extract some structured data from it.
For example I want to extract(annotate) height and weight from following statements.
"He is 6 feet tall and weighs 200 pounds" or
"His height is 6 feet and weight is 200" etc.
I have looked into UIMA but it seems like a  self created REGEX dictionary with no training capabilities.
So in a nutshell, what Java framework can I use to create an annotation engine that can be trained as well!
Any help(pointers) on this will be heavily appreciated.
Thanks</p>

答:
Since you asked for pointers: LingPipe (already mentioned above), OpenNLP, and Stanford NLP distributions.

Note: if Python is an option, you can use the Natural Language Toolkit.

Title: New to NLP, Question about annotation


问:
the g:link not working while using inside the g:formremote
this is the code for ajax request to the controller i already tried.

```<code><g:formRemote onComplete="onComplete()" update="addBlock" autocomplete="off" url="[controller: 'someContoller', action:'someAction']">
</code>```

this is the link inside the form remote and it is not working.

```<code><g:link url="[controller:'anotherController',action:'anotherAction']"><button>Go</button></g:link></g:formremote>
</code>```

答:
You are putting url attribute in g:link that's why it is not working. Use this it will help you .</p>

```<code><g:link controller:"anotherController",action:"anotherAction">Go</g:link>
</code>```

Body:
this is the code for ajax request to the controller i already tried.

<g:formRemote onComplete="onComplete()" update="addBlock" autocomplete="off" url="[controller: 'someContoller', action:'someAction']">

this is the link inside the form remote and it is not working.

<g:link url="[controller:'anotherController',action:'anotherAction']"><button>Go</button></g:link></g:formremote>

Body:
You are putting url attribute in g:link that's why it is not working. Use this it will help you .

<g:link controller:"anotherController",action:"anotherAction">Go</g:link>


问:
coffescript jquery on click delegated function rails
I have question, i have input event_dodavatel, on that field is on keyup  declared loading of json. But i can't click on div with id doplnovac.

Can anybody give me hints?

html:

```<code><input type="text" name="event[dodavatel]" id="event_dodavatel" />
<textarea name="event[adresa]" id="event_adresa"></textarea>
</code>```

fragment of generated autocomplete:

```<code><div id="help">
<div id="napoveda" class="list-group sm">
<div class="doplnovac" id="14" data-name="Vitana a.s.                 +" data-adresa="Mělnická 133" data-city="Byšice">Vitana a.s.                 +</div>
<div class="doplnovac" id="4751" data-name="Vitana,a.s. - catering" data-adresa="Mělnická 133" data-city="Byšice">Vitana,a.s. - catering</div>
</div>
</div>
</code>```

CoffeScript

```<code>String::replaceAll = (stringFind, stringReplace) ->
ex = new RegExp(stringFind.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,
'\\$1'), 'g')
@replace ex, stringReplace

jQuery ->
  $(document).on "click", ".doplnovac",(event) ->
    $('#event_dodavatel').val $this.data('name')
    $('#event_adresadodavatel').val $this.data('adresa') + ' ' + $this.data('city')
    $('#help').empty()
    event.preventdefault()
    return
  $('#event_dodavatel').keyup ->
  $('#help').empty()
  $.getJSON 'local web/'+$(this).val(), (data) ->
    items=[]
    $.each data.data, (i, item) ->
      items.push("<div class='doplnovac' id='"+item.Internal+"' data-name='"+item.Name1+"' data-adresa='"+item.Street+"' data-city='"+item.City+"'>" +item.Name1+ "</div>");
    $('<div>',
      'id': 'napoveda'
      'class': 'list-group sm'
      html: items.join('')).appendTo '#help'
  return
return
$('.kalendar').datepicker({ beforeShowDay:
$.datepicker.noWeekends,defaultDate: new Date() });
$('#q_datum_eq').datepicker({ beforeShowDay:
$.datepicker.noWeekends,defaultDate: new Date() });
$('#q_datum_eq').change ->
@form.submit()
return
$('#q_cil_id_eq').change ->
@form.submit();
return
$('#tisk').click ->
window.print()
return
</code>```

答:
html:

```<code><div id="help">
  <div id="napoveda" class="list-group sm">
   <div class="list-group-item doplnovac" data-name="Vitana a.s.                 +" data-adresa="Mělnická 133" data-city="Byšice">Vitana a.s.                 +</div>
   <div class="list-group-item doplnovac" data-name="Vitana,a.s. - catering" data-adresa="Mělnická 133" data-city="Byšice">Vitana,a.s. - catering</div>
  </div>
</div>
</code>```

jquery:

```<code>jQuery ->
  $(document).on "click", ".doplnovac",(event) ->
    $('#event_dodavatel').val $this.data('name')
    $('#event_adresadodavatel').val $this.data('adresa') + ' ' + $this.data('city')
    $('#help').empty()
    event.preventdefault()
    return
  $('#event_dodavatel').keyup ->
  $('#help').empty()
  $.getJSON 'local web/'+$(this).val(), (data) ->
    items=[]
    $.each data.data, (i, item) ->
      items.push("<div class='list-group-item doplnovac' data-name='"+item.Name1+"' data-adresa='"+item.Street+"' data-city='"+item.City+"'>" +item.Name1+ "</div>");
    $('<div>',
      'id': 'napoveda'
      'class': 'list-group sm'
      html: items.join('')).appendTo '#help'
  return
return
</code>```

Body:
I have question, i have input event_dodavatel, on that field is on keyup  declared loading of json. But i can't click on div with id doplnovac.

Can anybody give me hints?

html:

<input type="text" name="event[dodavatel]" id="event_dodavatel" />
<textarea name="event[adresa]" id="event_adresa"></textarea>

fragment of generated autocomplete:

Vitana a.s.                 +

Vitana,a.s. - catering

CoffeScript

String::replaceAll = (stringFind, stringReplace) ->
ex = new RegExp(stringFind.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,
'\\$1'), 'g')
@replace ex, stringReplace

jQuery ->
  $(document).on "click", ".doplnovac",(event) ->
    $('#event_dodavatel').val $this.data('name')
    $('#event_adresadodavatel').val $this.data('adresa') + ' ' + $this.data('city')
    $('#help').empty()
    event.preventdefault()
    return
  $('#event_dodavatel').keyup ->
  $('#help').empty()
  $.getJSON 'local web/'+$(this).val(), (data) ->
    items=[]
    $.each data.data, (i, item) ->
      items.push("
" +item.Name1+ "
");
    $('
',
      'id': 'napoveda'
      'class': 'list-group sm'
      html: items.join('')).appendTo '#help'
  return
return
$('.kalendar').datepicker({ beforeShowDay:
$.datepicker.noWeekends,defaultDate: new Date() });
$('#q_datum_eq').datepicker({ beforeShowDay:
$.datepicker.noWeekends,defaultDate: new Date() });
$('#q_datum_eq').change ->
@form.submit()
return
$('#q_cil_id_eq').change ->
@form.submit();
return
$('#tisk').click ->
window.print()
return

Body:
html:

<div id="help">
  <div id="napoveda" class="list-group sm">
   <div class="list-group-item doplnovac" data-name="Vitana a.s.                 +" data-adresa="Mělnická 133" data-city="Byšice">Vitana a.s.                 +</div>
   <div class="list-group-item doplnovac" data-name="Vitana,a.s. - catering" data-adresa="Mělnická 133" data-city="Byšice">Vitana,a.s. - catering</div>
  </div>
</div>

jquery:

jQuery ->
  $(document).on "click", ".doplnovac",(event) ->
    $('#event_dodavatel').val $this.data('name')
    $('#event_adresadodavatel').val $this.data('adresa') + ' ' + $this.data('city')
    $('#help').empty()
    event.preventdefault()
    return
  $('#event_dodavatel').keyup ->
  $('#help').empty()
  $.getJSON 'local web/'+$(this).val(), (data) ->
    items=[]
    $.each data.data, (i, item) ->
      items.push("<div class='list-group-item doplnovac' data-name='"+item.Name1+"' data-adresa='"+item.Street+"' data-city='"+item.City+"'>" +item.Name1+ "</div>");
    $('<div>',
      'id': 'napoveda'
      'class': 'list-group sm'
      html: items.join('')).appendTo '#help'
  return
return


问:
get synonym of word with JWI
To find synonym of a word, I have below code. There is a one problem with below source code; since word coming from user, I donot know its POS type. Therefore, how can I find IIndexWord of a word in case of I dont know its POS type?

```<code>IIndexWord idxWord = dict . getIndexWord ("dog", POS. NOUN );
IWordID wordID = idxWord . getWordIDs ().get (0) ; // 1st meaning
IWord word = dict . getWord ( wordID );
ISynset synset = word . getSynset ();

for( IWord w : synset . getWords ())
 System .out . println (w. getLemma ());
</code>```

signature of my method looks like;

```<code> void synonym(Strng word)
</code>```

I am going to use word in type of String in place of "dog" word but, at runtime, I dont know its POS type.

I have second problem, before getting its synonym of a word, I want to check whether it is English word or not but JWI does not have a method like isEnglish() or isInDictionary(). How can I check a word whether it is english or not so that I would avoid to look for synonym of non-english word? ( eventually, improve performance)

答:
You can use a simple loop on all the POS value:</p>

```<code>Set<String> lexicon = new HashSet<>();

for (POS p : POS.values()) {
    IIndexWord idxWord = dict.getIndexWord("name", p);
    if (idxWord != null) {
        System.out.println("\t : " + idxWord.getWordIDs().size());
        IWordID wordID = idxWord.getWordIDs().get(0);
        IWord word = dict.getWord(wordID);
        ISynset synset = word.getSynset();
        System.out.print(synset.getWords().size());
        for (IWord w : synset.getWords()) {
            lexicon.add(w.getLemma());
        }

    }
}

for (String s : lexicon) {
    System.out.println("wordnet lexicon : " + s);
}
</code>```

Title: get synonym of word with JWI

Body:
To find synonym of a word, I have below code. There is a one problem with below source code; since word coming from user, I donot know its POS type. Therefore, how can I find IIndexWord of a word in case of I dont know its POS type?

IIndexWord idxWord = dict . getIndexWord ("dog", POS. NOUN );
IWordID wordID = idxWord . getWordIDs ().get (0) ; // 1st meaning
IWord word = dict . getWord ( wordID );
ISynset synset = word . getSynset ();

for( IWord w : synset . getWords ())
 System .out . println (w. getLemma ());

signature of my method looks like;

 void synonym(Strng word)

I am going to use word in type of String in place of "dog" word but, at runtime, I dont know its POS type.

I have second problem, before getting its synonym of a word, I want to check whether it is English word or not but JWI does not have a method like isEnglish() or isInDictionary(). How can I check a word whether it is english or not so that I would avoid to look for synonym of non-english word? ( eventually, improve performance)

Body:
You can use a simple loop on all the POS value:

Set<String> lexicon = new HashSet<>();

for (POS p : POS.values()) {
    IIndexWord idxWord = dict.getIndexWord("name", p);
    if (idxWord != null) {
        System.out.println("\t : " + idxWord.getWordIDs().size());
        IWordID wordID = idxWord.getWordIDs().get(0);
        IWord word = dict.getWord(wordID);
        ISynset synset = word.getSynset();
        System.out.print(synset.getWords().size());
        for (IWord w : synset.getWords()) {
            lexicon.add(w.getLemma());
        }

    }
}

for (String s : lexicon) {
    System.out.println("wordnet lexicon : " + s);
}


问:
Accessing Shadow DOM tree with Selenium
Is it possible to access elements within a Shadow DOM using Selenium/Chrome webdriver?

Using the normal element search methods doesn't work, as is to be expected.   I've seen references to the switchToSubTree spec on w3c, but couldn't locate any actual docs, examples, etc.

Anyone had success with this?

答:
I am using C# and Selenium and managed to find an element inside a nestled shadow DOM using java script.
This is my html tree:

html tree

I want the url on the last line and to get it I first select the "downloads-manager" tag and then the first shadow root right below it.
Once inside the shadow root I want to find the element closest to the next shadow root. That element is "downloads-item". With that selected I can enter the second shadow root. From there I select the img item containing the url by id = "file-icon". At last I can get the attribute "src" which contains the url I am seeking.

The two lines of C# code that does the trick:

```<code>IJavaScriptExecutor jse2 = (IJavaScriptExecutor)_driver;
var pdfUrl = jse2.ExecuteScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('downloads-item').shadowRoot.getElementById('file-icon').getAttribute('src')");
</code>```

Title: Accessing Shadow DOM tree with Selenium

Body:
I am using C# and Selenium and managed to find an element inside a nestled shadow DOM using java script.
This is my html tree:

html tree

I want the url on the last line and to get it I first select the "downloads-manager" tag and then the first shadow root right below it.
Once inside the shadow root I want to find the element closest to the next shadow root. That element is "downloads-item". With that selected I can enter the second shadow root. From there I select the img item containing the url by id = "file-icon". At last I can get the attribute "src" which contains the url I am seeking.

The two lines of C# code that does the trick:

IJavaScriptExecutor jse2 = (IJavaScriptExecutor)_driver;
var pdfUrl = jse2.ExecuteScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('downloads-item').shadowRoot.getElementById('file-icon').getAttribute('src')");


问:
webix no scroll bar in treegrid
As title, no scroll bar even I did the setting below, I tried scroll:"y",scroll:"xy",scroll:true, scrollX:true, scrollY:true, etc. All failed.
I am thinking is it because the view is "treetable".
the code is as below:

let dataTree = function(){
  const  config={
  // container:"testA", //the container is the div Id going to contain the grid, we will addd it @ PlTreeGrid
  view:"treetable",
  //autowidth:true,
  width:'100%',
  //autoheight:true,
  minHeight:530,
  scroll:"xy",
  scroll:"x",
  scroll:"y",
  scrollX:true,
  scrollY:true,
columns:[
{ id:"id", header:"", css:{"text-align":"right"}, width:50, sort:"int"}, //,header:{ height:25 }
{ id:"value", header:"Film title", width:250,
template:"{common.treetable()} #value#", sort:"string" },
//{ id:"chapter", header:"Mode", sort:"string", template:"#value#
Del
", width:300}//width:200, height:'auto'
      { id:"chapter", header:"Mode", sort:"string", width:'auto',fillspace:true}
],
  onDblClick:{
      "webix_remove_upload":function(ev, id){
              console.log("ev,id");console.log(ev,id)
              //this.remove(id);
      }
  },
data: [
{ "id":"1", "value":"The Shawshank Redemption", "open":true, "data":[
{ "id":"1.1", "value":"Part 1 l A", "chapter":"alpha"},
{ "id":"1.2", "value":"Part 2", "chapter":"beta", "open":true, "data":[
{ "id":"1.2.1", "value":"Part 1", "chapter":"beta-twin"}
]},
{ "id":"1.3", "value":"Part 3", "chapter":"gamma" }
]},
{ "id":"2", "value":"The Godfather", "data":[
{ "id":"2.1", "value":"Part 1", "chapter":"alpha" }
]}
]
  }
   let onItemDblClick = function(id, e, node){
     alert("happy" + id, e, node);
  }
  return <TreeGrid config={config} onItemDblClick={onItemDblClick} />```

答:
No problems with the scroll bar.

Your code in snippet : http://webix.com/snippet/78021640
I've just removed any "scroll" attributes, to use the default one.

The scrollbar is only showed when needed. If you use the resizer to reduce the treetable size. The scrollbar will appear when part of content become hidden.

Title: webix no scroll bar in treegrid


问:
Using SAML with JWT for Node API
I'm building an Angular 2 application using SAML2 via the passport-wsfed-saml2 strategy https://github.com/auth0/passport-wsfed-saml2. When I receive a users info back from SAML I generate a JWT token which I use to authenticate a user on an API I am also writing.

So I have two servers, APP/Auth Server is serving my application as well as generating my JWT tokens and API Server has my API. Both servers have a copy of the JWT secret, so when a user sends a request from APP/Auth Server to the API Server I verify the token they sent with their request by verifying it with the secret.

Now for my questions, is it bad practice to have your app served from the same server you use to generate your JWT tokens? If so, what should I do here? Should I be doing more to authenticate a user on my API side?

Something about this just feels dirty....any help would be appreciated.

答:
Having the application and authentication system in the same service is not a malpractice by itself. In general, decoupled services are recommended but this does not mean that the deployment can group services and of course depends on the context

If you are worried about sharing the secret key among servers, you can use an asymmetric key pair (private and public). The private key only needs to be known by the Auth Server in order to sign the JWT. The API Server can use the public key to verify tokens.

Title: Using SAML with JWT for Node API


问:
assertFalse should pass when no arguments in method phpunit
My Test includes the wp_verify_nonce and implemented that in OOP environment.
Now the problem is: If verifyNonce() has no arguemnts passed, then i want to expect return false due to the function:

```<code>verifyNonce():

     public function verifyNonce( $nonce ) {

          if( ! function_exists( 'wp_verify_nonce') || empty( $nonce ) || !is_string( $nonce ) )  return false;

          return wp_verify_nonce( $nonce, $this->action );

     }
</code>```

If $nonce is empty then it should return false since i passed this the if condition!

Now here i'm expecting that when there is no arguements passed, then it should return false:

```<code>testVerifyNonce():

public function testVerifyNonce() {

      $action        = 'my_action';
      $nonce         = '4832552f';

      $myWPNonce     = new test\MY_WP_Nonces( $action );

      \WP_Mock::userFunction( 'wp_verify_nonce', array(

           'times'             =>   3,
           'return_in_order'   =>   array(false, 1, 2)

      ) );

      $this->assertFalse( $myWPNonce->verifyNonce() );

      $this->assertEquals( 1, $myWPNonce->verifyNonce( $nonce ) );

      $this->assertEquals( 2, $myWPNonce->verifyNonce( $nonce ) );

 }
</code>```

Here's the output of my bash console:

```<code>PHPUnit 5.1.7 by Sebastian Bergmann and contributors.

..E....                                                             7 / 7 (100%)

Time: 206 ms, Memory: 8.00Mb

There was 1 error:

1) MYWPNonce_Test::testVerifyNonce
Missing argument 1 for Mywpnonces\src\wpnonce\MY_WP_Nonces::verifyNonce(), called in /mnt/c/Users/hm/Desktop/Github/Mywpnonces/src/tests/wpnonceTest.php on line 76 and defined

/mnt/c/Users/hm/Desktop/Github/Mywpnonces/src/wpnonce.php:37
/mnt/c/Users/hm/Desktop/Github/Mywpnonces/src/tests/wpnonceTest.php:76

FAILURES!
Tests: 7, Assertions: 6, Errors: 1.
</code>```

答:
PHPUnit tests your returning value of $myWPNonce->verifyNonce(). Before this can be accomplished you must pass the parameter, as it is defined in the method as mandatory parameter.

PHPUnit does not test forgotten/missing parameters. PHP itself validates this.

So pass something what should return false there as result.

Body:
My Test includes the wp_verify_nonce and implemented that in OOP environment.
Now the problem is: If verifyNonce() has no arguemnts passed, then i want to expect return false due to the function:

verifyNonce():

     public function verifyNonce( $nonce ) {

          if( ! function_exists( 'wp_verify_nonce') || empty( $nonce ) || !is_string( $nonce ) )  return false;

          return wp_verify_nonce( $nonce, $this->action );

     }

If $nonce is empty then it should return false since i passed this the if condition!

Now here i'm expecting that when there is no arguements passed, then it should return false:

testVerifyNonce():

public function testVerifyNonce() {

      $action        = 'my_action';
      $nonce         = '4832552f';

      $myWPNonce     = new test\MY_WP_Nonces( $action );

      \WP_Mock::userFunction( 'wp_verify_nonce', array(

           'times'             =>   3,
           'return_in_order'   =>   array(false, 1, 2)

      ) );

      $this->assertFalse( $myWPNonce->verifyNonce() );

      $this->assertEquals( 1, $myWPNonce->verifyNonce( $nonce ) );

      $this->assertEquals( 2, $myWPNonce->verifyNonce( $nonce ) );

 }

Here's the output of my bash console:

PHPUnit 5.1.7 by Sebastian Bergmann and contributors.

..E....                                                             7 / 7 (100%)

Time: 206 ms, Memory: 8.00Mb

There was 1 error:

1) MYWPNonce_Test::testVerifyNonce
Missing argument 1 for Mywpnonces\src\wpnonce\MY_WP_Nonces::verifyNonce(), called in /mnt/c/Users/hm/Desktop/Github/Mywpnonces/src/tests/wpnonceTest.php on line 76 and defined

/mnt/c/Users/hm/Desktop/Github/Mywpnonces/src/wpnonce.php:37
/mnt/c/Users/hm/Desktop/Github/Mywpnonces/src/tests/wpnonceTest.php:76

FAILURES!
Tests: 7, Assertions: 6, Errors: 1.


问:
treating allocated memory as a different type
Suppose I allocate some memory.

```<code>char* buffer = (char*)my_malloc(2062);
</code>```

I assign char values to the first 14 bytes from a previously defined array named header.

```<code>memcpy(buffer, header, 14);
</code>```

Then I want to treat the rest of the allocated space as pointers to float.

```<code>float* float_buffer = (float*)(buffer + 14);
some_function(float_buffer);
</code>```

Then at some point later on I need to send all the data out.

```<code>transmit(buffer);
my_free(buffer);
</code>```

Is this correct way to treat memory?  Is the float* cast ok?  I am having issues where I am losing values and not getting the correct results.
My question is:
If you have to treat allocated memory as different types but then send it as char* at the end of the processing.....is this the correct way to do it?

I checked the ptr values and they are the same when they are float* and char* but I am not getting the correct result.

One of my restrictions is that I can only initially allocate one block of memory from a static buffer.  So calling another malloc as a different type (float*) is not allowed.

答:
Conceptually, this is OK - but you have to do some additional work to ensure it will work reliably.

A potential problem is that you cannot just access any arbitrary address as a float.  There may be specific alignment requirements - the address returned by malloc() is required to be correctly aligned for access as any type, but once you add 14 to that address, all bets are off (except for char).

To ensure the correct alignment, you must ensure that the address you add to buffer is a multiple of sizeof(float).  You can do that by adding padding using the following formula:

```<code>#define PAD_OFFSET(offset, type) ((offset) + sizeof(type) - 1) & ~(sizeof(type) - 1))

float *float_buffer = (float *)(buffer + PAD_OFFSET(14, float));
</code>```

Note that this will create a gap - padding - between your chars and your floats.

Alternatively, you can define a struct, and the compiler will figure the padding out for you.  This uses a C99 feature called a flexible array member:

```<code>struct foo {
    char abc[14];
    float xyz[];
};

struct foo *buffer = malloc(2062);
memcpy(&buffer->abc, header, 14);
some_function(&buffer->xyz);
transmit(buffer); /* Presuming transmit() expects a void * parameter. */
</code>```

If you wish to do it without padding, you cannot directly access the memory in buffer as floats - you will have to create a temporary array and copy it in:

```<code>float temp[500]; /* Or whatever size */
some_function(&temp);
memcpy(buffer + 14, temp, sizeof temp);
</code>```

Body:
Suppose I allocate some memory.

char* buffer = (char*)my_malloc(2062);

I assign char values to the first 14 bytes from a previously defined array named header.

memcpy(buffer, header, 14);

Then I want to treat the rest of the allocated space as pointers to float.

float* float_buffer = (float*)(buffer + 14);
some_function(float_buffer);

Then at some point later on I need to send all the data out.

transmit(buffer);
my_free(buffer);

Is this correct way to treat memory?  Is the float* cast ok?  I am having issues where I am losing values and not getting the correct results.
My question is:
If you have to treat allocated memory as different types but then send it as char* at the end of the processing.....is this the correct way to do it?

I checked the ptr values and they are the same when they are float* and char* but I am not getting the correct result.

One of my restrictions is that I can only initially allocate one block of memory from a static buffer.  So calling another malloc as a different type (float*) is not allowed.

Body:
Conceptually, this is OK - but you have to do some additional work to ensure it will work reliably.

A potential problem is that you cannot just access any arbitrary address as a float.  There may be specific alignment requirements - the address returned by malloc() is required to be correctly aligned for access as any type, but once you add 14 to that address, all bets are off (except for char).

To ensure the correct alignment, you must ensure that the address you add to buffer is a multiple of sizeof(float).  You can do that by adding padding using the following formula:

#define PAD_OFFSET(offset, type) ((offset) + sizeof(type) - 1) & ~(sizeof(type) - 1))

float *float_buffer = (float *)(buffer + PAD_OFFSET(14, float));

Note that this will create a gap - padding - between your chars and your floats.

Alternatively, you can define a struct, and the compiler will figure the padding out for you.  This uses a C99 feature called a flexible array member:

struct foo {
    char abc[14];
    float xyz[];
};

struct foo *buffer = malloc(2062);
memcpy(&buffer->abc, header, 14);
some_function(&buffer->xyz);
transmit(buffer); /* Presuming transmit() expects a void * parameter. */

If you wish to do it without padding, you cannot directly access the memory in buffer as floats - you will have to create a temporary array and copy it in:

float temp[500]; /* Or whatever size */
some_function(&temp);
memcpy(buffer + 14, temp, sizeof temp);


问:
React / Redux conditionally applying style
In my React & Redux App, I am trying to show/hide a div based on state returned by Redux. Here is my code:

```<code><div
    className="notify-success"
    style={{  ({this.props.terms}) ? "" : "display: 'none'" }}
>
    Saved successfully!
</div>
</code>```

But its not working for me, instead throwing an error!

答:
Put the condition on value, Use this:</p>

```<code>style={{'display': this.props.terms ? "" : 'none' }}
</code>```

Body:
In my React & Redux App, I am trying to show/hide a div based on state returned by Redux. Here is my code:

    Saved successfully!

But its not working for me, instead throwing an error!

Body:
Put the condition on value, Use this:

style={{'display': this.props.terms ? "" : 'none' }}


问:
Java UTF-8 not working properly for JSON
I am using spring rest template for getting rest API.

When I try to print the output, I get unwanted Characters.

Here is my code:

```<code>RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> apiResponse = restTemplate.getForEntity(url,String.class);
        return apiResponse.getBody();
</code>```

Output is:

```<code>ï»¿{"status":"FAILURE","error_code":"ITI","message":"Invalid Transaction Id","time":"30-03-2017 11:47:32"}
</code>```

After getting this error I added UTF-8 Charecter encoding in the rest client:

```<code>public static String exicute(String url) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("utf-8")));
        ResponseEntity<String> apiResponse = restTemplate.getForEntity(url,String.class);
        return apiResponse.getBody();
    }
</code>```

After that OUTPUT GOT changed but now ? in front of the result.

```<code>?{"status":"FAILURE","error_code":"ITI","message":"Invalid Transaction Id","time":"30-03-2017 11:49:34"}
</code>```

How can i solve this issue?

答:
ï»¿ in front of the message is because the input stream has a byte order mark (BOM) at the beginning of the stream. The byte order mark is a Unicode character often at the beginning of the byte sequence which signals that the following bytes are encoded in UTF-8.

The character itself is often encoded as UTF-8 as well. It is then encoded as 0xEF,0xBB,0xBF, and it is often displayed as ï»¿.

its only use in UTF-8 is to signal at the start that the text stream is encoded in UTF-8

That character is actually not part of the contents itself; instead it is merely a piece of metadata.

How to fix it?

The creator of the byte sequence (often a file, but it can also be some byte stream over the network) should remove it, in my opinion.

But on the other hand, you can easily remove it by replacing the character by an empty string.

```<code>string.replace("\uFEFF", "");
</code>```

code piece copied from this post

Body:
I am using spring rest template for getting rest API.

When I try to print the output, I get unwanted Characters.

Here is my code:

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> apiResponse = restTemplate.getForEntity(url,String.class);
        return apiResponse.getBody();

Output is:

ï»¿{"status":"FAILURE","error_code":"ITI","message":"Invalid Transaction Id","time":"30-03-2017 11:47:32"}

After getting this error I added UTF-8 Charecter encoding in the rest client:

public static String exicute(String url) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("utf-8")));
        ResponseEntity<String> apiResponse = restTemplate.getForEntity(url,String.class);
        return apiResponse.getBody();
    }

After that OUTPUT GOT changed but now ? in front of the result.

?{"status":"FAILURE","error_code":"ITI","message":"Invalid Transaction Id","time":"30-03-2017 11:49:34"}

How can i solve this issue?

Body:
ï»¿ in front of the message is because the input stream has a byte order mark (BOM) at the beginning of the stream. The byte order mark is a Unicode character often at the beginning of the byte sequence which signals that the following bytes are encoded in UTF-8.

The character itself is often encoded as UTF-8 as well. It is then encoded as 0xEF,0xBB,0xBF, and it is often displayed as ï»¿.

its only use in UTF-8 is to signal at the start that the text stream is encoded in UTF-8

That character is actually not part of the contents itself; instead it is merely a piece of metadata.

How to fix it?

The creator of the byte sequence (often a file, but it can also be some byte stream over the network) should remove it, in my opinion.

But on the other hand, you can easily remove it by replacing the character by an empty string.

string.replace("\uFEFF", "");

code piece copied from this post


问:
Payment to this merchant is not allowed in android while integrating paypal
I am using sandbox account and following the tutorial http://androiddevelopmentanddiscussion.blogspot.com/2014/05/paypal-integration-in-android.html

I have given the client id which i have achieved by logging into sandbox account from my selling tools->api access

Here is my code:

```<code>private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;

    // note that these credentials will differ between live & sandbox environments.
    private static final String CONFIG_CLIENT_ID = "";

    private static final int REQUEST_CODE_PAYMENT = 1;
    private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;

    private static PayPalConfiguration config = new PayPalConfiguration()
            .environment(CONFIG_ENVIRONMENT)
            .clientId(CONFIG_CLIENT_ID)
            // The following are only used in PayPalFuturePaymentActivity.
            .merchantName(" ")
            .merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
            .merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));

    PayPalPayment thingToBuy;

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

        Intent intent = new Intent(this, PayPalService.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
        startService(intent);

    }

    public void onBuyPressed(View pressed) {
        // PAYMENT_INTENT_SALE will cause the payment to complete immediately.
        // Change PAYMENT_INTENT_SALE to PAYMENT_INTENT_AUTHORIZE to only authorize payment and
        // capture funds later.

        if(pressed.getId() == R.id.button1){
            thingToBuy = new PayPalPayment(new BigDecimal("8"), "USD", "Painting 1", PayPalPayment.PAYMENT_INTENT_SALE);
        }else if(pressed.getId() == R.id.button2){
            thingToBuy = new PayPalPayment(new BigDecimal("4"), "USD", "Painting 2", PayPalPayment.PAYMENT_INTENT_SALE);
        }

        Intent intent = new Intent(MainActivity.this, PaymentActivity.class);

        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);

        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }

    public void onFuturePaymentPressed(View pressed) {
        Intent intent = new Intent(MainActivity.this, PayPalFuturePaymentActivity.class);

        startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PaymentConfirmation confirm =
                        data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirm != null) {
                    try {
                        Log.i(TAG, confirm.toJSONObject().toString(4));
                        Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));

                        Toast.makeText(
                                getApplicationContext(),
                                "PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG)
                                .show();

                    } catch (JSONException e) {
                        Log.e(TAG, "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i(TAG, "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i(TAG,"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        } else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PayPalAuthorization auth =
                        data.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
                if (auth != null) {
                    try {
                        Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));

                        String authorization_code = auth.getAuthorizationCode();
                        Log.i("FuturePaymentExample", authorization_code);

                        sendAuthorizationToServer(auth);
                        Toast.makeText(
                                getApplicationContext(),
                                "Future Payment code received from PayPal", Toast.LENGTH_LONG)
                                .show();

                    } catch (JSONException e) {
                        Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i("FuturePaymentExample", "The user canceled.");
            } else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i(
                        "FuturePaymentExample",
                        "Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
            }
        }
    }

    private void sendAuthorizationToServer(PayPalAuthorization authorization) {

    }

    public void onFuturePaymentPurchasePressed(View pressed) {
        // Get the Application Correlation ID from the SDK
        String correlationId = PayPalConfiguration.getApplicationCorrelationId(this);

        Log.i("FuturePaymentExample", "Application Correlation ID: " + correlationId);

        // TODO: Send correlationId and transaction details to your server for processing with
        // PayPal...
        Toast.makeText(
                getApplicationContext(), "App Correlation ID received from SDK", Toast.LENGTH_LONG)
                .show();
    }

    @Override
    public void onDestroy() {
        // Stop service when done
        stopService(new Intent(this, PayPalService.class));
        super.onDestroy();
    }
</code>```

Here is the log message:

```<code>01-12 06:32:04.143: E/paypal.sdk(1778): request failure with http statusCode:401,exception:org.apache.http.client.HttpResponseException: Unauthorized
01-12 06:32:04.143: E/paypal.sdk(1778): request failed with server response:{"error":"invalid_client","error_description":"The client credentials are invalid"}
01-12 06:32:04.143: E/PayPalService(1778): invalid_client
</code>```

I am new in this topic so explanation would be nice.

答:
Use your sandbox credential (Client id) here.

```<code>private static final String CONFIG_CLIENT_ID = "";
</code>```

Or follow below links:

Paypal integration using SDK

Paypal integration using gradle integration

Body:
I am using sandbox account and following the tutorial http://androiddevelopmentanddiscussion.blogspot.com/2014/05/paypal-integration-in-android.html

I have given the client id which i have achieved by logging into sandbox account from my selling tools->api access

Here is my code:

private static final String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;

    // note that these credentials will differ between live & sandbox environments.
    private static final String CONFIG_CLIENT_ID = "";

    private static final int REQUEST_CODE_PAYMENT = 1;
    private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;

    private static PayPalConfiguration config = new PayPalConfiguration()
            .environment(CONFIG_ENVIRONMENT)
            .clientId(CONFIG_CLIENT_ID)
            // The following are only used in PayPalFuturePaymentActivity.
            .merchantName(" ")
            .merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
            .merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));

    PayPalPayment thingToBuy;

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

        Intent intent = new Intent(this, PayPalService.class);
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
        startService(intent);

    }

    public void onBuyPressed(View pressed) {
        // PAYMENT_INTENT_SALE will cause the payment to complete immediately.
        // Change PAYMENT_INTENT_SALE to PAYMENT_INTENT_AUTHORIZE to only authorize payment and
        // capture funds later.

        if(pressed.getId() == R.id.button1){
            thingToBuy = new PayPalPayment(new BigDecimal("8"), "USD", "Painting 1", PayPalPayment.PAYMENT_INTENT_SALE);
        }else if(pressed.getId() == R.id.button2){
            thingToBuy = new PayPalPayment(new BigDecimal("4"), "USD", "Painting 2", PayPalPayment.PAYMENT_INTENT_SALE);
        }

        Intent intent = new Intent(MainActivity.this, PaymentActivity.class);

        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);

        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }

    public void onFuturePaymentPressed(View pressed) {
        Intent intent = new Intent(MainActivity.this, PayPalFuturePaymentActivity.class);

        startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PaymentConfirmation confirm =
                        data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirm != null) {
                    try {
                        Log.i(TAG, confirm.toJSONObject().toString(4));
                        Log.i(TAG, confirm.getPayment().toJSONObject().toString(4));

                        Toast.makeText(
                                getApplicationContext(),
                                "PaymentConfirmation info received from PayPal", Toast.LENGTH_LONG)
                                .show();

                    } catch (JSONException e) {
                        Log.e(TAG, "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i(TAG, "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i(TAG,"An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        } else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PayPalAuthorization auth =
                        data.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
                if (auth != null) {
                    try {
                        Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));

                        String authorization_code = auth.getAuthorizationCode();
                        Log.i("FuturePaymentExample", authorization_code);

                        sendAuthorizationToServer(auth);
                        Toast.makeText(
                                getApplicationContext(),
                                "Future Payment code received from PayPal", Toast.LENGTH_LONG)
                                .show();

                    } catch (JSONException e) {
                        Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i("FuturePaymentExample", "The user canceled.");
            } else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i(
                        "FuturePaymentExample",
                        "Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
            }
        }
    }

    private void sendAuthorizationToServer(PayPalAuthorization authorization) {

    }

    public void onFuturePaymentPurchasePressed(View pressed) {
        // Get the Application Correlation ID from the SDK
        String correlationId = PayPalConfiguration.getApplicationCorrelationId(this);

        Log.i("FuturePaymentExample", "Application Correlation ID: " + correlationId);

        // TODO: Send correlationId and transaction details to your server for processing with
        // PayPal...
        Toast.makeText(
                getApplicationContext(), "App Correlation ID received from SDK", Toast.LENGTH_LONG)
                .show();
    }

    @Override
    public void onDestroy() {
        // Stop service when done
        stopService(new Intent(this, PayPalService.class));
        super.onDestroy();
    }

Here is the log message:

01-12 06:32:04.143: E/paypal.sdk(1778): request failure with http statusCode:401,exception:org.apache.http.client.HttpResponseException: Unauthorized
01-12 06:32:04.143: E/paypal.sdk(1778): request failed with server response:{"error":"invalid_client","error_description":"The client credentials are invalid"}
01-12 06:32:04.143: E/PayPalService(1778): invalid_client

I am new in this topic so explanation would be nice.

Body:
Use your sandbox credential (Client id) here.

private static final String CONFIG_CLIENT_ID = "";

Or follow below links:

Paypal integration using SDK

Paypal integration using gradle integration


问:
Need to check dropdown opened state in toolstripmenu item from menustrip
I need to check if dropdown is opened or not in toolstripmenuitem. Iam used this below code.

```<code>foreach (ToolStripMenuItem Tm_items in menustrp.Items){
       if (Tm_items.DropDown.Visible == true){

       }
}
</code>```

here iam using visible  to check, But that doesnt work for my condition.It shows only if it is visible. I need to check once the dropdown is opened.

I want to check something like this ..

```<code> if(Tm_items.DropDown.opened == true)
{
   here i want to do something.

}
</code>```

Please help me out.  iam trying this for past 2 days. It will be more helpfull for me if there is a solution.

Thanks,
sridhar

答:
Posting this as answer since it contains code

In your Form's constructor you could do something like this:

```<code>public Form1() {

      InitializeComponent();

      foreach (ToolStripMenuItem Tm_items in menustrp.Items) {
        Tm_items.DropDownOpened += (sender, args) => {
          MessageBox.Show("Open"); // Perform logic here
        };

      }
}
</code>```

Subscribe to the according Event which tells you, if the Dropdown was opened.

You might also subscribe to the DropDownClosed-event if you want to take care if it was closed again

Note

This only handles the First-Level-Items of your Menu!

Body:
I need to check if dropdown is opened or not in toolstripmenuitem. Iam used this below code.

foreach (ToolStripMenuItem Tm_items in menustrp.Items){
       if (Tm_items.DropDown.Visible == true){

       }
}

here iam using visible  to check, But that doesnt work for my condition.It shows only if it is visible. I need to check once the dropdown is opened.

I want to check something like this ..

 if(Tm_items.DropDown.opened == true)
{
   here i want to do something.

}

Please help me out.  iam trying this for past 2 days. It will be more helpfull for me if there is a solution.

Thanks,
sridhar

Body:
Posting this as answer since it contains code

In your Form's constructor you could do something like this:

public Form1() {

      InitializeComponent();

      foreach (ToolStripMenuItem Tm_items in menustrp.Items) {
        Tm_items.DropDownOpened += (sender, args) => {
          MessageBox.Show("Open"); // Perform logic here
        };

      }
}

Subscribe to the according Event which tells you, if the Dropdown was opened.

You might also subscribe to the DropDownClosed-event if you want to take care if it was closed again

Note

This only handles the First-Level-Items of your Menu!


问:
Playgrounds broken in Xcode 8.3
Since I started working Xcode 8.2 (and 8.3 lately), playgrounds are completely broken for me.

When opening a playground I see the message "Failed to launch process. Error returned in reply: Connection Interrupted"

Complete re-installation of Xcode or removing / re-creating /private/tmp folder (as suggested by some other posts) did not help.

Did someone encounter a similar problem? Are there other known work-arounds?
(http://www.openradar.me/31296836)

Here is some sample output from CoreSimulator.log

```<code>Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error from finding pasteboard support port, Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:40 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error from finding pasteboard support port, Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
</code>```

答:
workaround provided by an engineer at apple
run below command in terminal after quitting Xcode
defaults write com.apple.dt.xcode IDEPlaygroundDisableSimulatorAlternateFramebuffer -bool YES

Title: Playgrounds broken in Xcode 8.3

Body:
Since I started working Xcode 8.2 (and 8.3 lately), playgrounds are completely broken for me.

When opening a playground I see the message "Failed to launch process. Error returned in reply: Connection Interrupted"

Complete re-installation of Xcode or removing / re-creating /private/tmp folder (as suggested by some other posts) did not help.

Did someone encounter a similar problem? Are there other known work-arounds?
(http://www.openradar.me/31296836)

Here is some sample output from CoreSimulator.log

Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:30 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error looking up host support port: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error from finding pasteboard support port, Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook CoreSimulatorService[5859] <Error>: Error Domain=com.apple.CoreSimulator.SimError Code=163 "Unable to lookup in current state: Shutting Down" UserInfo={NSLocalizedDescription=Unable to lookup in current state: Shutting Down}
Mar 28 16:19:40 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}
Mar 28 16:19:40 sergey-macbook com.apple.dt.Xcode[6955] <Error>: Error from finding pasteboard support port, Error Domain=NSPOSIXErrorDomain Code=53 "Software caused connection abort" UserInfo={NSLocalizedDescription=Error returned in reply: Connection interrupted}


问:
Mutex gone wrong?
I am trying Pthreads and its pretty basic program: I have two shared variables (declared global) among all threads

```<code>long Sum = 0;
long Sum1 = 0;
pthread_mutex_t mutexLock = PTHREAD_MUTEX_INITIALIZER;
</code>```

In thread function:

```<code>for(int i=start; i<end; i++) //start and end are being passed to thread and they are being passed correctly
{
 pthread_mutex_lock(&mutexLock);
 Sum1+=i;
 Sum+=Sum1;
 pthread_mutex_unlock(&mutexLock);
}
</code>```

main() in case one needs for reference:

```<code>int main()

{

pthread_t threadID[10];

for(int i=0; i<10; i++)
{
 int a = (i*500) + 1;
 int b =(i + 1)*500;

 ThreadStruct* obj = new ThreadStruct(a,b);
 pthread_create(&threadID[i],NULL,ThreadFunc,obj);
}

for(int i=0; i<10; i++)
{
  pthread_join(threadID[i], NULL);
}

cout<<"Sum: "<<Sum<<endl;
cout<<"Sum1: "<<Sum1<<endl;

return 0;

}
</code>```

OUTPUT

Sum: 40220835000
Sum1: 12502500

Run again

Sum: 38720835000
Sum1: 12502500

Run again

Sum: 39720835000
Sum1: 12502500

PROBLEM

Why I am getting a different value for Sum in each iteration?
Rest whole code is working ok and output of Sum1 is correct - no matter how much times do I run the code. (Only issue is in Sum). Am I doing something wrong in use of mutex here?

UPDATE

If I use local variables as @molbdnilo specified in his well detailed answer, this problem is solved. In start, I thought that mutex is irrelevant here but I tested it a number of times and observed the cases when not using a mutex results in recurrence of this problem. So, solution of this problem (courtesy: Answer by @molbdnilo) is to use local variables WITH mutex and I have tested it to work perfectly!

答:
It's not a threading problem – the problem is that even though the order of additions to Sum1 doesn't matter, the order of additions to Sum does.

Consider the much shorter sum 1 + 2 + 3 and the following interleavings

1:

```<code>Sum1 = 1 + 2 = 3
Sum = 0 + 3 = 3
Sum1 = 3 + 3 = 6
Sum = 3 + 6 = 9
</code>```

2:

```<code>Sum1 = 1 + 3 = 4
Sum =  0 + 4 = 4
Sum1 = 4 + 2 = 6
Sum = 4 + 6 = 10
</code>```

3:

```<code>Sum1 = 2 + 3 = 5
Sum =  0 + 5 = 5
Sum1 = 5 + 1 = 6
Sum = 5 + 6 = 11
</code>```

You could solve this by having the threads compute their own sum-of-sums independently and adding them afterwards.

(Notice that there's no concurrent mutation here, so locking anything can't make any difference.)

For a more concrete example, let's limit your program to two threads and the sum from 1 to 6.

You then have one thread computing 1 + 2 + 3 and one doing 4 + 5 + 6.

At a glance, thread one should also compute 1 + (1 + 2) + (1 + 2 + 3) and thread 2, 4 + (4 + 5) + (4 + 5 + 6).

Except they don't – every time they use it, Sum may have been modified by the other thread.

So thread one may compute 1 + ((1 + 4) + 2) + ((1 + 4) + 2 + 3), or something else.

When you use local variables, you keep each thread's result independent of the others.

(I think this problem is a pretty good illustration of how shared mutable state can complicate things in unexpected ways, by the way.)

Title: Mutex gone wrong?

Body:
I am trying Pthreads and its pretty basic program: I have two shared variables (declared global) among all threads

long Sum = 0;
long Sum1 = 0;
pthread_mutex_t mutexLock = PTHREAD_MUTEX_INITIALIZER;

In thread function:

for(int i=start; i<end; i++) //start and end are being passed to thread and they are being passed correctly
{
 pthread_mutex_lock(&mutexLock);
 Sum1+=i;
 Sum+=Sum1;
 pthread_mutex_unlock(&mutexLock);
}

main() in case one needs for reference:

int main()

{

pthread_t threadID[10];

for(int i=0; i<10; i++)
{
 int a = (i*500) + 1;
 int b =(i + 1)*500;

 ThreadStruct* obj = new ThreadStruct(a,b);
 pthread_create(&threadID[i],NULL,ThreadFunc,obj);
}

for(int i=0; i<10; i++)
{
  pthread_join(threadID[i], NULL);
}

cout<<"Sum: "<<Sum<<endl;
cout<<"Sum1: "<<Sum1<<endl;

return 0;

}

OUTPUT

Sum: 40220835000
Sum1: 12502500

Run again

Sum: 38720835000
Sum1: 12502500

Run again

Sum: 39720835000
Sum1: 12502500

PROBLEM

Why I am getting a different value for Sum in each iteration?
Rest whole code is working ok and output of Sum1 is correct - no matter how much times do I run the code. (Only issue is in Sum). Am I doing something wrong in use of mutex here?

UPDATE

If I use local variables as @molbdnilo specified in his well detailed answer, this problem is solved. In start, I thought that mutex is irrelevant here but I tested it a number of times and observed the cases when not using a mutex results in recurrence of this problem. So, solution of this problem (courtesy: Answer by @molbdnilo) is to use local variables WITH mutex and I have tested it to work perfectly!

Body:
It's not a threading problem – the problem is that even though the order of additions to Sum1 doesn't matter, the order of additions to Sum does.

Consider the much shorter sum 1 + 2 + 3 and the following interleavings

1:

Sum1 = 1 + 2 = 3
Sum = 0 + 3 = 3
Sum1 = 3 + 3 = 6
Sum = 3 + 6 = 9

2:

Sum1 = 1 + 3 = 4
Sum =  0 + 4 = 4
Sum1 = 4 + 2 = 6
Sum = 4 + 6 = 10

3:

Sum1 = 2 + 3 = 5
Sum =  0 + 5 = 5
Sum1 = 5 + 1 = 6
Sum = 5 + 6 = 11

You could solve this by having the threads compute their own sum-of-sums independently and adding them afterwards.

(Notice that there's no concurrent mutation here, so locking anything can't make any difference.)

For a more concrete example, let's limit your program to two threads and the sum from 1 to 6.

You then have one thread computing 1 + 2 + 3 and one doing 4 + 5 + 6.

At a glance, thread one should also compute 1 + (1 + 2) + (1 + 2 + 3) and thread 2, 4 + (4 + 5) + (4 + 5 + 6).

Except they don't – every time they use it, Sum may have been modified by the other thread.

So thread one may compute 1 + ((1 + 4) + 2) + ((1 + 4) + 2 + 3), or something else.

When you use local variables, you keep each thread's result independent of the others.

(I think this problem is a pretty good illustration of how shared mutable state can complicate things in unexpected ways, by the way.)


问:
Charset changes after uploading a file in a Java environment under Apache HTTP
I have a project running in a standalone WildFly that is working fine locally under Eclipse, but the same project running on WildFly in a remote server under Apache HTTP is getting special characters corrupted after submitting a file. For example:

Before submit a file:

After submit a file:

OS: Linux

Using: JSF 2.2, Java 8, WildFly 10 and Apache HTTP 2.4

All the XHTML files are encoded with UTF-8 and the head contains the meta tag:

```<code><meta http-equiv="restrict-type" content="text/html; charset=UTF-8" />
</code>```

I've already tried:

→ Form with the 'charset' param in the enctype attribute:

```<code><h:form id="fileForm" enctype="multipart/form-data;charset=UTF-8">
</code>```

→ Running WildFly with the argument:

```<code>-Dfile.encoding=UTF-8
</code>```

→ Enable the following option in httpd.conf:

```<code>AddDefaultCharset UTF-8
</code>```

I don't know what I'm missing... Did anyone know a solution to this problem? I would appreciate any help. Thank you in advance and sorry for the bad English.

答:
with what character set is the OS running? what do you get from echo $LANG, echo $LC_CTYPE or echo $LC_ALL? Could be that somewhere the default charset of the OS is used.

I once had similar problems when running a Wildfly application in a Kubernetes pod on Google Container Engine. There was no encoding set at all, so I had to set the following environments variables before starting the application server:

```<code>ENV LANG=en_US.UTF-8
ENV LANGUAGE=en_US.UTF-8
ENV LC_ALL=en_US.UTF-8
</code>```

So check what is set in your OS and set the env variables according to your needs before starting WildFly.

Edit: According to the comments, this seems to be a problem of the Apache running as proxy. I'm no specialist here, but perhaps this answer from superuser can help you further.

Body:
I have a project running in a standalone WildFly that is working fine locally under Eclipse, but the same project running on WildFly in a remote server under Apache HTTP is getting special characters corrupted after submitting a file. For example:

Before submit a file:

After submit a file:

OS: Linux

Using: JSF 2.2, Java 8, WildFly 10 and Apache HTTP 2.4

All the XHTML files are encoded with UTF-8 and the head contains the meta tag:

<meta http-equiv="restrict-type" content="text/html; charset=UTF-8" />

I've already tried:

→ Form with the 'charset' param in the enctype attribute:

<h:form id="fileForm" enctype="multipart/form-data;charset=UTF-8">

→ Running WildFly with the argument:

-Dfile.encoding=UTF-8

→ Enable the following option in httpd.conf:

AddDefaultCharset UTF-8

I don't know what I'm missing... Did anyone know a solution to this problem? I would appreciate any help. Thank you in advance and sorry for the bad English.

Body:
with what character set is the OS running? what do you get from echo $LANG, echo $LC_CTYPE or echo $LC_ALL? Could be that somewhere the default charset of the OS is used.

I once had similar problems when running a Wildfly application in a Kubernetes pod on Google Container Engine. There was no encoding set at all, so I had to set the following environments variables before starting the application server:

ENV LANG=en_US.UTF-8
ENV LANGUAGE=en_US.UTF-8
ENV LC_ALL=en_US.UTF-8

So check what is set in your OS and set the env variables according to your needs before starting WildFly.

Edit: According to the comments, this seems to be a problem of the Apache running as proxy. I'm no specialist here, but perhaps this answer from superuser can help you further.


问:
What CSS Selector to use to remove property from nested class?

 .row {
      padding-left: 15px;
      padding-right: 15px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="row">
       <div class="col"> </div>
       <div class="col"> </div>
       <div class="col row">
           <div class="col"> </div>
           <div class="col"> </div>
       </div>
    </div></code>```

What I need:

To remove the paddings on ALL nested and deeply row class

.row > .row would not suffice since it only affects one layer deep

答:
Simply use .row, .row .row

.row {
  padding: 15px;
  border: 1px solid #ddd;
  min-height: 10px;
}

.row,
.row .row {
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
   <div class="col"> </div>
   <div class="col"> </div>
   <div class="col row">
       <div class="col"> </div>
       <div class="col"> </div>
   </div>
</div></code>```

Body:
 .row {
      padding-left: 15px;
      padding-right: 15px;
    }

What I need:

To remove the paddings on ALL nested and deeply row class

.row > .row would not suffice since it only affects one layer deep

Body:
Simply use .row, .row .row

.row {
  padding: 15px;
  border: 1px solid #ddd;
  min-height: 10px;
}

.row,
.row .row {
  padding: 0;
}

<div class="row">
   <div class="col"> </div>
   <div class="col"> </div>
   <div class="col row">
       <div class="col"> </div>
       <div class="col"> </div>
   </div>
</div>