问:
Java Sort map by key explanation
I recently found a great way to sort a map that contains GregorianCalendar as keys.

```<code>Map<GregorianCalendar, String> map = new HashMap<>();

Map<GregorianCalendar, String> sortedMap = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
            (oldValue, newValue) -> oldValue, LinkedHashMap::new));
</code>```

Can someone help me to understand each procedure called in this command especially going on from the stream function ?

Thanks

答:
map.entrySet().stream() produces a Stream of the entries of the input Map (i.e. a Stream<Map.Entry<GregorianCalendar,String>>.

.sorted(Map.Entry.comparingByKey()) sorts the elements of this Stream by the keys of the entries (it relies on the fact that the key type - GregorianCalendar - implements Comparable).

.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
            (oldValue, newValue) -> oldValue, LinkedHashMap::new))

produces a LinkedHashMap that contains the same entries as the input Map. Since you are using LinkedHashMap, the insertion order is maintained, and since you sorted the entries of the Stream by the keys, you get a Map whose insertion order (and iteration order) is according to the order of the keys.

Of course you can get a sorted Map more easily by putting all the entries of the input Map in a TreeMap:

```<code>Map<GregorianCalendar, String> sortedMap = new TreeMap<>(map);
</code>```

This has the advantage of maintaining the order even if you add new entries to the Map.

Title: Java Sort map by key explanation

Body:
I recently found a great way to sort a map that contains GregorianCalendar as keys.

Map<GregorianCalendar, String> map = new HashMap<>();

Map<GregorianCalendar, String> sortedMap = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
            (oldValue, newValue) -> oldValue, LinkedHashMap::new));

Can someone help me to understand each procedure called in this command especially going on from the stream function ?

Thanks

Body:
map.entrySet().stream() produces a Stream of the entries of the input Map (i.e. a Stream<Map.Entry<GregorianCalendar,String>>.

.sorted(Map.Entry.comparingByKey()) sorts the elements of this Stream by the keys of the entries (it relies on the fact that the key type - GregorianCalendar - implements Comparable).

.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
            (oldValue, newValue) -> oldValue, LinkedHashMap::new))

produces a LinkedHashMap that contains the same entries as the input Map. Since you are using LinkedHashMap, the insertion order is maintained, and since you sorted the entries of the Stream by the keys, you get a Map whose insertion order (and iteration order) is according to the order of the keys.

Of course you can get a sorted Map more easily by putting all the entries of the input Map in a TreeMap:

Map<GregorianCalendar, String> sortedMap = new TreeMap<>(map);

This has the advantage of maintaining the order even if you add new entries to the Map.


来源: stackexchange

答:
First you sort entries by Key via sorted(Map.Entry.comparingByKey())

then these are are collected to a Map (the implementation underneath uses HashMap), where the Key is of type GregorianCalendar and value is of type String. The code also supplies a merge function:

```<code>(oldValue, newValue) -> oldValue
</code>```

where they keep the last value, when there is a collision, like a "last-wins" policy. So when these is a collision ( two same GregorianCalendar values ), you will always keep the second one, whatever second means here. Since your source for streaming is a HashMap that does not have a defined order, this "second" can change if you have add or remove values from your initial map.

Once those are sorted and you collect them to a HashMap (via collect), you order can break, so the collecting happens in a LinkedHashMap basically preserving that sorted order

ContentLicense: CC BY-SA 3.0

Title: Java Sort map by key explanation

Body:
First you sort entries by Key via sorted(Map.Entry.comparingByKey())

then these are are collected to a Map (the implementation underneath uses HashMap), where the Key is of type GregorianCalendar and value is of type String. The code also supplies a merge function:

(oldValue, newValue) -> oldValue

where they keep the last value, when there is a collision, like a "last-wins" policy. So when these is a collision ( two same GregorianCalendar values ), you will always keep the second one, whatever second means here. Since your source for streaming is a HashMap that does not have a defined order, this "second" can change if you have add or remove values from your initial map.

Once those are sorted and you collect them to a HashMap (via collect), you order can break, so the collecting happens in a LinkedHashMap basically preserving that sorted order


问:
Android device monitor is not loading in android studio
My device configured with :
 mac Sierra 10.12.6,
 Android studio 2.3.3,
 java 8.
Android device monitor shows 'an error has occurred' and generated a log report.

Here is the few lines log report:I cant understand the issue with device monitor. How to resolve this issue?

```<code>!SESSION 2017-11-30 09:45:22.279 -----------------------------------------------
eclipse.buildId=unknown
java.version=1.6.0_65
java.vendor=Apple Inc.
BootLoader constants: OS=macosx, ARCH=x86_64, WS=cocoa, NL=en_US
Framework arguments:  -keyring /Users/sarathvijayaraghavan/.eclipse_keyring -showlocation
Command-line arguments:  -os macosx -ws cocoa -arch x86_64 -data @noDefault -keyring /Users/sarathvijayaraghavan/.eclipse_keyring -showlocation

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.746
!MESSAGE Bundle reference:file:org.apache.ant_1.8.3.v201301120609/@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.751
!MESSAGE Bundle reference:file:org.apache.jasper.glassfish_2.2.2.v201205150955.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.752
!MESSAGE Bundle reference:file:org.apache.lucene.core_2.9.1.v201101211721.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.822
!MESSAGE Bundle reference:file:org.eclipse.help.base_3.6.101.v201302041200.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.822
!MESSAGE Bundle reference:file:org.eclipse.help.ui_3.5.201.v20130108-092756.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.823
!MESSAGE Bundle reference:file:org.eclipse.help.webapp_3.6.101.v20130116-182509.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.824
!MESSAGE Bundle reference:file:org.eclipse.jetty.server_8.1.3.v20120522.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.828
!MESSAGE Bundle reference:file:org.eclipse.platform.doc.user_4.2.2.v20130121-200410.jar@4 not found.
</code>```

答:
Tried above mentioned method by @ArnoldBrown and some other solutions from similar questions.But those wont works for me.

 I just updated JDK and JRE with latest version. Problem solved after updation and restart . Don't know it is the exact solution or not.

Java reference link :
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Thanks everyone for your valuable time.

Body:
My device configured with :
 mac Sierra 10.12.6,
 Android studio 2.3.3,
 java 8.
Android device monitor shows 'an error has occurred' and generated a log report.

Here is the few lines log report:I cant understand the issue with device monitor. How to resolve this issue?

!SESSION 2017-11-30 09:45:22.279 -----------------------------------------------
eclipse.buildId=unknown
java.version=1.6.0_65
java.vendor=Apple Inc.
BootLoader constants: OS=macosx, ARCH=x86_64, WS=cocoa, NL=en_US
Framework arguments:  -keyring /Users/sarathvijayaraghavan/.eclipse_keyring -showlocation
Command-line arguments:  -os macosx -ws cocoa -arch x86_64 -data @noDefault -keyring /Users/sarathvijayaraghavan/.eclipse_keyring -showlocation

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.746
!MESSAGE Bundle reference:file:org.apache.ant_1.8.3.v201301120609/@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.751
!MESSAGE Bundle reference:file:org.apache.jasper.glassfish_2.2.2.v201205150955.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.752
!MESSAGE Bundle reference:file:org.apache.lucene.core_2.9.1.v201101211721.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.822
!MESSAGE Bundle reference:file:org.eclipse.help.base_3.6.101.v201302041200.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.822
!MESSAGE Bundle reference:file:org.eclipse.help.ui_3.5.201.v20130108-092756.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.823
!MESSAGE Bundle reference:file:org.eclipse.help.webapp_3.6.101.v20130116-182509.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.824
!MESSAGE Bundle reference:file:org.eclipse.jetty.server_8.1.3.v20120522.jar@4 not found.

!ENTRY org.eclipse.osgi 4 0 2017-11-30 09:45:23.828
!MESSAGE Bundle reference:file:org.eclipse.platform.doc.user_4.2.2.v20130121-200410.jar@4 not found.


