问:
Spring Security OAuth - Provider Manager is Not Configured for Null Resource
Am trying to use Spring Secruity's OAuth API to obtain an access token from an externally published API.

This curl command works (and its contents are all that I need to obtain an access token):

```<code>curl -X POST \
https://api.app.com/v1/oauth/token \
  -H 'content-type: application/x-www-form-urlencoded' \
  -d'grant_type=client_credentials&client_id=bcfrtew123&client_secret=Y67493012'
</code>```

Am able to obtain an access token from the external service after running this curl command.

When using Spring Security OAuth API:

```<code><dependency>
   <groupId>org.springframework.security.oauth</groupId>
     <artifactId>spring-security-oauth2</artifactId>
     <version>2.1.1.RELEASE</version>
</dependency>
</code>```

Setup my SpringMVC Controller's method like this:

```<code>@RequestMapping(value = "/getAccessToken", method = RequestMethod.POST, consumes="application/x-www-form-urlencoded")
public OAuth2AccessToken getAccessToken(@RequestParam(value="client_id", required=true) String clientId, @RequestParam(value="client_secret", required=true) String clientSecret) throws Exception {
    String tokenUri = "https://api.app.com/v1/oauth/token";

    ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();

    resourceDetails.setAccessTokenUri(tokenUri);
    resourceDetails.setClientId(clientId);
    resourceDetails.setClientSecret(clientSecret);
    resourceDetails.setGrantType("client_credentials");
    resourceDetails.setScope(Arrays.asList("read", "write"));

    DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

    oauth2RestTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);

    OAuth2AccessToken token = oauth2RestTemplate.getAccessToken();
    return token;
}
</code>```

When I invoke the getAccessToken call from my local tomcat instance:

```<code>access_denied
error_description=Unable to obtain a new access token for resource 'null'.
The provider manager is not configured to support it.
</code>```

Question(s):

What am I missing here? Is there some annotation required for this? Is there a property that is not set or is needed?

(Please notice that the content-type needs to be "application/x-www-form-urlencoded"...)

How can I mimic the working curl command using Spring Security OAuth API?

Could it be the default values that I have set in the RequestParameters?

If successful, how can I set it up so that access token is always preloaded before any request made?

答:
This could be oocured beacuse server doest not recognize the content type you posting to that specific url.
In your CURL request try include the 'content-type: application/x-www-form-urlencoded' for custom conrtroller using http headers.

Also you have not set username and password for resourceDetails.
resourceDetails.setUserName("user");
resourceDetails.setUserName("password");

if those does not work try to extract the request that Encoded with application/x-www-form-urlencoded and pass it as a string via RestTemplate and you can get the token.

Let me know any if you need additional support.

Try the code below that is giving token as and string response.

Body:
Am trying to use Spring Secruity's OAuth API to obtain an access token from an externally published API.

This curl command works (and its contents are all that I need to obtain an access token):

curl -X POST \
https://api.app.com/v1/oauth/token \
  -H 'content-type: application/x-www-form-urlencoded' \
  -d'grant_type=client_credentials&client_id=bcfrtew123&client_secret=Y67493012'

Am able to obtain an access token from the external service after running this curl command.

When using Spring Security OAuth API:

<dependency>
   <groupId>org.springframework.security.oauth</groupId>
     <artifactId>spring-security-oauth2</artifactId>
     <version>2.1.1.RELEASE</version>
</dependency>

Setup my SpringMVC Controller's method like this:

@RequestMapping(value = "/getAccessToken", method = RequestMethod.POST, consumes="application/x-www-form-urlencoded")
public OAuth2AccessToken getAccessToken(@RequestParam(value="client_id", required=true) String clientId, @RequestParam(value="client_secret", required=true) String clientSecret) throws Exception {
    String tokenUri = "https://api.app.com/v1/oauth/token";

    ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();

    resourceDetails.setAccessTokenUri(tokenUri);
    resourceDetails.setClientId(clientId);
    resourceDetails.setClientSecret(clientSecret);
    resourceDetails.setGrantType("client_credentials");
    resourceDetails.setScope(Arrays.asList("read", "write"));

    DefaultOAuth2ClientContext clientContext = new DefaultOAuth2ClientContext();

    oauth2RestTemplate = new OAuth2RestTemplate(resourceDetails, clientContext);

    OAuth2AccessToken token = oauth2RestTemplate.getAccessToken();
    return token;
}

When I invoke the getAccessToken call from my local tomcat instance:

access_denied
error_description=Unable to obtain a new access token for resource 'null'.
The provider manager is not configured to support it.

Question(s):

What am I missing here? Is there some annotation required for this? Is there a property that is not set or is needed?

(Please notice that the content-type needs to be "application/x-www-form-urlencoded"...)

How can I mimic the working curl command using Spring Security OAuth API?

Could it be the default values that I have set in the RequestParameters?

If successful, how can I set it up so that access token is always preloaded before any request made?


来源: stackexchange

问:
How to sort json in reverse alphabetical order using gulp-json-sort plugin
With gulp-json-sort I was able to sort a JSON file in alphabetical order. But I don't understand how to use its API to sort in reverse alphabetical order. I tried the following with no avail, it's still sorting in alphabetical order as if I weren't using any function inside sortJSON():</p>

```<code>sortJSON({
  function (a, b) {
    return a.key < b.key ? 1 : -1;
}})
</code>```

答:
I figured it out myself, according to their API I had to use it as follows:

```<code>sortJSON({
  cmp: function (a, b) {
    return a.key < b.key ? 1 : -1;
}})
</code>```

It'd have been better if the README of the plugin provided an example! :)

ContentLicense: CC BY-SA 3.0

Body:
With gulp-json-sort I was able to sort a JSON file in alphabetical order. But I don't understand how to use its API to sort in reverse alphabetical order. I tried the following with no avail, it's still sorting in alphabetical order as if I weren't using any function inside sortJSON():

sortJSON({
  function (a, b) {
    return a.key < b.key ? 1 : -1;
}})

Body:
I figured it out myself, according to their API I had to use it as follows:

sortJSON({
  cmp: function (a, b) {
    return a.key < b.key ? 1 : -1;
}})

It'd have been better if the README of the plugin provided an example! :)


问:
Jquery Trigger is firing the wrong table column
I have a dynamically generated table with many checkboxes with same name and click event. I am using an ALL checkbox in every column which will check all the checkbox in that column .
The code is
***dynamically generated checkboxes

```<code>    if (discountProductGroupBuyer != null)
    {
    sb.Append("<td><input name=productGroupWiseCustomer id='" + "GetProduct" + customerGroup + "' type=checkbox checked=true value=mlb onclick=GetProduct('" + customerGroup + "') ></td>");
    }
</code>```

****onclick of generated checkboxes

```<code>   function GetProduct(ids) {
    debugger;
   var str = ids;
   var temp = [];
   temp.length = 0;
   temp = str.toString().split('-');

var addOrDelete = "";
var checkboxid = "#GetProduct" + ids;
if ($(checkboxid).is(":checked")) {
    addOrDelete = true;
    var flag = 0;
    $.grep(ProductGroupID, function (item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}
else {
    addOrDelete = false;
    flag = 0;
    $.grep(ProductGroupID, function(item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}
</code>```

}

*** Check all code

```<code>$(document).on("click", "#chkAll", function () {

    var cbody = $(this),
    theader = cbody.parent(),
    column = theader.index() + 1;
    $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);

});
</code>```

Which seems to work and its checking all the checkbox in that specific column
like below image.

But the problem arise after adding a trigger event. Let me explain

I have also a trigger click event which will be fired by clicking that all checkbox for that specific column only. The problem is when I click the #chkAll checkbox its not triggering that specific column but triggering for the other column checkbox.

```<code>$(document).on("click", "#chkAll", function () {

     var cbody = $(this),
     theader = cbody.parent(),
     column = theader.index() + 1;
     $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);
     $("input:checkbox[name='productGroupWiseCustomer']").trigger('click');

});
</code>```

What I am trying to achieve that by clicking individual column's #chkAll  checkbox it will trigger only the checkboxes under that column only.Help Needed .Thanks for help

I also added a photo.

答:
From what I understand, you not only want to (un)check the whole column of checkboxes, you also want the checkboxes that change because of this action, to have their event handlers executed. That second requirement is not happening when using prop. You could chain a call to trigger, but be aware that this will toggle the check again.

The solution is to select only those checkboxes in the column whose checkbox needs to toggle (which might not be all of them), and then to call .trigger("click") on those. This will both change their checked status and call the corresponding event handlers.

Here is how you could do it:

```<code>$("#tbody td:nth-child(" + column + ") input"
             + (this.checked ? ":not(:checked)" : ":checked").trigger('click');
</code>```

Here is a working fiddle:

$(document).on("click", ".chkAll", function () {
    var cbody = $(this),
        theader = cbody.parent(),
        column = theader.index() + 1;
    $("#tbody td:nth-child(" + column + ") input"
             + (this.checked ? ":not(:checked)" : ":checked")).trigger('click');
});

// Dummy click handler just to give visual clue that it gets called
function GetProduct(input) {
    $(input).fadeOut(100).fadeIn(100);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>th { background-color: silver }
td { text-align: center }</code>```

Noodles
<input class="chkAll" type="checkbox">
Detergent
<input class="chkAll" type="checkbox">
Chocolate
<input class="chkAll" type="checkbox">

<input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)">
<input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)">
<input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)">

<input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)">
<input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)">
<input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)">

<input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)">
<input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)">
<input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)">

The fickering of the checkboxes is intentional: it is evidence of the click handlers being invoked.```
</div>
</div>
</p>

<h3>Calling the event handler for all checkboxes</h3>

<p>Checkboxes that do not change state should not need to get their click event handler caller. Since you insist in comments on this point, and I failed to convince you that this is conceptually wrong, you could use <code>.triggerHandler</code> (instead of <code>.trigger</code>) to call the event handler on all checkboxes of the clicked column -- but without any real click being simulated. </p>

<p>Again, this is not best practice:</p>

```$("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked))
    .each(function() {
        $(this).triggerHandler('click');
    });
```

<p>Here is a working fiddle:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).on("click", ".chkAll", function () {
    var cbody = $(this),
        theader = cbody.parent(),
        column = theader.index() + 1;
    $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked)
        .each(function() {
            $(this).triggerHandler('click');
        });
});

// Dummy click handler just to give visual clue that it gets called
function GetProduct(input) {
    $(input).fadeOut(100).fadeIn(100);
}</code>```

th { background-color: silver }
td { text-align: center }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr>
<th>Noodles<br><input class="chkAll" type="checkbox"></th>
<th>Detergent<br><input class="chkAll" type="checkbox"></th>
<th>Chocolate<br><input class="chkAll" type="checkbox"></th>
</tr>
<tbody id="tbody">
<tr>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
</tr>
<tr>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
</tr>
<tr>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
</tr>
</tbody>
</table>
The fickering of the checkboxes is intentional: it is evidence of the click handlers being invoked.</code>```

Body:
I have a dynamically generated table with many checkboxes with same name and click event. I am using an ALL checkbox in every column which will check all the checkbox in that column .
The code is
***dynamically generated checkboxes

    if (discountProductGroupBuyer != null)
    {
    sb.Append("<input name=productGroupWiseCustomer id='" + "GetProduct" + customerGroup + "' type=checkbox checked=true value=mlb onclick=GetProduct('" + customerGroup + "') >	");
    }

****onclick of generated checkboxes

   function GetProduct(ids) {
    debugger;
   var str = ids;
   var temp = [];
   temp.length = 0;
   temp = str.toString().split('-');

var addOrDelete = "";
var checkboxid = "#GetProduct" + ids;
if ($(checkboxid).is(":checked")) {
    addOrDelete = true;
    var flag = 0;
    $.grep(ProductGroupID, function (item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}
else {
    addOrDelete = false;
    flag = 0;
    $.grep(ProductGroupID, function(item, idx) {
        if (item.DiscountTypeId == temp[0] && item.BuyerId == temp[1] && item.ProductGroupId == temp[2]) {
            //ProductGroupID.splice(idx, 1);
            item.DiscountTypeId = temp[0];
            item.BuyerId = temp[1];
            item.ProductGroupId = temp[2];
            item.AddOrDelete = addOrDelete;
            flag = 1;
        }
    });
    if (flag == 0) {
        ProductGroupID.push({
            DiscountTypeId:temp[0],
            BuyerId:temp[1],
            ProductGroupId:temp[2],
            AddOrDelete:addOrDelete
        });
    }
}

}

*** Check all code

$(document).on("click", "#chkAll", function () {

    var cbody = $(this),
    theader = cbody.parent(),
    column = theader.index() + 1;
    $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);

});

Which seems to work and its checking all the checkbox in that specific column
like below image.

But the problem arise after adding a trigger event. Let me explain

I have also a trigger click event which will be fired by clicking that all checkbox for that specific column only. The problem is when I click the #chkAll checkbox its not triggering that specific column but triggering for the other column checkbox.

$(document).on("click", "#chkAll", function () {

     var cbody = $(this),
     theader = cbody.parent(),
     column = theader.index() + 1;
     $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked);
     $("input:checkbox[name='productGroupWiseCustomer']").trigger('click');

});

What I am trying to achieve that by clicking individual column's #chkAll  checkbox it will trigger only the checkboxes under that column only.Help Needed .Thanks for help

I also added a photo.

Body:
From what I understand, you not only want to (un)check the whole column of checkboxes, you also want the checkboxes that change because of this action, to have their event handlers executed. That second requirement is not happening when using prop. You could chain a call to trigger, but be aware that this will toggle the check again.

The solution is to select only those checkboxes in the column whose checkbox needs to toggle (which might not be all of them), and then to call .trigger("click") on those. This will both change their checked status and call the corresponding event handlers.

Here is how you could do it:

$("#tbody td:nth-child(" + column + ") input"
             + (this.checked ? ":not(:checked)" : ":checked").trigger('click');

Here is a working fiddle:

$(document).on("click", ".chkAll", function () {
    var cbody = $(this),
        theader = cbody.parent(),
        column = theader.index() + 1;
    $("#tbody td:nth-child(" + column + ") input"
             + (this.checked ? ":not(:checked)" : ":checked")).trigger('click');
});

// Dummy click handler just to give visual clue that it gets called
function GetProduct(input) {
    $(input).fadeOut(100).fadeIn(100);
}

th { background-color: silver }
td { text-align: center }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr>
<th>Noodles<br><input class="chkAll" type="checkbox"></th>
<th>Detergent<br><input class="chkAll" type="checkbox"></th>
<th>Chocolate<br><input class="chkAll" type="checkbox"></th>
</tr>
<tbody id="tbody">
<tr>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
</tr>
<tr>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
</tr>
<tr>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
</tr>
</tbody>
</table>
The fickering of the checkboxes is intentional: it is evidence of the click handlers being invoked.

Calling the event handler for all checkboxes

Checkboxes that do not change state should not need to get their click event handler caller. Since you insist in comments on this point, and I failed to convince you that this is conceptually wrong, you could use .triggerHandler (instead of .trigger) to call the event handler on all checkboxes of the clicked column -- but without any real click being simulated.

Again, this is not best practice:

$("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked))
    .each(function() {
        $(this).triggerHandler('click');
    });

Here is a working fiddle:

$(document).on("click", ".chkAll", function () {
    var cbody = $(this),
        theader = cbody.parent(),
        column = theader.index() + 1;
    $("#tbody td:nth-child(" + column + ") input").prop("checked", this.checked)
        .each(function() {
            $(this).triggerHandler('click');
        });
});

// Dummy click handler just to give visual clue that it gets called
function GetProduct(input) {
    $(input).fadeOut(100).fadeIn(100);
}

th { background-color: silver }
td { text-align: center }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr>
<th>Noodles<br><input class="chkAll" type="checkbox"></th>
<th>Detergent<br><input class="chkAll" type="checkbox"></th>
<th>Chocolate<br><input class="chkAll" type="checkbox"></th>
</tr>
<tbody id="tbody">
<tr>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
</tr>
<tr>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
</tr>
<tr>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
<td><input name="productGroupWiseCustomer" type="checkbox" onclick="GetProduct(this)"></td>
</tr>
</tbody>
</table>
The fickering of the checkboxes is intentional: it is evidence of the click handlers being invoked.


问:
Table Naming Dilemma: Singular vs. Plural Names
Academia has it that table names should be the singular of the entity that they store attributes of.

I dislike any T-SQL that requires square brackets around names, but I have renamed a Users table to the singular, forever sentencing those using the table to sometimes have to use brackets.

My gut feel is that it is more correct to stay with the singular, but my gut feel is also that brackets indicate undesirables like column names with spaces in them etc.

Should I stay, or should I go?

答:
Singular. I don't buy any argument involving which is most logical - every person thinks his own preference is most logical. No matter what you do it is a mess, just pick a convention and stick to it. We are trying to map a language with highly irregular grammar and semantics (normal spoken and written language) to a highly regular (SQL) grammar with very specific semantics.

My main argument is that I don't think of the tables as a set but as relations.

So, the AppUser relation tells which entities are AppUsers.

The AppUserGroup relation tells me which entities are AppUserGroups

The AppUser_AppUserGroup relation tells me how the AppUsers and AppUserGroups are related.

The AppUserGroup_AppUserGroup relation tells me how AppUserGroups and AppUserGroups are related (i.e. groups member of groups).

In other words, when I think about entities and how they are related I think of relations in singular, but of course, when I think of the entities in collections or sets, the collections or sets are plural.

In my code, then, and in the database schema, I use singular. In textual descriptions, I end up using plural for increased readability - then use fonts etc. to distinguish the table/relation name from the plural s.

I like to think of it as messy, but systematic - and this way there is always a systematically generated name for the relation I wish to express, which to me is very important.

OwnerDisplayName: ProfK

LastEditorDisplayName: Michael Haren


问:
Create a list of dictionaries from a list of keys and multiple lists of values
My solution

```<code>keys = ['FirstName', 'LastName', 'ID']

name1 = ['Michael', 'Jordan', '224567']
name2 = ['Kyle', 'Hynes', '294007']
name3 = ['Josef', 'Jones', '391107']

dictList = []
dictList.append(dict(zip(keys, name1)))
dictList.append(dict(zip(keys, name2)))
dictList.append(dict(zip(keys, name3)))
</code>```

Works fine, but is there any other solution, because I will have at least 20000 names, so I am looking how to improve this.

答:
You should append your dictionaries to the list inside a loop, like this:

```<code>In [1152]: names = [name1, name2, name3]

In [1153]: d = []

In [1154]: for name in names:
      ...:     d.append(dict(zip(keys, name)))
      ...:

In [1155]: d
Out[1155]:
[{'FirstName': 'Michael', 'ID': '224567', 'LastName': 'Jordan'},
 {'FirstName': 'Kyle', 'ID': '294007', 'LastName': 'Hynes'},
 {'FirstName': 'Josef', 'ID': '391107', 'LastName': 'Jones'}]
</code>```

Or, if you prefer, a list comprehension:

```<code>In [1160]: d = [dict(zip(keys, name)) for name in names]

In [1161]: d
Out[1161]:
[{'FirstName': 'Michael', 'ID': '224567', 'LastName': 'Jordan'},
 {'FirstName': 'Kyle', 'ID': '294007', 'LastName': 'Hynes'},
 {'FirstName': 'Josef', 'ID': '391107', 'LastName': 'Jones'}]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My solution

keys = ['FirstName', 'LastName', 'ID']

name1 = ['Michael', 'Jordan', '224567']
name2 = ['Kyle', 'Hynes', '294007']
name3 = ['Josef', 'Jones', '391107']

dictList = []
dictList.append(dict(zip(keys, name1)))
dictList.append(dict(zip(keys, name2)))
dictList.append(dict(zip(keys, name3)))

Works fine, but is there any other solution, because I will have at least 20000 names, so I am looking how to improve this.

Body:
You should append your dictionaries to the list inside a loop, like this:

In [1152]: names = [name1, name2, name3]

In [1153]: d = []

In [1154]: for name in names:
      ...:     d.append(dict(zip(keys, name)))
      ...:

In [1155]: d
Out[1155]:
[{'FirstName': 'Michael', 'ID': '224567', 'LastName': 'Jordan'},
 {'FirstName': 'Kyle', 'ID': '294007', 'LastName': 'Hynes'},
 {'FirstName': 'Josef', 'ID': '391107', 'LastName': 'Jones'}]

Or, if you prefer, a list comprehension:

In [1160]: d = [dict(zip(keys, name)) for name in names]

In [1161]: d
Out[1161]:
[{'FirstName': 'Michael', 'ID': '224567', 'LastName': 'Jordan'},
 {'FirstName': 'Kyle', 'ID': '294007', 'LastName': 'Hynes'},
 {'FirstName': 'Josef', 'ID': '391107', 'LastName': 'Jones'}]


问:
Pinterest API Rate Limits
We currently use our applications to download some pins information for analytics purposes
Currently we hit the API on hourly basis but we have some problems with rate limiting, so we need the following questions to be addresses:

The documentation states that the rate limit is 1000 calls per hour per user token per endpoint. By looking at the HTTP headers apparently the actual limit is 200. So, which is the correct one?

Are GET /v1/pins/1234 and GET /v1/pins/5678 considered to be a call to the same endpoint?

Are there any application level (so, despite of the used user token) rate-limit in place?

Are there any IP level rate limits?

Since we use concurrent requests, are there any limitation on the number of CONCURRENT request? (which means: make another call from the same IP and using the same token, even if the previous one hasn't ended yet)

Thanks in advance.

PS: I tried to contact them via support form, but it returns a 422. Which is awesome!

答: For apps that is still in development stage the limit is 200. You will get 1000 if your apps passed the review.</p>

Title: Pinterest API Rate Limits


问:
I'm confused, what's the easiest way to install Ruby 1.9.2 on OS X?
My current version is ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-darwin10]</p>

答: You can try rvm to install whatever the version of ruby.</p>

ContentLicense: CC BY-SA 2.5


问:
How To Count Exact Matches on String by Two or More Letters
I have this simple string:

```<code>string code = "HelloWorld";
</code>```

Now I want to count the exact matches of:

```<code>string match = "ll"
</code>```

Which is my expected result is:

```<code>1
</code>```

Since there is only one exact match of double ll in "HelloWorld"

I am trying to do it by split:

```<code>var splitted = code.Split(new string[]{ "l", "l" }, StringSplitOptions.None);
</code>```

But as you would expect, if there was a match of single "l", it will also split it, so I cannot guarantee a good count.

I am trying to do it on a binary number:

```<code>1011010110110
</code>```

Which I want to get how many "10"s it have. Here on my example it has 5 exact 10s.

答:
Please note that you do not need LINQ for this - this can be achieved by using string methods like Split and IndexOf, or by using a regex match.

The following code is the simplest, but suboptimal since it creates an extra array:

```<code>"HelloWorld".Split(new[] { "ll" }, StringSplitOptions.None).Length-1;
</code>```

Also, as @Sweeper pointed out you can use Regex.
If you want to avoid using Regex you can do a small code snippet like this: (Note: skipped args check for brevity, but you should add them)

```<code>public int CountMatches(string searchString, string lookFor)
{
    int count = 0;
    int index = -lookFor.Length;
    do
    {
        index = searchString.IndexOf(lookFor, index + lookFor.Length);
        count++;
    }
    while (index >= 0);

    return count - 1;
}
</code>```

Body:
I have this simple string:

string code = "HelloWorld";

Now I want to count the exact matches of:

string match = "ll"

Which is my expected result is:

1

Since there is only one exact match of double ll in "HelloWorld"

I am trying to do it by split:

var splitted = code.Split(new string[]{ "l", "l" }, StringSplitOptions.None);

But as you would expect, if there was a match of single "l", it will also split it, so I cannot guarantee a good count.

I am trying to do it on a binary number:

1011010110110

Which I want to get how many "10"s it have. Here on my example it has 5 exact 10s.

Body:
Please note that you do not need LINQ for this - this can be achieved by using string methods like Split and IndexOf, or by using a regex match.

The following code is the simplest, but suboptimal since it creates an extra array:

"HelloWorld".Split(new[] { "ll" }, StringSplitOptions.None).Length-1;

Also, as @Sweeper pointed out you can use Regex.
If you want to avoid using Regex you can do a small code snippet like this: (Note: skipped args check for brevity, but you should add them)

public int CountMatches(string searchString, string lookFor)
{
    int count = 0;
    int index = -lookFor.Length;
    do
    {
        index = searchString.IndexOf(lookFor, index + lookFor.Length);
        count++;
    }
    while (index >= 0);

    return count - 1;
}


答:
Do you really need a dictionary? Why not just use a namedtuple:

```<code>>>> from collections import namedtuple
>>> Employee = namedtuple('Employee', 'FirstName, LastName, ID')
>>> names_list = [['Michael', 'Jordan', '224567'], ['Kyle', 'Hynes', '294007'], ['Josef', 'Jones', '391107']]
>>> employee_list = map(Employee._make, names_list)
>>> employee_list[0].FirstName
'Michael'
>>> pprint(employee_list)
[Employee(FirstName='Michael', LastName='Jordan', ID='224567'),
 Employee(FirstName='Kyle', LastName='Hynes', ID='294007'),
 Employee(FirstName='Josef', LastName='Jones', ID='391107')]
</code>```

Title: Create a list of dictionaries from a list of keys and multiple lists of values

Body:
Do you really need a dictionary? Why not just use a namedtuple:

>>> from collections import namedtuple
>>> Employee = namedtuple('Employee', 'FirstName, LastName, ID')
>>> names_list = [['Michael', 'Jordan', '224567'], ['Kyle', 'Hynes', '294007'], ['Josef', 'Jones', '391107']]
>>> employee_list = map(Employee._make, names_list)
>>> employee_list[0].FirstName
'Michael'
>>> pprint(employee_list)
[Employee(FirstName='Michael', LastName='Jordan', ID='224567'),
 Employee(FirstName='Kyle', LastName='Hynes', ID='294007'),
 Employee(FirstName='Josef', LastName='Jones', ID='391107')]


问:
react-router 4.1.1 returning 404's
I've just upgraded to "react-router": "^4.1.1" and now I'm getting 404's from all routes except the default route. Not sure what I'm missing here?

Any assistance is appreciated.

```<code>import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import {  BrowserRouter, Route, Switch } from 'react-router-dom'

import Tee from './components/Tee'
import About from './components/About'
import Home from './components/Home'

class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <div>
                    <Switch>
                        <Route exact path="/" component={Home} />
                        <Route path="/about" component={About} />
                        <Route path="/tee" component={Tee} />
                    </Switch>
                </div>
            </BrowserRouter>
        );
    }
}

export default App;

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

答:
I have tested your code, and duplicated to my own project here:

https://github.com/tzookb/react-router-stackoverflow-q/tree/master

but everything seems to work perfectly, kudos for that! :)

So please can you update your question with relevant errors?
please go through my repo and see that all is good.

Title: react-router 4.1.1 returning 404's

Body:
I've just upgraded to "react-router": "^4.1.1" and now I'm getting 404's from all routes except the default route. Not sure what I'm missing here?

Any assistance is appreciated.

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import {  BrowserRouter, Route, Switch } from 'react-router-dom'

import Tee from './components/Tee'
import About from './components/About'
import Home from './components/Home'

class App extends Component {
    render() {
        return (
            <BrowserRouter>

                    <Switch>
                        <Route exact path="/" component={Home} />
                        <Route path="/about" component={About} />
                        <Route path="/tee" component={Tee} />
                    </Switch>

            </BrowserRouter>
        );
    }
}

export default App;

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


问:
What is the most performant 2D graphics engine for use with Android?
I have managed to make a hello world JBox2D application, and it works (I have some bouncing balls). However, I just read a comment on a forum post, which claims that JBox2D produces a lot of garbage, and so causes animation to be poor. Is this true?

If yes, then what other 2D engines are available to me? I would very much like to use a physics engine for my 2D game, even if it's just a very simple one.

Update:

Just tried running the JBox2D bouncing balls demo on my phone, and the performance was terrible. Looks like libgdx is the way to go for physics, since I think it comes with a  native version of Box2D that works well on Android. As for AndEngine, this is a game engine and not a physics engine, but I may use it in conjunction with libgdx to give myself a head start.

Update 2:

I've had a quick play with libgdx and AndEngine. I've found that they're both Android game engines, but AndEngine has a less steep learing curve at the cost of being more limiting. So if you want to build a serious game, you probably want to use libgdx as it will allow you to do more (but is harder to use).

答:
JBox2D is a port from the native version called Box2D. The native version obviously didn't need to worry about garbage collection as it was written for a language which used manual memory management (C++ I think).

The problem comes as the port for Java JBox2d hasn't been optimised, and as of such, lots of temporary variables are created which triggers garbage collections a lot and consequently really slows the framerate.

As Cristian suggested, you could try AndEngine. I can't remember if this uses JBox2d though or the native Box2D.

I would personally suggest the engine by BadLogicGames called LibGDX here:

http://code.google.com/p/libgdx/

It definitely uses Box2D natively and has the option of developing your whole application on your desktop and only porting to android occasionally for testing. Porting only needs a few lines of code and there are a couple of example apps so its not too tricky! :)

It is also very well maintained, updates are being made to it all the time!

Anyway, Hope this helps!

Andy.


问:
Passport 'logout()' not working as expected
I have a simple authentication system where a user may log in, then log out.