问:
OGM Custom Query using Custom Label
I have a Neo4j/OGM Entity Person which I mapped to the Label User using
@NodeEntity(label="User).
I now want to write a custom Query MATCH (p:Person) where....
As far as I see, there is no way to use my Application-Side Type Person instead of the Graph-Side Label User like in Hibernate, right?
If there is a way, please explain how to do this, or tell my a key-word to google for.
Same question goes for entity properties.

Thank you.

Update:
Lets say I have a User class like so:

```<code>@NodeEntity(label="Person")
class User {
@Property(name="username")
   private String name;
   ...
}
</code>```

I've used the Mapping to obtain loose coupling so I can eg. rename the Person and won't affect the Neo4j.
And in the Neo4j there are for example Houses with Relationships to Users.
Now I want to load all Houses, referencing a User with the name "Sven", so the Statement would be MATCH (h:House)-[:HOLDS]->(p:Person {username:'Sven'}).
Given, that I might have a huge poject with all the entities in some submodule somewhere else, I might not know, that User is mapped to Person and the user.name is mapped to username, so in a Hibernate environment, I would query as MATCH (h:House)-[:HOLDS]->(u:User {name:'Sven'}). However in OGM this doesn't seem to work.
There might be a way to solve this architectually but in some projects you don't have this choise.

So the question in the End is: Is there some way to get this to work, or do I really need to know the mapping of every entity i use?

答:
You can do this in several ways :

Make your User extend a Person class

if you need more dynamic labels, the class can contain an @Labelsannotated list of labels to apply. See the documentation for more details

About properties, I don't see how this would be useful. Interested to hear about the use case.

Title: OGM Custom Query using Custom Label

Body:
I have a Neo4j/OGM Entity Person which I mapped to the Label User using
@NodeEntity(label="User).
I now want to write a custom Query MATCH (p:Person) where....
As far as I see, there is no way to use my Application-Side Type Person instead of the Graph-Side Label User like in Hibernate, right?
If there is a way, please explain how to do this, or tell my a key-word to google for.
Same question goes for entity properties.

Thank you.

Update:
Lets say I have a User class like so:

@NodeEntity(label="Person")
class User {
@Property(name="username")
   private String name;
   ...
}

I've used the Mapping to obtain loose coupling so I can eg. rename the Person and won't affect the Neo4j.
And in the Neo4j there are for example Houses with Relationships to Users.
Now I want to load all Houses, referencing a User with the name "Sven", so the Statement would be MATCH (h:House)-[:HOLDS]->(p:Person {username:'Sven'}).
Given, that I might have a huge poject with all the entities in some submodule somewhere else, I might not know, that User is mapped to Person and the user.name is mapped to username, so in a Hibernate environment, I would query as MATCH (h:House)-[:HOLDS]->(u:User {name:'Sven'}). However in OGM this doesn't seem to work.
There might be a way to solve this architectually but in some projects you don't have this choise.

So the question in the End is: Is there some way to get this to work, or do I really need to know the mapping of every entity i use?


问:
How to set up Identity in an ASP.Net core project using EF 6.0 in a separate class library
A while ago I asked this question about using EF with ASP.Net core, and this is working great.  Now that I want to add ASP.Net Identity, I'm wondering if the best approach is to add identity logic to the separate project with regular / non-core EF, or into the main core project with EF core, or something else.  I see a lot of pages that discuss EF core, but I would prefer to use the same context everywhere, and I would prefer to use regular EF as I am currently doing.  I'm looking for what would be a clean / best practices approach here, I have been using regular EF since to my knowledge EF core 1.0 doesn't support stored procs, and I prefer to continue to use a database first approach anyway.  Appreciate any help that gets me out of the quicksand.

NOTE: My 'User' table (called something else) has some existing profile data in it; I intend to use this as my Identity User table.

答:
ASP.Net Identity Framework is designed for Code-first, and will normally try to generate its tables for you.  I'm not sure if it is able to work Database-first, but I think you could get it working as follows:

Create a separate, temporary, project/solution with Identity / Individual User Account.

Insert the data structure from this temporary database into your main database, merging AspNetUsers with your User table.

Delete the temporary project/solution and database.

Update the models in your EF6 project.  This should bring in the new tables.

Add Identity Framework to your ASP.Net Core project, referencing the database context from your EF6 project.

I haven't tried this, but having worked with Identity Framework quite a bit I can't see a reason why it wouldn't work.

Further reading:

Database first Identity: Using Asp.Net Identity DataBase first approach

Custom table name for Users table: How can I change the table names when using Visual Studio 2013 ASP.NET Identity?


问:
Creating custom grid number (24) for Bootstrap 4
I have a project and I want to integrate some bootstrap into my html files for ui development. I know that the standard grid size is 12 and I wanted to change the number of grid spaces from 12 to 24. I know there is a way to do it from the documentation but I dont know how to where to integrate it.

This is the bootstrap documentation

```<code>$grid-columns:               12 !default;
$grid-gutter-width-base:     30px !default;
$grid-gutter-widths: (
  xs: $grid-gutter-width-base,
  sm: $grid-gutter-width-base,
  md: $grid-gutter-width-base,
  lg: $grid-gutter-width-base,
  xl: $grid-gutter-width-base
) !default;
</code>```

Where do I put it in my code.

```<code>CSS file
HTML file
Js file
....
</code>```

答:
Inside 'application.scss' you can add in your own stylesheet containing custom vars to override Bootstrap's:

```<code>// application.scss

@import "variables"; // Add custom vars here

@import "bootstrap/variables";

@import "bootstrap/main";

// _variables.scss

%scope {
  @import "boostrap/variables";

  @gridColumns: 24
  @gridColumnWidth: 30px
  @gridGutterWidth: 1px
  @gridColumnWidth1200: 35px
  @gridGutterWidth1200: 15px
  @gridColumnWidth768: 21px
  @gridGutterWidth768: 10px
}
</code>```

Check this answer for more info:
https://stackoverflow.com/a/38225564/1528308

Body:
I have a project and I want to integrate some bootstrap into my html files for ui development. I know that the standard grid size is 12 and I wanted to change the number of grid spaces from 12 to 24. I know there is a way to do it from the documentation but I dont know how to where to integrate it.

This is the bootstrap documentation

$grid-columns:               12 !default;
$grid-gutter-width-base:     30px !default;
$grid-gutter-widths: (
  xs: $grid-gutter-width-base,
  sm: $grid-gutter-width-base,
  md: $grid-gutter-width-base,
  lg: $grid-gutter-width-base,
  xl: $grid-gutter-width-base
) !default;

Where do I put it in my code.

CSS file
HTML file
Js file
....

Body:
Inside 'application.scss' you can add in your own stylesheet containing custom vars to override Bootstrap's:

// application.scss

@import "variables"; // Add custom vars here

@import "bootstrap/variables";

@import "bootstrap/main";

// _variables.scss

%scope {
  @import "boostrap/variables";

  @gridColumns: 24
  @gridColumnWidth: 30px
  @gridGutterWidth: 1px
  @gridColumnWidth1200: 35px
  @gridGutterWidth1200: 15px
  @gridColumnWidth768: 21px
  @gridGutterWidth768: 10px
}

Check this answer for more info:
https://stackoverflow.com/a/38225564/1528308


问:
Print out all possible strings in C using recursion
My assignment is that code takes a string as input, and if there are x's in the string replace them with either a 0 or a 1, and print out all the possible string combinations. We have to use recursion for this as well. For example, if the input string was "1x0X" the output would be:

```<code>1000
1001
1100
1101
</code>```

I'm really struggling with how I'm supposed to find all the permutations of the string without having the complete string yet. I have a series of function that combine to print out all permutations of a list of numbers, but I don't know how to make a function where it only permutes certain elements of a list.

Does anyone have any suggestions on how to accomplish this?

答:
I would do something a bit simpler.  Just use a position parameter to iterate over the input string. Whenever you hit the 'x' character recurse twice, once for '0' and once for '1'. Make sure to reset the character back to 'x' after you return.  Whenever you hit the digit character just recurse once.  Increment the position parameter each time you recurse.  When you hit the end of the string, print it out.  With this idea, you'd get something like this:

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

void print_combo(char *str, int pos) {
    char c;

    c = str[pos];
    switch (c) {
            case '0':
            case '1':
                    print_combo(str, pos+1);
                    break;
            case 'x':
            case 'X':
                    str[pos] = '0';
                    print_combo(str, pos+1);
                    str[pos] = '1';
                    print_combo(str, pos+1);
                    str[pos] = c;
                    break;
            case '\0':
                    printf("%s\n", str);
                    break;
            default:
                    printf("bad input\n");
                    break;
    }
}

int main() {
    char str[10];
    strcpy(str, "1x0x");
    printf("printing %s\n", str);
    print_combo(str, 0);
    strcpy(str, "0x01x");
    printf("printing %s\n", str);
    print_combo(str, 0);
    strcpy(str, "0x01x0X1");
    printf("printing %s\n", str);
    print_combo(str, 0);
    return 0;
}
</code>```

My output looks like this:

```<code>printing 1x0x
1000
1001
1100
1101
printing 0x01x
00010
00011
01010
01011
printing 0x01x0X1
00010001
00010011
00011001
00011011
01010001
01010011
01011001
01011011
</code>```

Body:
My assignment is that code takes a string as input, and if there are x's in the string replace them with either a 0 or a 1, and print out all the possible string combinations. We have to use recursion for this as well. For example, if the input string was "1x0X" the output would be:

1000
1001
1100
1101

I'm really struggling with how I'm supposed to find all the permutations of the string without having the complete string yet. I have a series of function that combine to print out all permutations of a list of numbers, but I don't know how to make a function where it only permutes certain elements of a list.

Does anyone have any suggestions on how to accomplish this?

Body:
I would do something a bit simpler.  Just use a position parameter to iterate over the input string. Whenever you hit the 'x' character recurse twice, once for '0' and once for '1'. Make sure to reset the character back to 'x' after you return.  Whenever you hit the digit character just recurse once.  Increment the position parameter each time you recurse.  When you hit the end of the string, print it out.  With this idea, you'd get something like this:

#include <stdio.h>

void print_combo(char *str, int pos) {
    char c;

    c = str[pos];
    switch (c) {
            case '0':
            case '1':
                    print_combo(str, pos+1);
                    break;
            case 'x':
            case 'X':
                    str[pos] = '0';
                    print_combo(str, pos+1);
                    str[pos] = '1';
                    print_combo(str, pos+1);
                    str[pos] = c;
                    break;
            case '\0':
                    printf("%s\n", str);
                    break;
            default:
                    printf("bad input\n");
                    break;
    }
}

int main() {
    char str[10];
    strcpy(str, "1x0x");
    printf("printing %s\n", str);
    print_combo(str, 0);
    strcpy(str, "0x01x");
    printf("printing %s\n", str);
    print_combo(str, 0);
    strcpy(str, "0x01x0X1");
    printf("printing %s\n", str);
    print_combo(str, 0);
    return 0;
}

My output looks like this:

printing 1x0x
1000
1001
1100
1101
printing 0x01x
00010
00011
01010
01011
printing 0x01x0X1
00010001
00010011
00011001
00011011
01010001
01010011
01011001
01011011


问:
Add parameters to Paypal Express Checkout Button for subscription payment
Is it possible to simply add parameters to the Paypal Express Checkout code - that will set up for subscription - or point to an existing subscription - already set up on my seller account?

```<code>payment: function(data, actions) {
return actions.payment.create({
    payment: {
        transactions: [
            {
                amount: { total: '0.11', currency: 'USD' },
                hosted_button_id: 'PAYPALS_BUTTON_ID_7KDHB44PVYQ21',
                or_maybe_subscriptio_detials: 'monthly'

            }
        ]
    }
});
</code>```

},

You know - like you can with their regular HTML buttons:

```<code><input type="hidden" name="hosted_button_id" value="PAYPALS_BUTTON_ID_7KDHB44PVYQ21">
</code>```

Or do you need to set up the subscription details dynamically through the API?

I like the pop-up and staying on your site of the Express Checkout.
But I am not sure it is worth a bunch of additional coding - when I could just send them off to PayPal with a HTML button.

答:
You can use Express Checkout to utilize the Recurring Payment but, the integration itself consist of ;

Setup Payment Authorization (SetExpressCheckout)

Redirect Customer to Authorization

Obtain Customer Details

Create Recurring Profiles.

It does not shared same dock just like WPS button you use to know.

Basically in SetExpressCheckout you would need to add below parameter ;

```<code>&L_BILLINGTYPE0=RecurringPayments    #The type of billing agreement
&L_BILLINGAGREEMENTDESCRIPTION0=RecurringPaymentWithEC    #The description of the billing agreement
</code>```

It would be set as ;

```<code>Endpoint URL: https://api-3t.sandbox.paypal.com/nvp
HTTP method: POST
POST data:
USER=insert_merchant_user_name_here
&PWD=insert_merchant_password_here
&SIGNATURE=insert_merchant_signature_value_here
&METHOD=SetExpressCheckout
&VERSION=86
&L_BILLINGTYPE0=RecurringPayments    #The type of billing agreement
&L_BILLINGAGREEMENTDESCRIPTION0=RecurringPaymentWithEC    #The description of the billing agreement
&cancelUrl=https://example.com/cancel    #For use if the consumer decides not to proceed with payment
&returnUrl=https://example.com/success   #For use if the consumer proceeds with payment
</code>```

After user is redirect, then the buyer need to provide an authorization for being charged with a specific terms.

After that call the CreateRecurringPaymentsProfileAPI

```<code>Endpoint URL: https://api-3t.sandbox.paypal.com/nvp
HTTP method: POST
POST data:
USER=insert_merchant_user_name_here
&PWD=insert_merchant_password_here
&SIGNATURE=insert_merchant_signature_value_here
&METHOD=CreateRecurringPaymentsProfile
&VERSION=86
&TOKEN=insert_token_value_here
&PAYERID=payer_id_value   #Identifies the customer's account
&PROFILESTARTDATE=2012-05-11T00:00:00Z    #Billing date start, in UTC/GMT format
&DESC=RecurringPaymentWithEC    #Profile description - same as billing agreement description
&BILLINGPERIOD=Month    #Period of time between billings
&BILLINGFREQUENCY=1    #Frequency of charges
&AMT=10    #The amount the buyer will pay in a payment period
&CURRENCYCODE=USD    #The currency, e.g. US dollars
&COUNTRYCODE=US    #The country code, e.g. US
&MAXFAILEDPAYMENTS=3    #Maximum failed payments before suspension of the profile
</code>```

In response you'll get

```<code>PROFILEID=I-6D5UGCVX1234
&PROFILESTATUS=ActiveProfile
&ACK=Success
...
</code>```

Body:
Is it possible to simply add parameters to the Paypal Express Checkout code - that will set up for subscription - or point to an existing subscription - already set up on my seller account?

payment: function(data, actions) {
return actions.payment.create({
    payment: {
        transactions: [
            {
                amount: { total: '0.11', currency: 'USD' },
                hosted_button_id: 'PAYPALS_BUTTON_ID_7KDHB44PVYQ21',
                or_maybe_subscriptio_detials: 'monthly'

            }
        ]
    }
});

},

You know - like you can with their regular HTML buttons:

<input type="hidden" name="hosted_button_id" value="PAYPALS_BUTTON_ID_7KDHB44PVYQ21">

Or do you need to set up the subscription details dynamically through the API?

I like the pop-up and staying on your site of the Express Checkout.
But I am not sure it is worth a bunch of additional coding - when I could just send them off to PayPal with a HTML button.

Body:
You can use Express Checkout to utilize the Recurring Payment but, the integration itself consist of ;

Setup Payment Authorization (SetExpressCheckout)

Redirect Customer to Authorization

Obtain Customer Details

Create Recurring Profiles.

It does not shared same dock just like WPS button you use to know.

Basically in SetExpressCheckout you would need to add below parameter ;

&L_BILLINGTYPE0=RecurringPayments    #The type of billing agreement
&L_BILLINGAGREEMENTDESCRIPTION0=RecurringPaymentWithEC    #The description of the billing agreement

It would be set as ;

Endpoint URL: https://api-3t.sandbox.paypal.com/nvp
HTTP method: POST
POST data:
USER=insert_merchant_user_name_here
&PWD=insert_merchant_password_here
&SIGNATURE=insert_merchant_signature_value_here
&METHOD=SetExpressCheckout
&VERSION=86
&L_BILLINGTYPE0=RecurringPayments    #The type of billing agreement
&L_BILLINGAGREEMENTDESCRIPTION0=RecurringPaymentWithEC    #The description of the billing agreement
&cancelUrl=https://example.com/cancel    #For use if the consumer decides not to proceed with payment
&returnUrl=https://example.com/success   #For use if the consumer proceeds with payment

After user is redirect, then the buyer need to provide an authorization for being charged with a specific terms.

After that call the CreateRecurringPaymentsProfileAPI

Endpoint URL: https://api-3t.sandbox.paypal.com/nvp
HTTP method: POST
POST data:
USER=insert_merchant_user_name_here
&PWD=insert_merchant_password_here
&SIGNATURE=insert_merchant_signature_value_here
&METHOD=CreateRecurringPaymentsProfile
&VERSION=86
&TOKEN=insert_token_value_here
&PAYERID=payer_id_value   #Identifies the customer's account
&PROFILESTARTDATE=2012-05-11T00:00:00Z    #Billing date start, in UTC/GMT format
&DESC=RecurringPaymentWithEC    #Profile description - same as billing agreement description
&BILLINGPERIOD=Month    #Period of time between billings
&BILLINGFREQUENCY=1    #Frequency of charges
&AMT=10    #The amount the buyer will pay in a payment period
&CURRENCYCODE=USD    #The currency, e.g. US dollars
&COUNTRYCODE=US    #The country code, e.g. US
&MAXFAILEDPAYMENTS=3    #Maximum failed payments before suspension of the profile

In response you'll get

PROFILEID=I-6D5UGCVX1234
&PROFILESTATUS=ActiveProfile
&ACK=Success
...


问:
TypeError: a float is required in python 3
I have a Python3 script as follows:

```<code>import math

Value_1 = float(input("what's the X1 value?")), float(input("what's the X2 value?"))

Value_2 = float(input("what's the Y1 value?")), float(input("what's the Y2 value?"))

equation =(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))

print (equation)
</code>```

with this output

what's the X1 value?3.0

what's the X2 value?12.0

what's the Y1 value?10.0

what's the Y2 value?110.0

Then the program return this error:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-15-cc8d8b28ff67> in <module>()
      5
      6
----> 7 equation = float(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))
      8
      9 print (equation)

TypeError: a float is required
</code>```

I have tried to use all tips for other questions but error persist. Any tips?

答:
no one cares about my question but I figure out it by myself. Here we go:</p>

```<code>import math

x1 = float(input("what's the X1 value?"))

x2 = float (input("what's the X2 value?"))

print (x2 - x1)

xdiff = abs (x2 - x1)

print (xdiff)

y1 = float(input("what's the y1 value?"))

y2 = float (input("what's the y2 value?"))

ydiff = abs(y2 - y1)
print (ydiff)

math.sqrt(math.pow(xdiff,2) + math.pow(ydiff,2))
</code>```

Body:
I have a Python3 script as follows:

import math

Value_1 = float(input("what's the X1 value?")), float(input("what's the X2 value?"))

Value_2 = float(input("what's the Y1 value?")), float(input("what's the Y2 value?"))

equation =(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))

print (equation)

with this output

what's the X1 value?3.0

what's the X2 value?12.0

what's the Y1 value?10.0

what's the Y2 value?110.0

Then the program return this error:

TypeError                                 Traceback (most recent call last)
<ipython-input-15-cc8d8b28ff67> in <module>()
      5
      6
----> 7 equation = float(math.sqrt(math.sqrt(Value_1)+ math.sqrt(Value_2)))
      8
      9 print (equation)

TypeError: a float is required

I have tried to use all tips for other questions but error persist. Any tips?

Body:
no one cares about my question but I figure out it by myself. Here we go:

import math

x1 = float(input("what's the X1 value?"))

x2 = float (input("what's the X2 value?"))

print (x2 - x1)

xdiff = abs (x2 - x1)

print (xdiff)

y1 = float(input("what's the y1 value?"))

y2 = float (input("what's the y2 value?"))

ydiff = abs(y2 - y1)
print (ydiff)

math.sqrt(math.pow(xdiff,2) + math.pow(ydiff,2))


问:
WebRTC in Chrome (JsSIP) and SDP directive "UDP/TLS/RTP/SAVPF"
I use the library JsSIP to make SIP calls over WebRTC plataform in Google Chrome web browser. I have to change the SDP directive "UDP/TLS/RTP/SAVPF" in SIP request to "UDP/RTP/AVPF" in JsSIP.js file because the Asterisk server reject calls no encrypted in TLS context and i need the calls no encrypted. But even with the change, the browser continues to send the "UDP/TLS/RTP/SAVPF" in SIP request. Anyone can help me? The WebRTC implementation or Chrome intercepts the SIP request and change to "UDP/TLS/RTP/SAVPF"? Or in some way, this directive is in cache request and needs a clean up? (I already tried to clean the Chrome cache). Or have another explanation to that?</p>

答: Chrome doesn't allow unencrypted/unsecure RTP. It always forces SRTP/DTLS encryption.</p>


问:
How did they do this? [iPhone layout]
checkout this app:

 If you swipe left in main image (the black shoes) you can see another image.

Can anyone try this app (Fashiolista, it's free and signup isn't required) and
say me how can I do an effect like that?

Thank you guys.

答: Looks like they are lowering the opacity of the content as it scrolls of using core animation and ease out transition </p>

ContentLicense: CC BY-SA 2.5

Title: How did they do this? [iPhone layout]


问:
Which dataset used in jakeret/tf_unet U-Net implementation?
I am trying to implement U-net and I use https://github.com/jakeret/tf_unet/tree/master/scripts this link as reference. I don't understand which dataset they used. please give me some idea or link which dataset i use. </p>

答:
On their github README.md they show three different datasets, that they applied their implementation to. Their implementation is dataset agnostic, therefore it shouldn't matter too much what data they use if you're trying to solve your own problem with your own data. But if you're looking for a toy data set to play around, check out their demos. There you'll see two readily available examples and how they can be used:

demo_radio_data.ipynb which uses an astronomic radio data example set from here: http://people.phys.ethz.ch/~ast/cosmo/bgs_example_data/

demo_toy_problem.ipynb which uses their built-in data generator of a noisy image with circles that are to be detected.

The latter is probably the easiest one if it comes to just having something to play with. To see how data is generated, check out the class:
image_gen.py -> GrayScaleDataProvider
(with an IDE like PyCharm you can just jump into the according classes in the demo source code)


问:
Why are these semicolumns in this for loop?
I was just looking at W3schools, and was looking at the "for loops". I saw this code example:

```<code>var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
for (;cars[i];) {
    text += cars[i] + "<br>";
    i++;
}
document.getElementById("demo").innerHTML = text;
</code>```

I saw these semicolumns in the "for loop", I removed them and tried running it again. And as you expect, I got an error. Why are these semicolumns there? This is the first time I saw this and I'm really curious why these need to be there.

Thanks if you can give me some information about this because I couldn't find anything about it...

答:
```<code>for (;cars[i];)
</code>```

First semicolon:
Usually in for loops we declare a counter. But, here the counter is already defined outside the for loop. So, a empty statement.

Second semicolon:
As soon as the counter i exceeds the length of the array, using arr[i] while return undefined which is falsy and the loop will be terminated. Usually after the second semicolon we increment or decrement the counter, but here the counter is incremented in the for loop itself.

The semicolons are there so that we don't get a syntax error.

Body:
I was just looking at W3schools, and was looking at the "for loops". I saw this code example:

var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var text = "";
for (;cars[i];) {
    text += cars[i] + "
";
    i++;
}
document.getElementById("demo").innerHTML = text;

I saw these semicolumns in the "for loop", I removed them and tried running it again. And as you expect, I got an error. Why are these semicolumns there? This is the first time I saw this and I'm really curious why these need to be there.

Thanks if you can give me some information about this because I couldn't find anything about it...

Body:
for (;cars[i];)

First semicolon:
Usually in for loops we declare a counter. But, here the counter is already defined outside the for loop. So, a empty statement.

Second semicolon:
As soon as the counter i exceeds the length of the array, using arr[i] while return undefined which is falsy and the loop will be terminated. Usually after the second semicolon we increment or decrement the counter, but here the counter is incremented in the for loop itself.

The semicolons are there so that we don't get a syntax error.


问:
Xamarin forms - Custom Picker Renderer
I am currently doing a custom render for a picker in ios and using uitextfield for it but apparently it lets you copy and paste with the text in the custom picker after I do a custom render of it in ios. So is there a way to disable UItextfield copy and paste in a custom render ty</p>

答:
Try overriding the CanPerform method in the renderer like this:</p>

```<code>public override bool CanPerform(ObjCRuntime.Selector action, NSObject withSender)
{
    return base.CanPerform(action, withSender);
    if (action == new ObjCRuntime.Selector("paste:"))
        return false;
    return base.CanPerform(action, withSender);
}
</code>```

Title: Xamarin forms - Custom Picker Renderer

Body:
Try overriding the CanPerform method in the renderer like this:

public override bool CanPerform(ObjCRuntime.Selector action, NSObject withSender)
{
    return base.CanPerform(action, withSender);
    if (action == new ObjCRuntime.Selector("paste:"))
        return false;
    return base.CanPerform(action, withSender);
}


问:
try catch block indentation in Emacs
I'm using the bsd style of indentation in emacs & I'd like to modify it a bit.  The related portion of my .emacs file is below.  When I write a function with try catch blocks the braces are indented.  I'd like them to not indent similar to a function.

What's it's doing now.

```<code>try
    {
    }
catch
    {
    }
</code>```

What I'd like it to do.

```<code>try
{
}
catch
{
}
</code>```

.emacs file

```<code>(defun my-c-mode-common-hook ()
  ;; my customizations for all of c-mode and related modes
  ;; other customizations can go here
  (setq c-default-style "bsd")
  (setq c-basic-offset 4)
  (setq indent-tabs-mode nil)
  )

(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
</code>```

Any help would be appreciated.

答: Go to the line with the indent you'd like to change and press C-c C-o.  This runs c-set-offset and defaults to the current line's syntax (in this case substatement-open).  '+' means one level of indent, '-' means one level unindent, and '0' means no additional indent.  You want 0.  To make it permanent, add (c-set-offset 'substatement-open 0) to your hook.</p>

Title: try catch block indentation in Emacs

Body:
I'm using the bsd style of indentation in emacs & I'd like to modify it a bit.  The related portion of my .emacs file is below.  When I write a function with try catch blocks the braces are indented.  I'd like them to not indent similar to a function.

What's it's doing now.

try
    {
    }
catch
    {
    }

What I'd like it to do.

try
{
}
catch
{
}

.emacs file

(defun my-c-mode-common-hook ()
  ;; my customizations for all of c-mode and related modes
  ;; other customizations can go here
  (setq c-default-style "bsd")
  (setq c-basic-offset 4)
  (setq indent-tabs-mode nil)
  )

(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

Any help would be appreciated.


问:
Can filebeat output to other application
The filebeat can be set to output to elasticsearch, logstash, file or console. Is it possible that filebeat can be input source for other application.</p>

答:
The following are the output possibilities of filebeat as per the latest release:

Elastic

Logstash

Kafka

Redis

File

Console

Cloud

But filebeat is an open source agent. You can create a plugin of your own to suit the needs of your application.


问:
How to use cordova-plugin-android-permissions in Ionic 3?
I am using a couple of cordova plugins like camera and Image Pickers in my App and they work great on all the Devices… but the problem comes for getting the Permission to these plugins from the phone. Below Android 6 Versions asks for these permissions while installing but Android 6 and above ask for these permissions only when for the first time when the user uses that plugin inside the application(i.e during the Runtime).

I found this Ionic native plugin to handle these permissions in all versions of Android But exactly not getting how to use it or where to use it in my code, So If anyone has any Videos or know anything about it then please mention it here.

Thanks,

答:
I figured it out how to use this native plugin. this is what I tried.

Installed the Plugin as mentioned in this ionic doc

then in my app.component.ts file

```<code>import { AndroidPermissions } from '@ionic-native/android-permissions';

constructor(platform: Platform, androidPermissions: AndroidPermissions) {
    platform.ready().then(() => {

         androidPermissions.requestPermissions(
           [
             androidPermissions.PERMISSION.CAMERA,
             androidPermissions.PERMISSION.CALL_PHONE,
             androidPermissions.PERMISSION.GET_ACCOUNTS,
             androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE,
             androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE
           ]
         );

    })
}
</code>```

I hope this will help someone. Thanks.

Body:
I figured it out how to use this native plugin. this is what I tried.

Installed the Plugin as mentioned in this ionic doc

then in my app.component.ts file

import { AndroidPermissions } from '@ionic-native/android-permissions';

constructor(platform: Platform, androidPermissions: AndroidPermissions) {
    platform.ready().then(() => {

         androidPermissions.requestPermissions(
           [
             androidPermissions.PERMISSION.CAMERA,
             androidPermissions.PERMISSION.CALL_PHONE,
             androidPermissions.PERMISSION.GET_ACCOUNTS,
             androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE,
             androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE
           ]
         );

    })
}

I hope this will help someone. Thanks.


问:
openlayers strategy: ol.loadingstrategy.bbox does'nt work with wfs features
I tried to visualize parcels in wfs with openlayers 4 (max 1000) with this code.
But the extent does not change at each movement or zoom of the view map, or the new features do not load in the layer?</p>

```<code> var parcellaireSource =  new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    url: function (extent) {
      return  'https://wxs.ign.fr/api key/geoportail/wfs?request=GetCapabilities&SERVICE=WFS&VERSION=2.0.0&request=GetFeature&typename=BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:parcelle&outputFormat=application/json&srsname=EPSG:2154&bbox='+ extent.join(',') + ',EPSG:3857';

          },

    strategy: ol.loadingstrategy.bbox
    });
     var parcellairewfs =  new ol.layer.Vector({
    source: parcellaireSource
  });
     map.addLayer(parcellairewfs);
</code>```

答:
It works know when I add

```<code>function onMoveEnd(evt) { parcellaireSource.clear() } map.on('moveend', onMoveEnd);
</code>```

But, because of the number of features limit, I want to load them only on a certain zoom level. Do you see how to do it ?

Body:
I tried to visualize parcels in wfs with openlayers 4 (max 1000) with this code.
But the extent does not change at each movement or zoom of the view map, or the new features do not load in the layer?

 var parcellaireSource =  new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    url: function (extent) {
      return  'https://wxs.ign.fr/api key/geoportail/wfs?request=GetCapabilities&SERVICE=WFS&VERSION=2.0.0&request=GetFeature&typename=BDPARCELLAIRE-VECTEUR_WLD_BDD_WGS84G:parcelle&outputFormat=application/json&srsname=EPSG:2154&bbox='+ extent.join(',') + ',EPSG:3857';

          },

    strategy: ol.loadingstrategy.bbox
    });
     var parcellairewfs =  new ol.layer.Vector({
    source: parcellaireSource
  });
     map.addLayer(parcellairewfs);

Body:
It works know when I add

function onMoveEnd(evt) { parcellaireSource.clear() } map.on('moveend', onMoveEnd);

But, because of the number of features limit, I want to load them only on a certain zoom level. Do you see how to do it ?


问:
How to resolve the Add-PSSnapin Microsoft.TeamFoundation.PowerShell and Get-TfsChildItem error?
Below is the PowerShell Script that I am using to download the folder from TFS 2013 Update 4 to my local machine but i am getting some exception which I have copied below the code.

```<code>$AutoDeployDir = "$/Intel/Installscript/Utility Scripts"
$deployDirectory = "C:\powershell scripts\New folder\Demo TFS Code"

# Add TFS 2013 dlls so we can download some files
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Client")
$tfsCollectionUrl = "http://stptfs2013dbsvr:8080/tfs/intelcollection"
$tfsCollection = New-Object -TypeName Microsoft.TeamFoundation.Client.TfsTeamProjectCollection -ArgumentList $tfsCollectionUrl
$tfsVersionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])

# Register PowerShell commands
Add-PSSnapin Microsoft.TeamFoundation.PowerShell

# Get all directories and files in the AutoDeploy directory
$items = Get-TfsChildItem $AutoDeployDir -Recurse -Server $tfsCollection

# Download each item to a specific destination
foreach ($item in $items) {
    # Serverpath of the item
    Write-Host "TFS item to download:" $($item.ServerItem) -ForegroundColor Blue

    $destinationPath = $item.ServerItem.Replace($AutoDeployDir, $deployDirectory)
    Write-Host "Download to" $([IO.Path]::GetFullPath($destinationPath)) -ForegroundColor Blue

    if ($item.ItemType -eq "Folder") {
        New-Item $([IO.Path]::GetFullPath($destinationPath)) -ItemType Directory -Force
    }
    else {
        # Download the file (not folder) to destination directory
        $tfsVersionControl.DownloadFile($item.ServerItem, $([IO.Path]::GetFullPath($destinationPath)))
    }
}
</code>```

Exception that occurs is:

```<code>Add-PSSnapin : The Windows PowerShell snap-in 'Microsoft.TeamFoundation.PowerShell' is not installed on this computer.
At C:\powershell scripts\demo1.ps1:12 char:1
+ Add-PSSnapin Microsoft.TeamFoundation.PowerShell
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (Microsoft.TeamFoundation.PowerShell:String) [Add-PSSnapin], PSArgumentException
    + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand

Get-TfsChildItem : The term 'Get-TfsChildItem' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\powershell scripts\demo1.ps1:15 char:10
+ $items = Get-TfsChildItem $AutoDeployDir -Recurse -Server $tfsCollection
+          ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-TfsChildItem:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
</code>```

答:
Please make sure you have fully installed the TFS Powertools.

By default it doesn’t install the PowerShell CmdLets. If it is, just install it and then the issue will be gone.

Another possibility is that the PowerShell Snap-in is stored in the inconsistent  registry with the OS version (32bit/64bit).

PowerTools installer is 32bit, on 64bit machine, it will write to
  HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\PowerShell\1\PowerShellSnapIns,
  but not to
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowerShellSnapIns.

Reference this similar thread for details: TFS Power Tools 2008 Powershell Snapin won’t run in on 64-bit in Windows 2008 R2?

Body:
Below is the PowerShell Script that I am using to download the folder from TFS 2013 Update 4 to my local machine but i am getting some exception which I have copied below the code.

$AutoDeployDir = "$/Intel/Installscript/Utility Scripts"
$deployDirectory = "C:\powershell scripts\New folder\Demo TFS Code"

# Add TFS 2013 dlls so we can download some files
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Client")
$tfsCollectionUrl = "http://stptfs2013dbsvr:8080/tfs/intelcollection"
$tfsCollection = New-Object -TypeName Microsoft.TeamFoundation.Client.TfsTeamProjectCollection -ArgumentList $tfsCollectionUrl
$tfsVersionControl = $tfsCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])

# Register PowerShell commands
Add-PSSnapin Microsoft.TeamFoundation.PowerShell

# Get all directories and files in the AutoDeploy directory
$items = Get-TfsChildItem $AutoDeployDir -Recurse -Server $tfsCollection

# Download each item to a specific destination
foreach ($item in $items) {
    # Serverpath of the item
    Write-Host "TFS item to download:" $($item.ServerItem) -ForegroundColor Blue

    $destinationPath = $item.ServerItem.Replace($AutoDeployDir, $deployDirectory)
    Write-Host "Download to" $([IO.Path]::GetFullPath($destinationPath)) -ForegroundColor Blue

    if ($item.ItemType -eq "Folder") {
        New-Item $([IO.Path]::GetFullPath($destinationPath)) -ItemType Directory -Force
    }
    else {
        # Download the file (not folder) to destination directory
        $tfsVersionControl.DownloadFile($item.ServerItem, $([IO.Path]::GetFullPath($destinationPath)))
    }
}

Exception that occurs is:

Add-PSSnapin : The Windows PowerShell snap-in 'Microsoft.TeamFoundation.PowerShell' is not installed on this computer.
At C:\powershell scripts\demo1.ps1:12 char:1
+ Add-PSSnapin Microsoft.TeamFoundation.PowerShell
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (Microsoft.TeamFoundation.PowerShell:String) [Add-PSSnapin], PSArgumentException
    + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand

Get-TfsChildItem : The term 'Get-TfsChildItem' is not recognized as the name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\powershell scripts\demo1.ps1:15 char:10
+ $items = Get-TfsChildItem $AutoDeployDir -Recurse -Server $tfsCollection
+          ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-TfsChildItem:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


问:
How to send mail using gmail rest api from postmnan native application
My requirement is that send an email to some recipient with text body using POSTMAN Native app,
I used the below endpoint with requested data,

Base URL: https://www.googleapis.com/gmail/v1/users/userId/messages/send

Headers :Authorization:Bearer

Request Method :POST

Request body :{"raw";"to:user1mail@gmail.com","subject":"Test_Mail"}

Clicking Send button

But getting error response code 400,required recipient address
Please help me in this to send an email using POSTMAN,and I've tried with upload end point too -https://www.googleapis.com/upload/gmail/v1/users/user1email@gmail.com/messages/send

Thanks in advance,looking for help guys

答:
400 error means bad request, which could mean there are missing or wrong parameters. Check the Users.messages.send

Path parameters

userId  string  The user's email address. The special value me can be
  used to indicate the authenticated user.

Required query parameters

uploadType  string  The type of upload request to the /upload URI.
  Acceptable values are:

media - Simple upload. Upload the media only, without any metadata.

multipart - Multipart upload. Upload both the media and its metadata, in a single request.