I have many pages and many routes in my app, and every route has this general structure (I'm using my dashboard.hbs route here as an example):

```<code>router.get('/dashboard', ensureAuthenticated, function(req, res, next) {
  User.findOne({ username: req.user.username }, function(err, loggedInUser) {
    if (err) throw err
    else {
      res.render('dashboard', {
        user: loggedInUser
      })
    }
  })
});
</code>```

Specifically, I'm assigning loggedInUser to user to use in my dashboard.hbs partial like so:

```<code><h2 align="center">{{user.first_name}}'s Dashboard</h2>
</code>```

When logging out, I simply use the '/logout route like so:

```<code>router.get('/logout', function(req, res, next) {
    req.logout()
    res.render('logout')
});
</code>```

The problem with this approach is that I'm repeating user: loggedInUser in every route, and I'd like to refactor my code to DRY it up, and define the user that's logged in just once, and use that in every partial.

To help solve this problem, I did the following in my server.js file:

```<code>app.use(function (req, res, next) {
  res.locals.logged_in_user = req.user
  next();
});
</code>```

Now, I'm able to use logged_in_user in any partial without having to assign it in a route.  This works fine everywhere, except when logging out.  When logging out, the req.user property (assigned as logged_in_user) is not immediately removed, and the login session is not immediately cleared.  I'm running the following code:

```<code>router.get('/logout', function(req, res, next) {
    req.logout()
    res.render('logout')
});
</code>```

This is almost identical to the Passport documentation here.

Once I hit the /logout route, I have to refresh the page for the login session to be cleared.  This was not the case when I was using user: loggedInUser in every route.  Now that it's refactored, it no longer works properly.

I should also note that my layout.hbs file includes this code:

```<code><ul class="nav nav-pills pull-right">
  {{#if logged_in_user }}
    <li role="presentation"><a href="/dashboard">Dashboard</a></li>
    <li role="presentation"><a href="/logout">Log Out</a></li>
    <li role="presentation"><a href="/messages">Messages</a></li>
     <li role="presentation"><a href="/users/member">Profile</a></li>
  {{else}}
    <li role="presentation"><a href="/login">Login</a></li>
    <li role="presentation"><a href="/register">Register</a></li>
  {{/if}}
</ul>
</code>```

Using the refactored style, how do I clear a user's login session?

Update

While res.render('logout') does not seem to work, I can just res.redirect the user to the login page, and display a message across the page (using connect-flash) that they have successfully logged out.

答:
Calling req.logout() will clear req.user (it does req.user = null, basically), but your middleware created a reference to the original object, which is what res.locals.logged_in_user is still pointing to.

As for the session (req.session.user): that will be updated at the end of the response, so after res.render('logout') has been called. That's why using res.redirect() is a better way to clear the session after logging out.

Body:
I have a simple authentication system where a user may log in, then log out.

I have many pages and many routes in my app, and every route has this general structure (I'm using my dashboard.hbs route here as an example):

router.get('/dashboard', ensureAuthenticated, function(req, res, next) {
  User.findOne({ username: req.user.username }, function(err, loggedInUser) {
    if (err) throw err
    else {
      res.render('dashboard', {
        user: loggedInUser
      })
    }
  })
});

Specifically, I'm assigning loggedInUser to user to use in my dashboard.hbs partial like so:

{{user.first_name}}'s Dashboard

When logging out, I simply use the '/logout route like so:

router.get('/logout', function(req, res, next) {
    req.logout()
    res.render('logout')
});

The problem with this approach is that I'm repeating user: loggedInUser in every route, and I'd like to refactor my code to DRY it up, and define the user that's logged in just once, and use that in every partial.

To help solve this problem, I did the following in my server.js file:

app.use(function (req, res, next) {
  res.locals.logged_in_user = req.user
  next();
});

Now, I'm able to use logged_in_user in any partial without having to assign it in a route.  This works fine everywhere, except when logging out.  When logging out, the req.user property (assigned as logged_in_user) is not immediately removed, and the login session is not immediately cleared.  I'm running the following code:

router.get('/logout', function(req, res, next) {
    req.logout()
    res.render('logout')
});

This is almost identical to the Passport documentation here.

Once I hit the /logout route, I have to refresh the page for the login session to be cleared.  This was not the case when I was using user: loggedInUser in every route.  Now that it's refactored, it no longer works properly.

I should also note that my layout.hbs file includes this code:

  {{#if logged_in_user }}

Dashboard

Log Out

Messages

Profile

  {{else}}

Login

Register

  {{/if}}

Using the refactored style, how do I clear a user's login session?

Update

While res.render('logout') does not seem to work, I can just res.redirect the user to the login page, and display a message across the page (using connect-flash) that they have successfully logged out.


问:
terminate called after throwing an instance of 'std::logic_error' basic_string::_S_construct null not valid
```<code>string Solution::findDigitsInBinary(int A) {
    int i, j, rem;

    if(A == 0) {
        return 0;
    }
    else {
        string res="";

        while(A > 0) {
            rem = A % 2;
            res = res + to_string(rem);
            A = A / 2;
        }

        return std::string(res.rbegin(), res.rend());
    }
}
</code>```

how to resolve this

答:
The problem caused by:

```<code>if(A == 0) {
    return 0;
}
</code>```

When A == 0 it tries to construct an std::string from 0. This is equal – because the implicit constructor call – to:

```<code>return std::string(0);
</code>```

In this case the 0 means a null pointer which is illegal. The error message

basic_string::_M_construct null not valid

means exactly the same.

If you wish to return zero when A == 0, you can solve it by changing the return 0 to:

```<code>return "0";
</code>```

Body:
string Solution::findDigitsInBinary(int A) {
    int i, j, rem;

    if(A == 0) {
        return 0;
    }
    else {
        string res="";

        while(A > 0) {
            rem = A % 2;
            res = res + to_string(rem);
            A = A / 2;
        }

        return std::string(res.rbegin(), res.rend());
    }
}

how to resolve this

Body:
The problem caused by:

if(A == 0) {
    return 0;
}

When A == 0 it tries to construct an std::string from 0. This is equal – because the implicit constructor call – to:

return std::string(0);

In this case the 0 means a null pointer which is illegal. The error message

basic_string::_M_construct null not valid

means exactly the same.

If you wish to return zero when A == 0, you can solve it by changing the return 0 to:

return "0";


答:
Place all your "name" sublists into the parent list names. Then you can easily use list comprehension:

```<code>keys = ['FirstName', 'LastName', 'ID']
names = [
    ['Michael', 'Jordan', '224567'],
    ['Kyle', 'Hynes', '294007'],
    ['Josef', 'Jones', '391107']
]

dictList = [{k:v for k,v in zip(keys, n)} for n in names]
print(dictList)
</code>```

The output:

```<code>[{'FirstName': 'Michael', 'LastName': 'Jordan', 'ID': '224567'}, {'FirstName': 'Kyle', 'LastName': 'Hynes', 'ID': '294007'}, {'FirstName': 'Josef', 'LastName': 'Jones', 'ID': '391107'}]
</code>```

Body:
Place all your "name" sublists into the parent list names. Then you can easily use list comprehension:

keys = ['FirstName', 'LastName', 'ID']
names = [
    ['Michael', 'Jordan', '224567'],
    ['Kyle', 'Hynes', '294007'],
    ['Josef', 'Jones', '391107']
]

dictList = [{k:v for k,v in zip(keys, n)} for n in names]
print(dictList)

The output:

[{'FirstName': 'Michael', 'LastName': 'Jordan', 'ID': '224567'}, {'FirstName': 'Kyle', 'LastName': 'Hynes', 'ID': '294007'}, {'FirstName': 'Josef', 'LastName': 'Jones', 'ID': '391107'}]


答: return 0; calls implicit string constructor accepting a pointer to char return std::string(const char *(0)). This pointer is not allowed to be null. To return an empty string write return std::string();

Title: terminate called after throwing an instance of 'std::logic_error' basic_string::_S_construct null not valid


问:
Convert php to java/android arrays
```<code>$tagArray = array(
    "apples" => 12,
    "oranges" => 38,
    "pears" => 10,
    "mangos" => 24,
    "grapes" => 18,
    "bananas" => 56,
    "watermelons" => 80,
    "lemons" => 12,
    "limes" => 12,
    "pineapples" => 15,
    "strawberries" => 20,
    "coconuts" => 43,
    "cherries" => 20,
    "raspberries" => 8,
    "peaches" => 25
    );
</code>```

How I can do this in Java, and how to calling for the first and second params?

答:
Java has no built in support for associative arrays. The corresponding datastructure in java is a Map. In this case you could for instance make use of a HashMap.

Here's one way.

```<code>Map<String, Integer> tagArray = new HashMap<String, Integer>() {{
    put("apples", 12);
    put("oranges", 38);
    put("pears", 10);
    put("mangos", 24);
    put("grapes", 18);
    put("bananas", 56);
    put("watermelons", 80);
    put("lemons", 12);
    put("limes", 12);
    put("pineapples", 15);
    put("strawberries", 20);
    put("coconuts", 43);
    put("cherries", 20);
    put("raspberries", 8);
    put("peaches", 25);
}};
</code>```

To get the value for, say, "lemons" you do

```<code>int value = tagArray.get("lemons");
</code>```

As @Peter Lawrey points out in the comments: If the order in the array is important to you, you could use a LinkedHashMap instead of a HashMap.

Title: Convert php to java/android arrays

Body:
$tagArray = array(
    "apples" => 12,
    "oranges" => 38,
    "pears" => 10,
    "mangos" => 24,
    "grapes" => 18,
    "bananas" => 56,
    "watermelons" => 80,
    "lemons" => 12,
    "limes" => 12,
    "pineapples" => 15,
    "strawberries" => 20,
    "coconuts" => 43,
    "cherries" => 20,
    "raspberries" => 8,
    "peaches" => 25
    );

How I can do this in Java, and how to calling for the first and second params?

Body:
Java has no built in support for associative arrays. The corresponding datastructure in java is a Map. In this case you could for instance make use of a HashMap.

Here's one way.

Map<String, Integer> tagArray = new HashMap<String, Integer>() {{
    put("apples", 12);
    put("oranges", 38);
    put("pears", 10);
    put("mangos", 24);
    put("grapes", 18);
    put("bananas", 56);
    put("watermelons", 80);
    put("lemons", 12);
    put("limes", 12);
    put("pineapples", 15);
    put("strawberries", 20);
    put("coconuts", 43);
    put("cherries", 20);
    put("raspberries", 8);
    put("peaches", 25);
}};

To get the value for, say, "lemons" you do

int value = tagArray.get("lemons");

As @Peter Lawrey points out in the comments: If the order in the array is important to you, you could use a LinkedHashMap instead of a HashMap.


问:
Why isn't FromQuery working in my ASP.Net Core 1.1 controller action
I am working on an ASP.Net Core 1.1 web API. I have a ServiceTypeCode controller as shown below;

```<code>[Produces("application/json")]
[Route("api/[controller]")]
public class ServiceTypeCodeController : Controller
{
    ...
    ...
    ...

    [HttpGet]
    public IActionResult Get([FromQuery] string a_query)
    {
        try
        {
            if (string.IsNullOrEmpty(a_query))
            {
                OperationResult<List<ServiceTypeCode>, string> result = m_bl.GetAllServiceTypeCodes();
                if (result.Success && result.Result.Count > 0)
                {
                    return Ok(JsonConvert.SerializeObject(result.Result));
                }
            } else
            {
                // Deserialize query into dictionary of strings and StringValues
                var query = QueryHelpers.ParseQuery(a_query.ToLower());

                if (query.TryGetValue("mailclasscode", out var mailClassCode))
                {
                    if (!string.IsNullOrEmpty(mailClassCode))
                    {
                        OperationResult<List<ServiceTypeCode>, string> result = m_bl.GetAllServiceTypeCodes(mailClassCode);
                        if (result.Success && result.Result.Count > 0)
                        {
                            return Ok(JsonConvert.SerializeObject(result.Result));
                        }
                    }
                }
                if (query.TryGetValue("stc", out var stc))
                {
                    if (!string.IsNullOrEmpty(stc))
                    {
                        OperationResult<ServiceTypeCode, string> result = m_bl.GetServiceTypeCode(stc);
                        if (result.Success)
                        {
                            return Ok(JsonConvert.SerializeObject(result.Result));
                        }
                    }
                }
            }
            return NotFound();
        }
        catch (Exception ex)
        {
            string msg = "An exception occurred while trying to get a list of ServiceTypeCodes from the database.";
            m_logger.LogError(1, ex, msg);
            ApiError error = BuildError("Server Error - Exception", "500", "Get", ex, msg);
            return Ok(JsonConvert.SerializeObject(error));
        }

    }
</code>```

If I use the url ...

```<code>http://localhost:5000/api/servicetypecodes
</code>```

in PostMan with the GET verb, I get the list of service type codes, as expected. However, If I try to add anything as a query string, such as ...

```<code>http://localhost:5000/api/servicetypecodes?mailclasscode=fc
</code>```

and set a breakpoint in my code at the

```<code>if (string.IsNullOrEmpty(a_query))
</code>```

location, the value of a_query is null instead of the expected "mailclasscode=fc"

What am I missing here?

Thanks in advance for any help.

答:
The .Net Core Controller Method's variable names must be the same as what you are sending.

```<code>http://localhost:5000/api/servicetypecodes?mailclasscode=fc
</code>```

If using that url to pass data the controller method will have to look like this:

```<code>[HttpGet]
public IActionResult Get([FromQuery] string mailclasscode)
{...}
</code>```

Or vice versa.

Good luck - happy coding.

Body:
I am working on an ASP.Net Core 1.1 web API. I have a ServiceTypeCode controller as shown below;

[Produces("application/json")]
[Route("api/[controller]")]
public class ServiceTypeCodeController : Controller
{
    ...
    ...
    ...

    [HttpGet]
    public IActionResult Get([FromQuery] string a_query)
    {
        try
        {
            if (string.IsNullOrEmpty(a_query))
            {
                OperationResult<List<ServiceTypeCode>, string> result = m_bl.GetAllServiceTypeCodes();
                if (result.Success && result.Result.Count > 0)
                {
                    return Ok(JsonConvert.SerializeObject(result.Result));
                }
            } else
            {
                // Deserialize query into dictionary of strings and StringValues
                var query = QueryHelpers.ParseQuery(a_query.ToLower());

                if (query.TryGetValue("mailclasscode", out var mailClassCode))
                {
                    if (!string.IsNullOrEmpty(mailClassCode))
                    {
                        OperationResult<List<ServiceTypeCode>, string> result = m_bl.GetAllServiceTypeCodes(mailClassCode);
                        if (result.Success && result.Result.Count > 0)
                        {
                            return Ok(JsonConvert.SerializeObject(result.Result));
                        }
                    }
                }
                if (query.TryGetValue("stc", out var stc))
                {
                    if (!string.IsNullOrEmpty(stc))
                    {
                        OperationResult<ServiceTypeCode, string> result = m_bl.GetServiceTypeCode(stc);
                        if (result.Success)
                        {
                            return Ok(JsonConvert.SerializeObject(result.Result));
                        }
                    }
                }
            }
            return NotFound();
        }
        catch (Exception ex)
        {
            string msg = "An exception occurred while trying to get a list of ServiceTypeCodes from the database.";
            m_logger.LogError(1, ex, msg);
            ApiError error = BuildError("Server Error - Exception", "500", "Get", ex, msg);
            return Ok(JsonConvert.SerializeObject(error));
        }

    }

If I use the url ...

http://localhost:5000/api/servicetypecodes

in PostMan with the GET verb, I get the list of service type codes, as expected. However, If I try to add anything as a query string, such as ...

http://localhost:5000/api/servicetypecodes?mailclasscode=fc

and set a breakpoint in my code at the

if (string.IsNullOrEmpty(a_query))

location, the value of a_query is null instead of the expected "mailclasscode=fc"

What am I missing here?

Thanks in advance for any help.

Body:
The .Net Core Controller Method's variable names must be the same as what you are sending.

http://localhost:5000/api/servicetypecodes?mailclasscode=fc

If using that url to pass data the controller method will have to look like this:

[HttpGet]
public IActionResult Get([FromQuery] string mailclasscode)
{...}

Or vice versa.

Good luck - happy coding.


问:
How to load a value from a div in a React component?
I want to dynamically set a value within my cart constructor. My cart variable has price, item. and size values. I want to assign a value to item dynamically on what item has been clicked. This is my code:

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addCart } from '../../actions';
import { withRouter } from 'react-router';
//import { Cart } from './webcart';

import CamoHat from './camodye.jpeg';
import TonyTape from './TonyTape.png';
import RegularHat from './regularhat.jpg';
import JaguarShirt from './JAGUARLOGO.png';
import SeltzShirt from './seltzshirt.jpg';
import NocHoodie from './NOCNOCHOODIE.png';

export class WebShop extends Component {
    constructor(props){
        super(props);
        this.state = {value: 'medium', cartData: {} };
        this.handleClick = this.handleClick.bind(this);
        this.change = this.change.bind(this);
        this.goProductPage = this.goProductPage.bind(this);
        this.goProductPage2 = this.goProductPage2.bind(this);
        this.goProductPage3 = this.goProductPage3.bind(this);
    }

    handleClick() {
        let cart = {price:0,item:"userselection",size:this.state.value};
        this.props.onCartAdd(cart);
        this.itemSelection(cart);
    }

    change(e){
        this.setState({value: e.target.value})
    }

    itemSelection(cart){
        let userItem = cart;
        let userSelection = cart
        if (userItem == "shirt1") {
           let itemPrice = 20.00;
        }
    }
    ...

    render() {
        return (
            <div className='Webshop' id='Webshop'>
                <ul id="Productlist">
                    <div className='Product'>
                      <img src={CamoHat} onClick={this.goProductPage}></img>
                      <div id='infoname'>NOC NOC HAT (CAMO)</div>
                      <div id='infoprice'>40.00</div>
                    </div>
                    <div className='Product'>
                      <img src={JaguarShirt} onClick={this.goProductPage2}></img>
                      <div id='infoname'>JAGUAR PYRAMIDS T-SHIRT</div>
                      <div id='infoprice'>25.00</div>
                    </div>
                    <div className='Product'>
                      <img src={SeltzShirt} onClick={this.goProductPage3}></img>
                      <div id='infoname'>JAGUAR PYRAMIDS T-SHIRT</div>
                      <div id='infoprice'>25.00</div>
                    </div>
                    <div className='Product'>
                      <img src={NocHoodie} onClick={this.goProductPage}></img>
                      <div id='infoname'>JAGUAR PYRAMIDS T-SHIRT</div>
                      <div id='infoprice'>25.00</div>
                    </div>
                    <div className='Product'>
                      <img src={RegularHat}></img>
                      <button onClick={this.handleClick} className="addit">Add to cart</button>
                      <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                      </select>
                    </div>
                    <div className='Product'>
                      <img src={TonyTape}></img>
                      <button onClick={this.handleClick} className="addit">Add to cart</button>
                      <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                      </select>
                    </div>
                </ul>
            </div>
        );
    }
}

...

export default connect(mapStateToProps,mapDispatchToProps)(WebShop);
</code>```

I want to assign the item value in cart using the description of the item within the item div id=infoname (the text itself) for ex: NOC NOC Hat. How can I do this within my function? Is there a better way to do it?

答:
The quickest way to do what you want to do is to use refs :
https://facebook.github.io/react/docs/refs-and-the-dom.html

Quote from the official doc :

The ref attribute takes a callback function, and the callback will be
  executed immediately after the component is mounted or unmounted.

When the ref attribute is used on an HTML element, the ref callback
  receives the underlying DOM element as its argument

I have removed some lines from your code so that it compiles for me.
Here it is :
https://codesandbox.io/s/314N8jxG9

Look at line 22 and 46. (check the console.log output)

The ref attributes receives a callback that can access the div element, thus it innerHTML value.

This is not the best way to do it but this will fix your issue.

Now the best is to use props.

Please, refactor your code by first extracting your products items into ProductIem this way :

```<code>  const ProductItdem = ({description, price})=>{
        return (
              <div className='Product'>
                          <div id='infoname'   >{description}</div>
                          <div id='infoprice'>{price}</div>
                        </div>
        );
    }
</code>```

You can even compose them in a ProductList Component.
Then you will pass props from you WebShop container component to the dumm components.

Try it and let us know your questions.

Body:
I want to dynamically set a value within my cart constructor. My cart variable has price, item. and size values. I want to assign a value to item dynamically on what item has been clicked. This is my code:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addCart } from '../../actions';
import { withRouter } from 'react-router';
//import { Cart } from './webcart';

import CamoHat from './camodye.jpeg';
import TonyTape from './TonyTape.png';
import RegularHat from './regularhat.jpg';
import JaguarShirt from './JAGUARLOGO.png';
import SeltzShirt from './seltzshirt.jpg';
import NocHoodie from './NOCNOCHOODIE.png';

export class WebShop extends Component {
    constructor(props){
        super(props);
        this.state = {value: 'medium', cartData: {} };
        this.handleClick = this.handleClick.bind(this);
        this.change = this.change.bind(this);
        this.goProductPage = this.goProductPage.bind(this);
        this.goProductPage2 = this.goProductPage2.bind(this);
        this.goProductPage3 = this.goProductPage3.bind(this);
    }

    handleClick() {
        let cart = {price:0,item:"userselection",size:this.state.value};
        this.props.onCartAdd(cart);
        this.itemSelection(cart);
    }

    change(e){
        this.setState({value: e.target.value})
    }

    itemSelection(cart){
        let userItem = cart;
        let userSelection = cart
        if (userItem == "shirt1") {
           let itemPrice = 20.00;
        }
    }
    ...

    render() {
        return (

NOC NOC HAT (CAMO)

40.00

JAGUAR PYRAMIDS T-SHIRT

25.00

JAGUAR PYRAMIDS T-SHIRT

25.00

JAGUAR PYRAMIDS T-SHIRT

25.00

                      <button onClick={this.handleClick} className="addit">Add to cart</button>
                      <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                      </select>

                      <button onClick={this.handleClick} className="addit">Add to cart</button>
                      <select id="size" onChange={this.change} value={this.state.value}>
                        <option value="medium">Medium</option>
                        <option value="large">Large</option>
                        <option value="x-large">X-large</option>
                      </select>

        );
    }
}

...

export default connect(mapStateToProps,mapDispatchToProps)(WebShop);

I want to assign the item value in cart using the description of the item within the item div id=infoname (the text itself) for ex: NOC NOC Hat. How can I do this within my function? Is there a better way to do it?

Body:
The quickest way to do what you want to do is to use refs :
https://facebook.github.io/react/docs/refs-and-the-dom.html

Quote from the official doc :

The ref attribute takes a callback function, and the callback will be
  executed immediately after the component is mounted or unmounted.

When the ref attribute is used on an HTML element, the ref callback
  receives the underlying DOM element as its argument

I have removed some lines from your code so that it compiles for me.
Here it is :
https://codesandbox.io/s/314N8jxG9

Look at line 22 and 46. (check the console.log output)

The ref attributes receives a callback that can access the div element, thus it innerHTML value.

This is not the best way to do it but this will fix your issue.

Now the best is to use props.

Please, refactor your code by first extracting your products items into ProductIem this way :

  const ProductItdem = ({description, price})=>{
        return (
              <div className='Product'>
                          <div id='infoname'   >{description}</div>
                          <div id='infoprice'>{price}</div>
                        </div>
        );
    }

You can even compose them in a ProductList Component.
Then you will pass props from you WebShop container component to the dumm components.

Try it and let us know your questions.


问:
Reference to a field of a row object
I'm having trouble accessing the fields of row objects which I have created in Presto. The Presto documentation claims "fields... are accessed with field reference operator." However that doesn't seem to work. This code reproduces the problem:

```<code>CREATE TABLE IF NOT EXISTS data AS
SELECT * FROM (VALUES
    (1, 'Adam', 17),
    (2, 'Bill', 42)
) AS x (id, name, age);

CREATE TABLE IF NOT EXISTS ungrouped_data AS
 WITH grouped_data AS (
  SELECT
    id,
    ROW(name, age) AS name_age
  FROM data
 )
SELECT
  id,
  name_age.1 AS name,
  name_age.2 AS age
FROM grouped_data;
</code>```

Which returns an "extraneous input '.1'" error.

答:
ROW(name, age) will create an row without field names. Today to access the fields in such row, you need to cast it into a row with field names. Try this:

```<code>WITH grouped_data AS (
    SELECT
      id,
      CAST(ROW(name, age) AS ROW(col1 VARCHAR, col2 INTEGER)) AS name_age
    FROM data
)
SELECT
  id,
  name_age.col1 AS name,
  name_age.col2 AS age
FROM grouped_data;
</code>```

Result:

```<code> id | name | age
----+------+-----
  1 | Adam |  17
  2 | Bill |  42
</code>```

See https://github.com/prestodb/presto/issues/7640 for discussions on this.

Title: Reference to a field of a row object

Body:
I'm having trouble accessing the fields of row objects which I have created in Presto. The Presto documentation claims "fields... are accessed with field reference operator." However that doesn't seem to work. This code reproduces the problem:

CREATE TABLE IF NOT EXISTS data AS
SELECT * FROM (VALUES
    (1, 'Adam', 17),
    (2, 'Bill', 42)
) AS x (id, name, age);

CREATE TABLE IF NOT EXISTS ungrouped_data AS
 WITH grouped_data AS (
  SELECT
    id,
    ROW(name, age) AS name_age
  FROM data
 )
SELECT
  id,
  name_age.1 AS name,
  name_age.2 AS age
FROM grouped_data;

Which returns an "extraneous input '.1'" error.

Body:
ROW(name, age) will create an row without field names. Today to access the fields in such row, you need to cast it into a row with field names. Try this:

WITH grouped_data AS (
    SELECT
      id,
      CAST(ROW(name, age) AS ROW(col1 VARCHAR, col2 INTEGER)) AS name_age
    FROM data
)
SELECT
  id,
  name_age.col1 AS name,
  name_age.col2 AS age
FROM grouped_data;

Result:

 id | name | age
----+------+-----
  1 | Adam |  17
  2 | Bill |  42

See https://github.com/prestodb/presto/issues/7640 for discussions on this.


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

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

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

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

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

And this is the output:

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

I want to print it like that:

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

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

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

It'll skip the last character in the string.

How can I achieve this?

答:
Since you do not want to use a HashMap or set, sorting the string before counting is a good option. Also, you are using a nested loop traversing the string twice, hence your time complexity is O(N^2) where N is the length of your string. While sorting the string first and then traversing it once reduces your time complexity to O(NlogN).

Note that using a HashMap would have made the time complexity O(N).

```<code>import java.util.Arrays;

public class PrintDuplicates
{
  public static void printDups(String str){

    char[] chars = str.toCharArray();
    Arrays.sort(chars);
    String sorted = new String(chars);

    //to handle the edge case that the String is of 0 length
    if(sorted.length() == 0){
     return;
    }

    int count=1;
    int i;
    for(i=0; i< sorted.length()-1; i++){

      if(sorted.charAt(i) != sorted.charAt(i+1)){
      System.out.println(sorted.charAt(i)+"-->"+count);
      count = 1;
    }
    else{
      count++;
    }
  }

  System.out.println(sorted.charAt(i)+"-->"+count); //to print the last character and it's count last seen

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

    // printDups("");
    // printDups("A");
    //printDups("ABA");
    printDups("ABCCAAADAA");
   }
}
</code>```

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

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

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

        count = 0;
    }
}

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

And this is the output:

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

I want to print it like that:

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

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

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

It'll skip the last character in the string.

How can I achieve this?

Body:
Since you do not want to use a HashMap or set, sorting the string before counting is a good option. Also, you are using a nested loop traversing the string twice, hence your time complexity is O(N^2) where N is the length of your string. While sorting the string first and then traversing it once reduces your time complexity to O(NlogN).

Note that using a HashMap would have made the time complexity O(N).

import java.util.Arrays;

public class PrintDuplicates
{
  public static void printDups(String str){

    char[] chars = str.toCharArray();
    Arrays.sort(chars);
    String sorted = new String(chars);

    //to handle the edge case that the String is of 0 length
    if(sorted.length() == 0){
     return;
    }

    int count=1;
    int i;
    for(i=0; i< sorted.length()-1; i++){

      if(sorted.charAt(i) != sorted.charAt(i+1)){
      System.out.println(sorted.charAt(i)+"-->"+count);
      count = 1;
    }
    else{
      count++;
    }
  }

  System.out.println(sorted.charAt(i)+"-->"+count); //to print the last character and it's count last seen

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

    // printDups("");
    // printDups("A");
    //printDups("ABA");
    printDups("ABCCAAADAA");
   }
}


问:
User defined command
I am having a situation for which I am looking for some suggestion.

Suppose I write a program which prints the directory names of the directories.
Is it possible to convert this program into a command (just on my system).
Not be alias but via C only.

答: Put it in the path. On Linux, for example, you should put it in /usr/local/bin.

Title: User defined command


问:
Running single Python Selenium test on Bamboo CI
I have a dedicated server which we are using for Selenium (Python) testing only.

So I want to SSH in that server and run a single Python Selenium test. I have Bamboo running on the other server. Is it possible through Bamboo SSH job?

This is my script for my Bamboo SSH task:

```<code>cd ~
cd tms2_selenium
source venv/bin/activate
behave features/login.feature
</code>```

and I get this error:

```<code>Exception WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
build   07-Jul-2017 17:17:41      (Driver info: chromedriver=2.26.436382 (70eb799287ce4c2208441fc057053a5b07ceabac),platform=Linux 3.16.0-4-amd64 x86_64)

Chrome failed to start: exited abnormally
</code>```

答:
Open display before opening chromedriver:</p>

```<code>  context.display = Display(visible=0, size=(800, 600))
  context.display.start()
  options.add_argument('--no-sandbox')
  context.browser = webdriver.Chrome('/usr/local/bin/chromedriver',chrome_options=options)
</code>```

Body:
I have a dedicated server which we are using for Selenium (Python) testing only.

So I want to SSH in that server and run a single Python Selenium test. I have Bamboo running on the other server. Is it possible through Bamboo SSH job?

This is my script for my Bamboo SSH task:

cd ~
cd tms2_selenium
source venv/bin/activate
behave features/login.feature

and I get this error:

Exception WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
build   07-Jul-2017 17:17:41      (Driver info: chromedriver=2.26.436382 (70eb799287ce4c2208441fc057053a5b07ceabac),platform=Linux 3.16.0-4-amd64 x86_64)

Chrome failed to start: exited abnormally

Body:
Open display before opening chromedriver:

  context.display = Display(visible=0, size=(800, 600))
  context.display.start()
  options.add_argument('--no-sandbox')
  context.browser = webdriver.Chrome('/usr/local/bin/chromedriver',chrome_options=options)


问:
SQL Grouping and dense rank concept
I have a data set that looks like:

```<code> cust   city    hotel_id amount
 -------------------------------
   A    1        252    3160
   B    1        256    1893
   C    2        105    2188
   D    2        105    3054
   E    3        370    6107
   F    2        110    3160
   G    2        150    1893
   H    3        310    2188
   I    1        252    3160
   J    1        250    4000
   K    3        370    5000
   L    3        311    1095
</code>```

Query to display the top 3 hotels by revenue (Sum of amount) for each city?
Since same hotel can be booked by other customer in same city so we need to sum the amount to find total amount.

Expected output:

```<code>city    hotel_id    amount
---------------------------
  1       252        6320
  1       250        4000
  1       256        1893

  2       105        5242
  2       110        3160
  2       150        1893

  3       370       11107
  3       310        2188
  3       311        1095
</code>```

答:
```<code>SELECT
    t.city, t.hotel_id, t.amount
FROM
(
    SELECT city, hotel_id, SUM(amount) AS amount,
        ROW_NUMBER() OVER (PARTITION BY city ORDER BY SUM(amount) DESC) AS rn
    FROM yourTable
    GROUP BY city, hotel_id
) t
WHERE t.rn <= 3
ORDER BY t.city, t.amount DESC;
</code>```

Demo here:

Rextester

Title: SQL Grouping and dense rank concept

Body:
I have a data set that looks like:

 cust   city    hotel_id amount
 -------------------------------
   A    1        252    3160
   B    1        256    1893
   C    2        105    2188
   D    2        105    3054
   E    3        370    6107
   F    2        110    3160
   G    2        150    1893
   H    3        310    2188
   I    1        252    3160
   J    1        250    4000
   K    3        370    5000
   L    3        311    1095

Query to display the top 3 hotels by revenue (Sum of amount) for each city?
Since same hotel can be booked by other customer in same city so we need to sum the amount to find total amount.

Expected output:

city    hotel_id    amount
---------------------------
  1       252        6320
  1       250        4000
  1       256        1893

  2       105        5242
  2       110        3160
  2       150        1893

  3       370       11107
  3       310        2188
  3       311        1095

Body:
SELECT
    t.city, t.hotel_id, t.amount
FROM
(
    SELECT city, hotel_id, SUM(amount) AS amount,
        ROW_NUMBER() OVER (PARTITION BY city ORDER BY SUM(amount) DESC) AS rn
    FROM yourTable
    GROUP BY city, hotel_id
) t
WHERE t.rn <= 3
ORDER BY t.city, t.amount DESC;

Demo here:

Rextester


答:
Since the method is expected to return a std::string so you are returning a std::string(0) ~ std::string(NULL) if A == 0 is true.

To return a default value for std::string - I guess - simply return std::string(); instead of return 0;.

Body:
string Solution::findDigitsInBinary(int A) {
    int i, j, rem;

    if(A == 0) {
        return 0;
    }
    else {
        string res="";

        while(A > 0) {
            rem = A % 2;
            res = res + to_string(rem);
            A = A / 2;
        }

        return std::string(res.rbegin(), res.rend());
    }
}

how to resolve this


问:
How do I disable log messages from the Requests library?
By default, the Requests python library writes log messages to the console, along the lines of:

```<code>Starting new HTTP connection (1): example.com
http://example.com:80 "GET / HTTP/1.1" 200 606
</code>```

I'm usually not interested in these messages, and would like to disable them. What would be the best way to silence those messages or decrease Requests' verbosity?

答:
If You have configuration file, You can configure it.

Add urllib3 in loggers section:

```<code>[loggers]
keys = root, urllib3
</code>```

Add logger_urllib3 section:

```<code>[logger_urllib3]
level = WARNING
handlers =
qualname = requests.packages.urllib3.connectionpool
</code>```

Body:
By default, the Requests python library writes log messages to the console, along the lines of:

Starting new HTTP connection (1): example.com
http://example.com:80 "GET / HTTP/1.1" 200 606

I'm usually not interested in these messages, and would like to disable them. What would be the best way to silence those messages or decrease Requests' verbosity?

Body:
If You have configuration file, You can configure it.

Add urllib3 in loggers section:

[loggers]
keys = root, urllib3

Add logger_urllib3 section:

[logger_urllib3]
level = WARNING
handlers =
qualname = requests.packages.urllib3.connectionpool


问:
Tensorflow tries to use more memory than the profiler indicates it should
I have implemented SSD (Single Shot Detector) in Tensorflow.

During inference, I'm loading the frozen graph as follows:

```<code>    def load_graph(filename):
        with tf.gfile.FastGFile(filename, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        img, box, cls, val = tf.import_graph_def(graph_def, name='',
            return_elements=['input:0', 'pred/box:0', 'pred/cls:0', 'pred/val:0']
        )
        return img, box, cls, val
</code>```

So that no unnecessary operations will tag along.

However, when I was running the usage script, like so:

```<code>    _box, _cls, _val = sess.run([box, cls, val],{img: np.expand_dims(image_data,0)},
</code>```

(i.e. I'm only using a batch size of one)

I noticed that tensorflow complained about memory allocation:

```<code>2017-07-08 20:38:46.389877: W
tensorflow/core/common_runtime/bfc_allocator.cc:217] Allocator
(GPU_0_bfc) ran out of memory trying to allocate 2.05GiB. The caller
indicates that this is not a failure, but may mean that there could be
performance gains if more memory is available.
</code>```

So I decided to profile the operations, and got the following result:

As you can see, none of the operations are claiming more than 75MB.

Where is this discrepancy coming from?

When I control the amount of memory allocation, like this:

```<code>    gpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.1)
    config = tf.ConfigProto(log_device_placement=True, gpu_options=gpu_options)
</code>```

Tensorflow still complains about the amount of memory available, but I don't see any critical hits in the performance (i.e. it always runs in about 8 ms, regardless of allowed memory allocated)

When I allow it to grow until Tensorflow seems satisfied, it grows to about 6.7GB.

I don't understand what is causing this behavior to occur. Where is this discrepancy coming from?

答:
The warning you report says that allocation on device memory failed and happened on host memory instead;

However, in your tensorboard screenshot, you only show device memory (the gpu:0 check box). You need to check the cpu:0 checkbox to also debug CPU operations.

Now, given that you get fast computations in that situation comparable to when it is allocated on the device, and given the size of the allocation (2GB), and given the position of the greyed-out boxes in your tensorboard snapshot, I suspect this tensor holds input data, and that only slices are sent to the GPU as batches. I would say this is fine.

Body:
I have implemented SSD (Single Shot Detector) in Tensorflow.

During inference, I'm loading the frozen graph as follows:

    def load_graph(filename):
        with tf.gfile.FastGFile(filename, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        img, box, cls, val = tf.import_graph_def(graph_def, name='',
            return_elements=['input:0', 'pred/box:0', 'pred/cls:0', 'pred/val:0']
        )
        return img, box, cls, val

So that no unnecessary operations will tag along.

However, when I was running the usage script, like so:

    _box, _cls, _val = sess.run([box, cls, val],{img: np.expand_dims(image_data,0)},

(i.e. I'm only using a batch size of one)

I noticed that tensorflow complained about memory allocation:

2017-07-08 20:38:46.389877: W
tensorflow/core/common_runtime/bfc_allocator.cc:217] Allocator
(GPU_0_bfc) ran out of memory trying to allocate 2.05GiB. The caller
indicates that this is not a failure, but may mean that there could be
performance gains if more memory is available.

So I decided to profile the operations, and got the following result:

As you can see, none of the operations are claiming more than 75MB.

Where is this discrepancy coming from?

When I control the amount of memory allocation, like this:

    gpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.1)
    config = tf.ConfigProto(log_device_placement=True, gpu_options=gpu_options)

Tensorflow still complains about the amount of memory available, but I don't see any critical hits in the performance (i.e. it always runs in about 8 ms, regardless of allowed memory allocated)

When I allow it to grow until Tensorflow seems satisfied, it grows to about 6.7GB.

I don't understand what is causing this behavior to occur. Where is this discrepancy coming from?


问:
How to cut box corner Using CSS with transparent background?
I want to cut left top corner of a box using CSS like this.

keep in mind that background is transparent.

答:
You can use a simple linear gradient for that:

body {
  background: purple;
}

.card {
  width: 200px;
  height: 200px;
  background: linear-gradient(to bottom right, transparent 5%, white 5%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card"></div></code>```

Body:
You can use a simple linear gradient for that:

body {
  background: purple;
}

.card {
  width: 200px;
  height: 200px;
  background: linear-gradient(to bottom right, transparent 5%, white 5%);
}

<div class="card"></div>


问:
How to generate locally the documentation for an imported pod
The script buildwebdocs.fan generates the documentation for the distribution's pods, but not for the pods I did myself or imported. How can I generate the documentation locally for this pods?

答:
That's a tricky question, and one I don't have an immediate answer (or script) for. However, assuming you only wish to view the documentation and don't require a directory of HTML files, then I can offer an alternative...

Install and use the Explorer application. It's a desktop file explorer application that, amongst other things, includes a Fandoc Viewer that lets you view documentation from pods in the current Fantom installation.

Example, to view the documentation for the afReflux pod, type afReflux (case-insensitive) in the address bar:

You can also press F1 to bring up an index page of all installed Fantom pods.


问:
GWT java URL Validator
Does someone knows a function that validate if a url is valid or not purely in GWT java without using any JSNI</p>

答:
I am using this one (making use of regular expressions):</p>

```<code>private RegExp urlValidator;
private RegExp urlPlusTldValidator;
public boolean isValidUrl(String url, boolean topLevelDomainRequired) {
    if (urlValidator == null || urlPlusTldValidator == null) {
        urlValidator = RegExp.compile("^((ftp|http|https)://[\\w@.\\-\\_]+(:\\d{1,5})?(/[\\w#!:.?+=&%@!\\_\\-/]+)*){1}$");
        urlPlusTldValidator = RegExp.compile("^((ftp|http|https)://[\\w@.\\-\\_]+\\.[a-zA-Z]{2,}(:\\d{1,5})?(/[\\w#!:.?+=&%@!\\_\\-/]+)*){1}$");
    }
    return (topLevelDomainRequired ? urlPlusTldValidator : urlValidator).exec(url) != null;
}
</code>```

Title: GWT java URL Validator

Body:
I am using this one (making use of regular expressions):

private RegExp urlValidator;
private RegExp urlPlusTldValidator;
public boolean isValidUrl(String url, boolean topLevelDomainRequired) {
    if (urlValidator == null || urlPlusTldValidator == null) {
        urlValidator = RegExp.compile("^((ftp|http|https)://[\\w@.\\-\\_]+(:\\d{1,5})?(/[\\w#!:.?+=&%@!\\_\\-/]+)*){1}$");
        urlPlusTldValidator = RegExp.compile("^((ftp|http|https)://[\\w@.\\-\\_]+\\.[a-zA-Z]{2,}(:\\d{1,5})?(/[\\w#!:.?+=&%@!\\_\\-/]+)*){1}$");
    }
    return (topLevelDomainRequired ? urlPlusTldValidator : urlValidator).exec(url) != null;
}


问:
Laravel 5.3 to 5.4 relations foreignKey issue
After updating to 5.4, my relations where not working properly anymore. After inspecting I found out Laravel is now looking for different
foreignKey names:  user_user_id or post_post_id instead of user_id,post_id etc. This was working until L 5.3. I also had to update some of my pivot tabels primarykey to tag_tag_id etc in order to get them working again.

I updated my tables foreignkey names according to this new convention and now it's working. But I still would like to know why and how this changed and where it's coming from.

Thanks!

答:
Are you overriding the primary key on your models using getKeyName ?

Laravel still uses the same convention user_id as the foreign key.

However, in 5.4, you don't need to explicitly specifying the foreign key when defining the relationship.

From the docs:

Just like previous Laravel releases, this relationship will typically use user_id as the foreign key. However, the behavior could be different from previous releases if you are overriding the  getKeyName method of the User model

Upgrading To 5.4.0 From 5.3

Update

The problem might be caused also by setting the value of  $primaryKey.
You did not submit any code. However, assuming on your user model, you define $primaryKey = user_id Laravel will append the column name to this key name. Thus, you see laravel trying to query user_user_id.

Just remove the $keyname from the user model, and laravel will assume the foreign key following the convention user_id.

Or you could define the foreign key explicitly passing a second argument to the belongsTo():

    return $this->belongsTo(User::class, 'user_id);


问:
How to make the query for quartile 1, 2, and 3 in MySQL?
I have a query for quartiles like this:

```<code>cast(substring_index(substring_index(group_concat(`lulusanmagisterrangkuman`.`IPK`
    order by `lulusanmagisterrangkuman`.`IPK` ASC separator ','),',',(((50 / 100) * count(0)) + 1)),',',-(1)) as decimal(10,0)) AS `Median`,
cast(substring_index(substring_index(group_concat(`lulusanmagisterrangkuman`.`IPK`
    order by `lulusanmagisterrangkuman`.`IPK` ASC separator ','),',',(((25 / 100) * count(0)) + 1)),',',-(1)) as decimal(10,0)) AS `Q1`,
cast(substring_index(substring_index(group_concat(`lulusanmagisterrangkuman`.`IPK`
    order by `lulusanmagisterrangkuman`.`IPK` ASC separator ','),',',(((75 / 100) * count(0)) + 1)),',',-(1)) as decimal(10,0)) AS `Q3`
</code>```

But this source code is not working for floating values. When I try those codes, the returned value was an integer. What can I do so that the quartile can be seen in integer or float value? Thanks in advance

答:
How about:
you cast the values as decimal(10,0) - the decimal is defined with a precision of 10 digits, but with zero scale.
have a look here: Precision & Scale in MySQL
I changed them to decimal(18,8) in the statement below.

Furthermore, you don't need things like (50 / 100) - just use 0.50

```<code>cast(substring_index(
        substring_index(
            group_concat(`lulusanmagisterrangkuman`.`IPK`
                          order by `lulusanmagisterrangkuman`.`IPK`
                          ASC separator ','
                        ),',',((0.50 * count(0)) + 1)
                       ),',',-(1)
                    ) as decimal(18,8)
    ) AS `Median`,
cast(substring_index(
        substring_index(
            group_concat(`lulusanmagisterrangkuman`.`IPK`
                          order by `lulusanmagisterrangkuman`.`IPK`
                          ASC separator ','
                        ),',',((0.25 * count(0)) + 1)
                       ),',',-(1)
                     ) as decimal(18,8)
    ) AS `Q1`,
cast(substring_index(
        substring_index(
            group_concat(`lulusanmagisterrangkuman`.`IPK`
                          order by `lulusanmagisterrangkuman`.`IPK`
                          ASC separator ','
                        ),',',((0.75 * count(0)) + 1)
                       ),',',-(1)
                    ) as decimal(18,8)
    ) AS `Q3`
</code>```

Body:
I have a query for quartiles like this:

cast(substring_index(substring_index(group_concat(`lulusanmagisterrangkuman`.`IPK`
    order by `lulusanmagisterrangkuman`.`IPK` ASC separator ','),',',(((50 / 100) * count(0)) + 1)),',',-(1)) as decimal(10,0)) AS `Median`,
cast(substring_index(substring_index(group_concat(`lulusanmagisterrangkuman`.`IPK`
    order by `lulusanmagisterrangkuman`.`IPK` ASC separator ','),',',(((25 / 100) * count(0)) + 1)),',',-(1)) as decimal(10,0)) AS `Q1`,
cast(substring_index(substring_index(group_concat(`lulusanmagisterrangkuman`.`IPK`
    order by `lulusanmagisterrangkuman`.`IPK` ASC separator ','),',',(((75 / 100) * count(0)) + 1)),',',-(1)) as decimal(10,0)) AS `Q3`

But this source code is not working for floating values. When I try those codes, the returned value was an integer. What can I do so that the quartile can be seen in integer or float value? Thanks in advance

Body:
How about:
you cast the values as decimal(10,0) - the decimal is defined with a precision of 10 digits, but with zero scale.
have a look here: Precision & Scale in MySQL
I changed them to decimal(18,8) in the statement below.

Furthermore, you don't need things like (50 / 100) - just use 0.50

cast(substring_index(
        substring_index(
            group_concat(`lulusanmagisterrangkuman`.`IPK`
                          order by `lulusanmagisterrangkuman`.`IPK`
                          ASC separator ','
                        ),',',((0.50 * count(0)) + 1)
                       ),',',-(1)
                    ) as decimal(18,8)
    ) AS `Median`,
cast(substring_index(
        substring_index(
            group_concat(`lulusanmagisterrangkuman`.`IPK`
                          order by `lulusanmagisterrangkuman`.`IPK`
                          ASC separator ','
                        ),',',((0.25 * count(0)) + 1)
                       ),',',-(1)
                     ) as decimal(18,8)
    ) AS `Q1`,
cast(substring_index(
        substring_index(
            group_concat(`lulusanmagisterrangkuman`.`IPK`
                          order by `lulusanmagisterrangkuman`.`IPK`
                          ASC separator ','
                        ),',',((0.75 * count(0)) + 1)
                       ),',',-(1)
                    ) as decimal(18,8)
    ) AS `Q3`


答:
You can use clip-path
https://developer.mozilla.org/en/docs/Web/CSS/clip-path

and use something like this:

div#test{
 background:red;
 width:200px;
 height: 200px;
 -webkit-clip-path: polygon(22% 0, 100% 0, 100% 100%, 0 100%, 0 20%);
clip-path: polygon(22% 0, 100% 0, 100% 100%, 0 100%, 0 20%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test"></div></code>```

Title: How to cut box corner Using CSS with transparent background?

Body:
I want to cut left top corner of a box using CSS like this.

keep in mind that background is transparent.

Body:
You can use clip-path
https://developer.mozilla.org/en/docs/Web/CSS/clip-path

and use something like this:

div#test{
 background:red;
 width:200px;
 height: 200px;
 -webkit-clip-path: polygon(22% 0, 100% 0, 100% 100%, 0 100%, 0 20%);
clip-path: polygon(22% 0, 100% 0, 100% 100%, 0 100%, 0 20%);
}

<div id="test"></div>


问:
How To Count Exact Matches on String by Two or More Letters
I have this simple string:

```<code>string code = "HelloWorld";
</code>```

Now I want to count the exact matches of:

```<code>string match = "ll"
</code>```

Which is my expected result is:

```<code>1
</code>```

Since there is only one exact match of double ll in "HelloWorld"

I am trying to do it by split:

```<code>var splitted = code.Split(new string[]{ "l", "l" }, StringSplitOptions.None);
</code>```

But as you would expect, if there was a match of single "l", it will also split it, so I cannot guarantee a good count.

I am trying to do it on a binary number:

```<code>1011010110110
</code>```

Which I want to get how many "10"s it have. Here on my example it has 5 exact 10s.

答:
Try to use regex. You match the string with the regex and count how many matches there are.

```<code>Regex.Matches("Hello", "ll").Count
</code>```

That will evaluate to 1.

Remember to using System.Text.RegularExpressions!

Body:
I have this simple string:

string code = "HelloWorld";

Now I want to count the exact matches of:

string match = "ll"

Which is my expected result is:

1

Since there is only one exact match of double ll in "HelloWorld"

I am trying to do it by split:

var splitted = code.Split(new string[]{ "l", "l" }, StringSplitOptions.None);

But as you would expect, if there was a match of single "l", it will also split it, so I cannot guarantee a good count.

I am trying to do it on a binary number:

1011010110110

Which I want to get how many "10"s it have. Here on my example it has 5 exact 10s.

Body:
Try to use regex. You match the string with the regex and count how many matches there are.

Regex.Matches("Hello", "ll").Count

That will evaluate to 1.

Remember to using System.Text.RegularExpressions!