resumable - Resumable upload. Upload the file in a resumable fashion, using a series of at least two requests where the first
  request includes the metadata.

ContentLicense: CC BY-SA 4.0


问:
How to apply a function to dataframe using list
I have a df

```<code>id a1 a2
1  x1 y1
2  x2 y2
</code>```

and another dataframe df2

```<code>id name1 name2
1  a1    b1
1  a2    b2
2  a3    b3
3  a4    b4
3  a5    b5
</code>```

df2 could contain multiple records of unique id's from df1.

I need to join the dataframes in such a way that for each row of df1, i should have one column from first record of df2 and if it exists, second column from second record.

To explain, the output should be like :

```<code>id a1 a2 n1 n2
1  x1 y1 a1  a2
2  x2 y2 a3 NA
</code>```

For doing this I have split df2 on id using split

```<code>s <- split(df2, df2$id)
</code>```

but i'm unsure how to use sapply over that. Any pointers for this

答:
If we are not taking the 'name2' column

```<code>library(dplyr)
df2 %>%
   filter(id %in% df$id) %>%
   select(-name2) %>%
   group_by(id) %>%
   mutate(rn = paste0("n", row_number())) %>%
   spread(rn, name1) %>%
   left_join(df, .)
#  id a1 a2 n1   n2
#1  1 x1 y1 a1   a2
#2  2 x2 y2 a3 <NA>
</code>```

data

```<code>df <- structure(list(id = 1:2, a1 = c("x1", "x2"), a2 = c("y1", "y2"
)), .Names = c("id", "a1", "a2"), class = "data.frame", row.names = c(NA,
 -2L))

df2 <- structure(list(id = c(1L, 1L, 2L, 3L, 3L), name1 = c("a1", "a2",
 "a3", "a4", "a5"), name2 = c("b1", "b2", "b3", "b4", "b5")), .Names = c("id",
 "name1", "name2"), class = "data.frame", row.names = c(NA, -5L))
</code>```

Body:
I have a df

id a1 a2
1  x1 y1
2  x2 y2

and another dataframe df2

id name1 name2
1  a1    b1
1  a2    b2
2  a3    b3
3  a4    b4
3  a5    b5

df2 could contain multiple records of unique id's from df1.

I need to join the dataframes in such a way that for each row of df1, i should have one column from first record of df2 and if it exists, second column from second record.

To explain, the output should be like :

id a1 a2 n1 n2
1  x1 y1 a1  a2
2  x2 y2 a3 NA

For doing this I have split df2 on id using split

s <- split(df2, df2$id)

but i'm unsure how to use sapply over that. Any pointers for this

Body:
If we are not taking the 'name2' column

library(dplyr)
df2 %>%
   filter(id %in% df$id) %>%
   select(-name2) %>%
   group_by(id) %>%
   mutate(rn = paste0("n", row_number())) %>%
   spread(rn, name1) %>%
   left_join(df, .)
#  id a1 a2 n1   n2
#1  1 x1 y1 a1   a2
#2  2 x2 y2 a3 <NA>

data

df <- structure(list(id = 1:2, a1 = c("x1", "x2"), a2 = c("y1", "y2"
)), .Names = c("id", "a1", "a2"), class = "data.frame", row.names = c(NA,
 -2L))

df2 <- structure(list(id = c(1L, 1L, 2L, 3L, 3L), name1 = c("a1", "a2",
 "a3", "a4", "a5"), name2 = c("b1", "b2", "b3", "b4", "b5")), .Names = c("id",
 "name1", "name2"), class = "data.frame", row.names = c(NA, -5L))


问:
React child component does not receive props on first load
I am fetching data in parent 'wrapper' component and pass it down to two child components. One child component receives it well, another does not.

In container:

```<code>const mapStateToProps = createStructuredSelector({
  visitedCountriesList: getVisitedCountriesList(),
  visitedCountriesPolygons: getVisitedCountriesPolygons()
});

export function mapDispatchToProps(dispatch) {
  return {
    loadVisitedCountries: () => {
      dispatch(loadVisitedCountriesRequest())
    },
  };
}
</code>```

in redux-saga I fetch data from API and store them:

```<code>function mapPageReducer(state = initialState, action) {
   switch (action.type) {
     case FETCH_VISITED_COUNTRIES_SUCCESS:
       return state
         .setIn(['visitedCountriesPolygons', 'features'], action.polygons)
 }
</code>```

Selectors:

```<code>const getVisitedCountriesList = () => createSelector(
  getMapPage,
  (mapState) => {
    let countriesList = mapState.getIn(['visitedCountriesPolygons', 'features']).map(c => {
      return {
        alpha3: c.id,
        name: c.properties.name
      }
    });
    return countriesList;
  }
)

const getVisitedCountriesPolygons = () => createSelector(
  getMapPage,
  (mapState) => mapState.get('visitedCountriesPolygons')
)
</code>```

in a wrapper component I render two components, triggering data fetch and passing props down to child components (visitedCountriesPolygons and visitedCountriesList):

```<code>class MapView extends React.Component {
  constructor(props) {
    super(props)
    this.props.loadVisitedCountries();
  }

  render() {
    return (
      <div>
        <Map visitedCountriesPolygons={this.props.visitedCountriesPolygons} />
        <MapActionsTab visitedCountriesList={this.props.visitedCountriesList} />
      </div>
    );
  }
}
</code>```

Then, in first child component Map I receive props well and can build a map:

```<code>componentDidMount() {
    this.map.on('load', () => {
      this.drawVisitedPolygons(this.props.visitedCountriesPolygons);
    });
};
</code>```

But in the second component MapActionsTab props are not received at initial render, but only after any update:

```<code>class MapActionsTab extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    let countriesList = this.props.visitedCountriesList.map(country => {
      return <li key={country.alpha3}>{country.name}</li>;
    }) || '';

    return (
      <Wrapper>
          <div>{countriesList}</div>
      </Wrapper>
    );
  }
}
</code>```

UPD:
Saga to fetch data form API:

```<code>export function* fetchVisitedCountries() {
  const countries = yield request
    .get('http://...')
    .query()
    .then((res, err) => {
      return res.body;
  });
  let polygons = [];
  yield countries.map(c => {
    request
      .get(`https://.../${c.toUpperCase()}.geo.json`)
      .then((res, err) => {
        polygons.push(res.body.features[0]);
      })
  });
  yield put(fetchVisitedCountriesSuccess(polygons));
}
</code>```

and a simple piece of reducer to store data:

```<code>case FETCH_VISITED_COUNTRIES_SUCCESS:
       return state
         .setIn(['visitedCountriesPolygons', 'features'], action.polygons)
</code>```

Why is it different and how to solve it, please?

thanks,
Roman

答:
Apparently, this works correct and it was just a minor issue in another place (not pasted here and not errors reported).
After thorough clean up and refactoring it worked as expected.

Conclusion: always keep your code clean, use linter and follow best practices :)

Body:
I am fetching data in parent 'wrapper' component and pass it down to two child components. One child component receives it well, another does not.

In container:

const mapStateToProps = createStructuredSelector({
  visitedCountriesList: getVisitedCountriesList(),
  visitedCountriesPolygons: getVisitedCountriesPolygons()
});

export function mapDispatchToProps(dispatch) {
  return {
    loadVisitedCountries: () => {
      dispatch(loadVisitedCountriesRequest())
    },
  };
}

in redux-saga I fetch data from API and store them:

function mapPageReducer(state = initialState, action) {
   switch (action.type) {
     case FETCH_VISITED_COUNTRIES_SUCCESS:
       return state
         .setIn(['visitedCountriesPolygons', 'features'], action.polygons)
 }

Selectors:

const getVisitedCountriesList = () => createSelector(
  getMapPage,
  (mapState) => {
    let countriesList = mapState.getIn(['visitedCountriesPolygons', 'features']).map(c => {
      return {
        alpha3: c.id,
        name: c.properties.name
      }
    });
    return countriesList;
  }
)

const getVisitedCountriesPolygons = () => createSelector(
  getMapPage,
  (mapState) => mapState.get('visitedCountriesPolygons')
)

in a wrapper component I render two components, triggering data fetch and passing props down to child components (visitedCountriesPolygons and visitedCountriesList):

class MapView extends React.Component {
  constructor(props) {
    super(props)
    this.props.loadVisitedCountries();
  }

  render() {
    return (

        <Map visitedCountriesPolygons={this.props.visitedCountriesPolygons} />
        <MapActionsTab visitedCountriesList={this.props.visitedCountriesList} />

    );
  }
}

Then, in first child component Map I receive props well and can build a map:

componentDidMount() {
    this.map.on('load', () => {
      this.drawVisitedPolygons(this.props.visitedCountriesPolygons);
    });
};

But in the second component MapActionsTab props are not received at initial render, but only after any update:

class MapActionsTab extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    let countriesList = this.props.visitedCountriesList.map(country => {
      return
{country.name}
;
    }) || '';

    return (
      <Wrapper>

{countriesList}

      </Wrapper>
    );
  }
}

UPD:
Saga to fetch data form API:

export function* fetchVisitedCountries() {
  const countries = yield request
    .get('http://...')
    .query()
    .then((res, err) => {
      return res.body;
  });
  let polygons = [];
  yield countries.map(c => {
    request
      .get(`https://.../${c.toUpperCase()}.geo.json`)
      .then((res, err) => {
        polygons.push(res.body.features[0]);
      })
  });
  yield put(fetchVisitedCountriesSuccess(polygons));
}

and a simple piece of reducer to store data:

case FETCH_VISITED_COUNTRIES_SUCCESS:
       return state
         .setIn(['visitedCountriesPolygons', 'features'], action.polygons)

Why is it different and how to solve it, please?

thanks,
Roman


问:
Decode all possible HTML entities?
We are working on a large amount of HTML data that needs to be converted to plain text. In the process we find not html_entity_decode() nor htmlspecialchars_decode() converts more than a few entities, e.g. &lt, &gt, ", $amp; and that's it.

However in modern day HTML pages, there are quite some common entities:

```<code>→
»
°
®
©
'
£
¥
€
∑
™
</code>```

Which are all ignored by these functions.

What are my options to convert them to their corresponding character? I guess my best option would be to manually write a string replace function to do this?

答:
html_entity_decode should be the answer, it just has stupid defaults and thus you are probably using it wrong. try

```<code>$text=html_entity_decode($html,ENT_QUOTES|ENT_HTML5,'UTF-8')
</code>```

alternatively,

```<code>$text=(@DOMDocument::loadHTML('<root>'.$html.'</root>'))->getElementsByTagName("root")->item(0)->textContent;
</code>```

may also work

ps, i have no idea what all the downvotes are about, but i didnt read the comments either

Title: Decode all possible HTML entities?

Body:
We are working on a large amount of HTML data that needs to be converted to plain text. In the process we find not html_entity_decode() nor htmlspecialchars_decode() converts more than a few entities, e.g. &lt, &gt, ", $amp; and that's it.

However in modern day HTML pages, there are quite some common entities:

→
»
°
®
©
'
£
¥
€
∑
™

Which are all ignored by these functions.

What are my options to convert them to their corresponding character? I guess my best option would be to manually write a string replace function to do this?

Body:
html_entity_decode should be the answer, it just has stupid defaults and thus you are probably using it wrong. try

$text=html_entity_decode($html,ENT_QUOTES|ENT_HTML5,'UTF-8')

alternatively,

$text=(@DOMDocument::loadHTML('<root>'.$html.'</root>'))->getElementsByTagName("root")->item(0)->textContent;

may also work

ps, i have no idea what all the downvotes are about, but i didnt read the comments either


问:
How can I change locale programmatically with Swift
I am making ios app on XCODE 6.3 by Swift.
And my app will have the choose language function like the image below

I already have storyboard for my local language.
But i can't find out how to change the localization programmatically off the app by the button.

Anyone know how to do it

答:
Jeremy's answer (here) works well on Swift 4 too (I just tested with a simple app and I changed language used in initial view controller).

Here is the Swift version of the same piece of code (for some reasons, my teammates prefer Swift-only than mixed with Objective-C, so I translated it):

```<code>import UIKit

private var kBundleKey: UInt8 = 0

class BundleEx: Bundle {

    override func localizedString(forKey key: String, value: String?, table tableName: String?) -> String {
        if let bundle = objc_getAssociatedObject(self, &kBundleKey) {
            return (bundle as! Bundle).localizedString(forKey: key, value: value, table: tableName)
        }
        return super.localizedString(forKey: key, value: value, table: tableName)
    }

}

extension Bundle {

    static let once: Void = {
        object_setClass(Bundle.main, type(of: BundleEx()))
    }()

    class func setLanguage(_ language: String?) {
        Bundle.once
        let isLanguageRTL = Bundle.isLanguageRTL(language)
        if (isLanguageRTL) {
            UIView.appearance().semanticContentAttribute = .forceRightToLeft
        } else {
            UIView.appearance().semanticContentAttribute = .forceLeftToRight
        }
        UserDefaults.standard.set(isLanguageRTL, forKey: "AppleTextDirection")
        UserDefaults.standard.set(isLanguageRTL, forKey: "NSForceRightToLeftWritingDirection")
        UserDefaults.standard.synchronize()

        let value = (language != nil ? Bundle.init(path: (Bundle.main.path(forResource: language, ofType: "lproj"))!) : nil)
        objc_setAssociatedObject(Bundle.main, &kBundleKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    class func isLanguageRTL(_ languageCode: String?) -> Bool {
        return (languageCode != nil && Locale.characterDirection(forLanguage: languageCode!) == .rightToLeft)
    }

}
</code>```

Body:
Jeremy's answer (here) works well on Swift 4 too (I just tested with a simple app and I changed language used in initial view controller).

Here is the Swift version of the same piece of code (for some reasons, my teammates prefer Swift-only than mixed with Objective-C, so I translated it):

import UIKit

private var kBundleKey: UInt8 = 0

class BundleEx: Bundle {

    override func localizedString(forKey key: String, value: String?, table tableName: String?) -> String {
        if let bundle = objc_getAssociatedObject(self, &kBundleKey) {
            return (bundle as! Bundle).localizedString(forKey: key, value: value, table: tableName)
        }
        return super.localizedString(forKey: key, value: value, table: tableName)
    }

}

extension Bundle {

    static let once: Void = {
        object_setClass(Bundle.main, type(of: BundleEx()))
    }()

    class func setLanguage(_ language: String?) {
        Bundle.once
        let isLanguageRTL = Bundle.isLanguageRTL(language)
        if (isLanguageRTL) {
            UIView.appearance().semanticContentAttribute = .forceRightToLeft
        } else {
            UIView.appearance().semanticContentAttribute = .forceLeftToRight
        }
        UserDefaults.standard.set(isLanguageRTL, forKey: "AppleTextDirection")
        UserDefaults.standard.set(isLanguageRTL, forKey: "NSForceRightToLeftWritingDirection")
        UserDefaults.standard.synchronize()

        let value = (language != nil ? Bundle.init(path: (Bundle.main.path(forResource: language, ofType: "lproj"))!) : nil)
        objc_setAssociatedObject(Bundle.main, &kBundleKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    class func isLanguageRTL(_ languageCode: String?) -> Bool {
        return (languageCode != nil && Locale.characterDirection(forLanguage: languageCode!) == .rightToLeft)
    }

}


答:
your code

```<code>var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0; // initialized here
var text = "";
for (;cars[i];) {
    text += cars[i] + "<br>";
    i++; // it will handle increment
}
document.getElementById("demo").innerHTML = text;
</code>```

is same as

```<code>for (var i=0;cars[i];i++) {
    text += cars[i] + "<br>";
}
</code>```

As in your code you have initialized var i and incremented within loop.

Title: Why are these semicolumns in this for loop?

Body:
your code

var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0; // initialized here
var text = "";
for (;cars[i];) {
    text += cars[i] + "<br>";
    i++; // it will handle increment
}
document.getElementById("demo").innerHTML = text;

is same as

for (var i=0;cars[i];i++) {
    text += cars[i] + "<br>";
}

As in your code you have initialized var i and incremented within loop.


问:
iOS app crashes upon opening when switching rotation views
I am trying to develop an app in XCode that will switch to a new view upon rotation.

Here is the code for view1controller.h:

```<code>#import UIKit/UIKit.h

@interface TestViewController : UIViewController {}

IBOutlet UIView *portrait;
IBOutlet UIView *landscape;

@property(nonatomic,retain) UIView *portrait;
@property(nonatomic,retain) UIView *landscape;

@end
</code>```

and here is the code for view1controller.m:

```<code>#import "view1controller.h"

@implementation TestViewController

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight)))
    {
        self.view = landscape;
    } else if (((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))) {
        self.view = portrait;
    }

    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

@synthesize portrait,landscape;

@end
</code>```

Anyway so the app opens but it crashes upon opening.

答:
I would do the following:

```<code>if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight)))
{
    [portrait removeFromSuperview];
    [self.view addSubview:landscape];
} else if (((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))) {
    [landscape removeFromSuperview];
    [self.view addSubview:portrait];
}
</code>```

Hope this helps!

Body:
I am trying to develop an app in XCode that will switch to a new view upon rotation.

Here is the code for view1controller.h:

#import UIKit/UIKit.h

@interface TestViewController : UIViewController {}

IBOutlet UIView *portrait;
IBOutlet UIView *landscape;

@property(nonatomic,retain) UIView *portrait;
@property(nonatomic,retain) UIView *landscape;

@end

and here is the code for view1controller.m:

#import "view1controller.h"

@implementation TestViewController

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight)))
    {
        self.view = landscape;
    } else if (((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))) {
        self.view = portrait;
    }

    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

@synthesize portrait,landscape;

@end

Anyway so the app opens but it crashes upon opening.

Body:
I would do the following:

if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight)))
{
    [portrait removeFromSuperview];
    [self.view addSubview:landscape];
} else if (((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))) {
    [landscape removeFromSuperview];
    [self.view addSubview:portrait];
}

Hope this helps!


问:
FIX Protocol with Ruby (and Rails)
Trying to use FIX Protocol (FIX4.4) to get stock market prices using Ruby. I'd like it to be on Rails too but simplifying things first.

I have the following code:

```<code>host_name = TCPSocket.gethostbyname(ADDRESS) # Not needed but checking resolves to IPa ddress
something = TCPSocket.new(ADDRESS, PORT)
</code>```

However I am getting:

```<code><#to_s method raised exception: wrong number of arguments (given 1, expected 2..3)>
</code>```

As the value of 'something'. Is there anyone that can give me a clue as to what is going on?

Thanks in advance...

答: I think your quickest / cheapest / easiest (already tested etc) solution if you want a FIX engine is to use QuickFIXJ to connect to your FIX counterparties and to work your FIX messaging layer. If you're not using middleware (I like Apache Geode since it's now open source. You could integrate with Ruby via the REST interface) then you can persist the FIX layer direct to your DB, and use Ruby on Rails to read it back to your UI layer. The DB needs to keep up with the market. If you've got a fast market with many updates per second you may find the DB falling behind: market makers all use RV, Gemfire, MQ etc. before persistence to their databases.</p>

Title: FIX Protocol with Ruby (and Rails)

Body:
Trying to use FIX Protocol (FIX4.4) to get stock market prices using Ruby. I'd like it to be on Rails too but simplifying things first.

I have the following code:

host_name = TCPSocket.gethostbyname(ADDRESS) # Not needed but checking resolves to IPa ddress
something = TCPSocket.new(ADDRESS, PORT)

However I am getting:

<#to_s method raised exception: wrong number of arguments (given 1, expected 2..3)>

As the value of 'something'. Is there anyone that can give me a clue as to what is going on?

Thanks in advance...


问:
SpringBoot external jar not load
i have a java project with spring boot and I need to load application.properties and dependency jar from external folder.

I tested by using the application.properties in the classpath, and the loader.path property work correctly.

When I use external properties file (I'm sure they're used) the loader.path not work correctly and the result is ClassNotFound because the jars are not loaded.

Also when i launch the application with **-Dloader.path=**xxx it's work correctly.

How can I solve the problem using external properties and jar?

答:
Here is the document

You need to make sure the load order of different property files.

You need to make sure the loader.path points to the right path. I mean, relative path or absolute path? You'd better print it out.

Title: SpringBoot external jar not load


问:
Errors with smooth scrolling and active class
hey someone did have problems with smooth scrolling and dynamic active classes? it shows me problems on this website:
https://dkapexhiu.github.io/brooklyn-outdoor-film-festival/
and the script is here:
https://github.com/dkapexhiu/brooklyn-outdoor-film-festival/blob/master/js/script.js
please navigate to some sections to see some errors on scrolling</p>

答:
For Scrolling smooth add this </p>

```<code>$('classname').click(function(event){
    event.preventDefault();
    var hlink = $(this).attr("href");
    $("body,html").animate({
    scrollTop: $(hlink).offset().top
    },500);
});
</code>```

Body:
For Scrolling smooth add this

$('classname').click(function(event){
    event.preventDefault();
    var hlink = $(this).attr("href");
    $("body,html").animate({
    scrollTop: $(hlink).offset().top
    },500);
});


问:
Access Javascript Object Key with special symbol
```<code>var obj = {
a?: "abc"
}
</code>```

Want to access Key Which is Not in a valid format.

Giving me Error.

I'm accessing it like this obj.a.

and this is throwing an error.

const obj = { a?: 'aaa' }
console.log(obj.a)```

答: The key should be a simple string in JavaScript, so if you change from a? to a, it should work. </p>

Body:
var obj = {
a?: "abc"
}

Want to access Key Which is Not in a valid format.

Giving me Error.

I'm accessing it like this obj.a.

and this is throwing an error.

const obj = { a?: 'aaa' }
console.log(obj.a)


问:
Get max score and the fields in the max score row in MySQL 5.7
```<code>| id | uid  | score   | date    |
————————————————————————————————
| 1  | aaa  | 10      | 2017.7.7|

| 2  | bbb  | 5       | 2017.7.7|

| 3  | aaa  | 15      | 2017.7.7|

| 4  | bbb  | 20      | 2017.7.8|
</code>```

I want to get everyone’s max score and every row should include all fields like id and date.

```<code>| id | uid | score | date    |
—————————————————————————————
| 4  | bbb | 20    | 2017.7.8|

| 3  | aaa | 15    | 2017.7.7|
</code>```

Select max(score) as score, id, date, uid from data group by uid order by score desc

I can use this sql to get what I want in MySQL before v5.7 but you know after MySQL 5.7 there is a sql_mode ONLY_FULL_GROUP_BY. So I can’t get the result as before. I see there are some answers tell me to disable the mode. But I want to know if there are any sql can do this as well as I don’t disable the mode.

答:
You can disable the mode with following query:

```<code>mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
</code>```

Also, your query will only  show max score of uid but not it's relevant id and date.

```<code>Select max(score) as score, id, date, uid
from data
where (uid,score) in (select uid,max(score)
                      from data
                      group by uid
                     )
group by uid
order by score desc
</code>```

Body:
| id | uid  | score   | date    |
————————————————————————————————
| 1  | aaa  | 10      | 2017.7.7|

| 2  | bbb  | 5       | 2017.7.7|

| 3  | aaa  | 15      | 2017.7.7|

| 4  | bbb  | 20      | 2017.7.8|

I want to get everyone’s max score and every row should include all fields like id and date.

| id | uid | score | date    |
—————————————————————————————
| 4  | bbb | 20    | 2017.7.8|

| 3  | aaa | 15    | 2017.7.7|

Select max(score) as score, id, date, uid from data group by uid order by score desc

I can use this sql to get what I want in MySQL before v5.7 but you know after MySQL 5.7 there is a sql_mode ONLY_FULL_GROUP_BY. So I can’t get the result as before. I see there are some answers tell me to disable the mode. But I want to know if there are any sql can do this as well as I don’t disable the mode.

Body:
You can disable the mode with following query:

mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

Also, your query will only  show max score of uid but not it's relevant id and date.

Select max(score) as score, id, date, uid
from data
where (uid,score) in (select uid,max(score)
                      from data
                      group by uid
                     )
group by uid
order by score desc


问:
Find XPath attribute name contains specific string
I have <form data-v-4db188a6=""> tag.
I need find only form tag contains 'data' in the attribute name not attribute value!
.//form[contains(@prop, 'data')] not work.
Is it even possible?

答:
Short xpath expression:

```<code>//form/@*[contains(name(), 'data')]
</code>```

Body:
Short xpath expression:

//form/@*[contains(name(), 'data')]


问:
Correct error or transform code to recursive function to evaluate matrix
I need a function that separates all the "islands" or regions of a matrix that are formed by 1s. In my example it works correctly, but there are some "special" cases where it fails (as in the example case).

How can I correct this error? or transform this function into a recursive function. Let the for travel through the matrix and in the position that is a 1, call the recursive function and evaluate all the points around it.

var matrix = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 1, 1, 1, 1, 0, 0, 0],
    [1, 1, 0, 1, 0, 0, 0, 1, 0, 0],
    [1, 0, 0, 1, 0, 0, 0, 1, 0, 0],
    [0, 0, 1, 1, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 1, 0, 0, 0, 1, 1, 0],
    [0, 1, 0, 1, 0, 0, 0, 1, 1, 1],
    [0, 1, 0, 1, 1, 0, 0, 1, 1, 0],
    [0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];

var contFilas = matrix.length;
var contColumnas = matrix[0].length;
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var sz = 20;
var regions = [];
var regionCollection = [];

canvas.width = sz * contColumnas;
canvas.height = sz * contColumnas;
ctx.fillStyle = "silver";
ctx.fillRect(0, 0, canvas.width, canvas.height);

for (var y = 0; y < contFilas; y++) {
    var regionline = [];
    regions.push(regionline);

    for (var x = 0; x < contColumnas; x++) {
        var pixelRegion = 0;
        regionline[x] = 0;

        if (matrix[y][x] === 1) {
            // check previous row
            if (y) {
                if (matrix[y - 1][x]) {
                    pixelRegion = regions[y - 1][x];
                } else if (x && matrix[y - 1][x - 1]) {
                    pixelRegion = regions[y - 1][x - 1];
                } else if (x + 1 < contColumnas && matrix[y - 1][x + 1]) {
                    pixelRegion = regions[y - 1][x + 1];
                }
            }

            // check current row
            if (x && matrix[y][x - 1]) {
                pixelRegion = regions[y][x - 1];
            }

            // if not connected, start a new region
            if (!pixelRegion) {
                regionCollection.push([]);
                pixelRegion = regionCollection.length;
            }
            // remember region
            regionline[x] = pixelRegion;
            regionCollection[pixelRegion - 1].push([x, y]);

            // paint it
            ctx.fillStyle = "black";
            ctx.fillRect(x * sz + 1, y * sz + 1, sz - 2, sz - 2);
        }

        ctx.fillStyle = "white";
        ctx.fillText(pixelRegion, x * sz + 8, y * sz + 13);

    }
}
document.querySelector("#result").innerHTML = JSON.stringify(regionCollection);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>getUserMedia</title>
</head>
<body>
 <canvas></canvas>
 <div id="result"></div>
</body>
</html></code>```

In the example, region 2 and 3 must be only one (region 2). That is, there will be 2 different regions. What is my error in the code? How can I correct it?

答:
I think your problem is you're trying to do this in one pass of the array, which is not really possible (depending on what exactly you count as "one pass").

The simplest algorithm is probably to loop through the array and where you see a 1 perform a flood-fill operation. Any pixel hit by the flood fill would be stored in a region and then ignored by the rest of your loop. Flood fill is computationally fairly slow, but it's well understood and there is a lot of code out there for it.

Given you already have this code, though, I expect you'll end up with a faster solution just by taking the regionCollection object you have and checking which regions touch. If any do, combine them. It will be less readable and probably more code than using flood-fills though, so it depends what you want to optimise for.

Body:
I need a function that separates all the "islands" or regions of a matrix that are formed by 1s. In my example it works correctly, but there are some "special" cases where it fails (as in the example case).

How can I correct this error? or transform this function into a recursive function. Let the for travel through the matrix and in the position that is a 1, call the recursive function and evaluate all the points around it.

var matrix = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 1, 1, 1, 1, 0, 0, 0],
    [1, 1, 0, 1, 0, 0, 0, 1, 0, 0],
    [1, 0, 0, 1, 0, 0, 0, 1, 0, 0],
    [0, 0, 1, 1, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 1, 0, 0, 0, 1, 1, 0],
    [0, 1, 0, 1, 0, 0, 0, 1, 1, 1],
    [0, 1, 0, 1, 1, 0, 0, 1, 1, 0],
    [0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];

var contFilas = matrix.length;
var contColumnas = matrix[0].length;
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");
var sz = 20;
var regions = [];
var regionCollection = [];

canvas.width = sz * contColumnas;
canvas.height = sz * contColumnas;
ctx.fillStyle = "silver";
ctx.fillRect(0, 0, canvas.width, canvas.height);

for (var y = 0; y < contFilas; y++) {
    var regionline = [];
    regions.push(regionline);

    for (var x = 0; x < contColumnas; x++) {
        var pixelRegion = 0;
        regionline[x] = 0;

        if (matrix[y][x] === 1) {
            // check previous row
            if (y) {
                if (matrix[y - 1][x]) {
                    pixelRegion = regions[y - 1][x];
                } else if (x && matrix[y - 1][x - 1]) {
                    pixelRegion = regions[y - 1][x - 1];
                } else if (x + 1 < contColumnas && matrix[y - 1][x + 1]) {
                    pixelRegion = regions[y - 1][x + 1];
                }
            }

            // check current row
            if (x && matrix[y][x - 1]) {
                pixelRegion = regions[y][x - 1];
            }

            // if not connected, start a new region
            if (!pixelRegion) {
                regionCollection.push([]);
                pixelRegion = regionCollection.length;
            }
            // remember region
            regionline[x] = pixelRegion;
            regionCollection[pixelRegion - 1].push([x, y]);

            // paint it
            ctx.fillStyle = "black";
            ctx.fillRect(x * sz + 1, y * sz + 1, sz - 2, sz - 2);
        }

        ctx.fillStyle = "white";
        ctx.fillText(pixelRegion, x * sz + 8, y * sz + 13);

    }
}
document.querySelector("#result").innerHTML = JSON.stringify(regionCollection);

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>getUserMedia</title>

 <canvas></canvas>

In the example, region 2 and 3 must be only one (region 2). That is, there will be 2 different regions. What is my error in the code? How can I correct it?


问:
nginx : Its Multithreaded but uses multiple processes?
I'm trying to understand what makes Nginx so fast, and I have a few questions.

As I understand it, Apache either spawns a new process to serve each request OR spawns a new thread to serve each request. Since each new thread shares virtual address space the memory usage keeps climbs if there are a number of concurrent requests coming in.

Nginx solves this by having just one listening process(Master), with a single execution thread AND 2 or 3(number is configurable) worker processes. This Master process/thread is running an event loop. Effectively waiting for any incoming request. When a request comes in it gives that request to one of the worker processes.

Please correct me if my above understanding is not correct

If the above is correct, then I have a few questions:

Isn't the worker process going to spawn multiple threads and going to run into the same problem as apache ?

Or is nginx fast because its event based architecture uses nonblocking-IO underneath it all. Maybe the worker process spawns threads which do only non-blocking-IO, is that it ?

What "exactly" is "event based architecture", can someone really simplify it, for soemone like me to understand. Does it just pertain to non-blocking-io or something else as well ?

I got a reference of c10k, I am trying to go through it, but I don't think its about event based arch. it seems more for nonblocking IO.

答:
It's not very complicated from a conceptual point of view. I'll try to be clear but I have to do some simplification.

The event based servers (like nginx and lighttpd) use a wrapper around an event monitoring system. For example. lighttpd uses libevent to abstract the more advanced high-speed event monitoring system (see libev also).

The server keeps track of all the non blocking connections it has (both writing and reading) using a simple state machine for each connection. The event monitoring system notifies the server process when there is new data available or when it can write more data. It's like a select() on steroids, if you know socket programming. The server process then simply sends the requested file using some advanced function like sendfile() where possible or turns the request to a CGI process using a socket for communication (this socket will be monitored with the event monitoring system like the other network connections.)

This link as a lot of great information about the internals of nginx, just in case. I hope it helps.


问:
Using SFINAE to detect if overloaded free-standing function exists at compile-time
Here is my unsuccessful attempt at detecting whether a free-standing function void set( T& , void (T::*Func)( const char* ) , const char* str ) exists for any class/struct T, in C++98/03.

```<code>#include <iostream>
#include <typeinfo>

struct Foo;
struct Bar;
struct Fuu;

void set( Foo& , void (Foo::*Func)( const char* ) , const char* str )
{
}

void set( Bar& , void (Bar::*Func)( const char* ) , const char* str )
{
}

template <typename T>
class setter_is_implemented
{
public:
    typedef void (*SetterFunction)( T& , void (T::*)( const char* ) , const char* );

    typedef char one;
    typedef long two;

    template <typename C> static one test( C c, SetterFunction = c ) ;
    template <typename C> static two test(...);

public:
    enum { value = sizeof( test<T>(&set)) == sizeof(one) };
};

int main()
{
    std::cout << setter_is_implemented<Foo>::value << std::endl;
    std::cout << setter_is_implemented<Bar>::value << std::endl;
    std::cout << setter_is_implemented<Fuu>::value << std::endl;
}
</code>```

GCC error message

```<code>Test.cpp:24:66: error: ‘c’ was not declared in this scope
     template <typename C> static one test( C c, SetterFunction = c ) ;
                                                                  ^
Test.cpp: In instantiation of ‘class setter_is_implemented<Foo>’:
Test.cpp:33:44:   required from here
Test.cpp:28:35: error: address of overloaded function with no contextual type information
     enum { value = sizeof( test<T>(&set)) == sizeof(one) };
                                   ^
Test.cpp: In instantiation of ‘class setter_is_implemented<Bar>’:
Test.cpp:34:44:   required from here
Test.cpp:28:35: error: address of overloaded function with no contextual type information
Test.cpp: In instantiation of ‘class setter_is_implemented<Fuu>’:
Test.cpp:35:44:   required from here
Test.cpp:28:35: error: address of overloaded function with no contextual type information
</code>```

答:
AFAIK, taking the address of an overloaded function happens before overload resolution, so SFINAE cannot work in that way. This is also harder because your function returns void (otherwise, one would just check the size of the result ). My C++03 metaprogramming is rusty, but this should work (live on coliru):

```<code>namespace setter_is_implemented_detail {
  struct dummy1 { char c[2]; };
  typedef char dummy2;

  dummy2 operator,(dummy1, dummy1);

  template<typename T> dummy1 set(T const&,...);

  template <typename T>
  struct impl
  {
    typedef void (T::*FT)( const char* );
    static T& x;

    enum { value = sizeof( set(x,static_cast<FT>(0),static_cast<const char*>(0)), dummy1() ) != sizeof(dummy2) };
  };
}

template <typename T>
struct setter_is_implemented: setter_is_implemented_detail::impl<T>{};
</code>```

note a few things:

set() needs to be found by ADL here (not a big deal, as far as I can tell from your problem description)(*)

the comma operator trick(**) is needed due to the void return type; in gcc, you can take the sizeof(void), so the code can be simplified there

this won't work for non object types (due to the static T&). It can be made to work though, if you need so...

(*) Note that this cannot work for every possible set() overload; this is true for any sfinae, even in c++17, set() must always be sfinae-friendly in order to work.

If you need to match sfinae-friendly set() overloads exactly, it's still possible to do it, but it's more complex; I'd do it in two phases: first you use the above code to find possible candidates, then you check the function pointer conversion, somewhat like you do in your original code ..

(**) This trick works because if set() has void return type (and hence exists) the comma is always interpreted as the built-in comma operator (see c++03[3.9.1/9]: "An expression of type void shall be used only as an expression statement (6.2), as an operand of a comma expression[...]") resulting in the right-most expression. Otherwise, the dummy set and comma operator are used.

Body:
Here is my unsuccessful attempt at detecting whether a free-standing function void set( T& , void (T::*Func)( const char* ) , const char* str ) exists for any class/struct T, in C++98/03.

#include <iostream>
#include <typeinfo>

struct Foo;
struct Bar;
struct Fuu;

void set( Foo& , void (Foo::*Func)( const char* ) , const char* str )
{
}

void set( Bar& , void (Bar::*Func)( const char* ) , const char* str )
{
}

template <typename T>
class setter_is_implemented
{
public:
    typedef void (*SetterFunction)( T& , void (T::*)( const char* ) , const char* );

    typedef char one;
    typedef long two;

    template <typename C> static one test( C c, SetterFunction = c ) ;
    template <typename C> static two test(...);

public:
    enum { value = sizeof( test<T>(&set)) == sizeof(one) };
};

int main()
{
    std::cout << setter_is_implemented<Foo>::value << std::endl;
    std::cout << setter_is_implemented<Bar>::value << std::endl;
    std::cout << setter_is_implemented<Fuu>::value << std::endl;
}

GCC error message

Test.cpp:24:66: error: ‘c’ was not declared in this scope
     template <typename C> static one test( C c, SetterFunction = c ) ;
                                                                  ^
Test.cpp: In instantiation of ‘class setter_is_implemented<Foo>’:
Test.cpp:33:44:   required from here
Test.cpp:28:35: error: address of overloaded function with no contextual type information
     enum { value = sizeof( test<T>(&set)) == sizeof(one) };
                                   ^
Test.cpp: In instantiation of ‘class setter_is_implemented<Bar>’:
Test.cpp:34:44:   required from here
Test.cpp:28:35: error: address of overloaded function with no contextual type information
Test.cpp: In instantiation of ‘class setter_is_implemented<Fuu>’:
Test.cpp:35:44:   required from here
Test.cpp:28:35: error: address of overloaded function with no contextual type information

Body:
AFAIK, taking the address of an overloaded function happens before overload resolution, so SFINAE cannot work in that way. This is also harder because your function returns void (otherwise, one would just check the size of the result ). My C++03 metaprogramming is rusty, but this should work (live on coliru):

namespace setter_is_implemented_detail {
  struct dummy1 { char c[2]; };
  typedef char dummy2;

  dummy2 operator,(dummy1, dummy1);

  template<typename T> dummy1 set(T const&,...);

  template <typename T>
  struct impl
  {
    typedef void (T::*FT)( const char* );
    static T& x;

    enum { value = sizeof( set(x,static_cast<FT>(0),static_cast<const char*>(0)), dummy1() ) != sizeof(dummy2) };
  };
}

template <typename T>
struct setter_is_implemented: setter_is_implemented_detail::impl<T>{};

note a few things:

set() needs to be found by ADL here (not a big deal, as far as I can tell from your problem description)(*)

the comma operator trick(**) is needed due to the void return type; in gcc, you can take the sizeof(void), so the code can be simplified there

this won't work for non object types (due to the static T&). It can be made to work though, if you need so...

(*) Note that this cannot work for every possible set() overload; this is true for any sfinae, even in c++17, set() must always be sfinae-friendly in order to work.

If you need to match sfinae-friendly set() overloads exactly, it's still possible to do it, but it's more complex; I'd do it in two phases: first you use the above code to find possible candidates, then you check the function pointer conversion, somewhat like you do in your original code ..

(**) This trick works because if set() has void return type (and hence exists) the comma is always interpreted as the built-in comma operator (see c++03[3.9.1/9]: "An expression of type void shall be used only as an expression statement (6.2), as an operand of a comma expression[...]") resulting in the right-most expression. Otherwise, the dummy set and comma operator are used.