问:
Angular Quickstart fails karma testing out of the box
The official Angular quickstart is not able to run karma tests after a clean install on Windows 10. I typed the following 4 commands and nothing else:

```<code>C:\projects\temp>git clone https://github.com/angular/quickstart.git
C:\projects\temp>cd C:\projects\temp\quickstart
C:\projects\temp\quickstart>npm install
...install logs omitted for brevity
C:\projects\temp\quickstart>npm start
...app launched successfully, but logs omitted for brevity
C:\projects\temp\quickstart>npm test
...Error shown in complete logs below
</code>```

The full error message resulting after the final command is as follows:

```<code>C:\projects\temp\quickstart>npm test

> angular-quickstart@1.0.0 pretest C:\projects\temp\quickstart
> npm run build

> angular-quickstart@1.0.0 build C:\projects\temp\quickstart
> tsc -p src/

> angular-quickstart@1.0.0 test C:\projects\temp\quickstart
> concurrently "npm run build:watch" "karma start karma.conf.js"

[0]
[0] > angular-quickstart@1.0.0 build:watch C:\projects\temp\quickstart
[0] > tsc -p src/ -w
[0]
[1] 01 06 2017 14:33:49.385:WARN [watcher]: Pattern "C:/projects/temp/quickstart/testing/**/*.js" does not match any file.
[1] 01 06 2017 14:33:49.406:WARN [watcher]: Pattern "C:/projects/temp/quickstart/testing/**/*.ts" does not match any file.
[1] 01 06 2017 14:33:49.407:WARN [watcher]: Pattern "C:/projects/temp/quickstart/testing/**/*.js.map" does not match any file.
[1] 01 06 2017 14:33:49.891:WARN [karma]: No captured browser, open http://localhost:9876/
[1] 01 06 2017 14:33:49.906:WARN [karma]: Port 9876 in use
[1] 01 06 2017 14:33:49.908:INFO [karma]: Karma v1.7.0 server started at http://0.0.0.0:9877/
[1] 01 06 2017 14:33:49.908:INFO [launcher]: Launching browser Chrome with unlimited concurrency
[1] 01 06 2017 14:33:49.958:INFO [launcher]: Starting browser Chrome
[1] 01 06 2017 14:33:51.821:INFO [watcher]: Changed file "C:/projects/temp/quickstart/src/app/app.component.js".
[1] 01 06 2017 14:33:51.843:INFO [watcher]: Changed file "C:/projects/temp/quickstart/src/app/app.component.spec.js".
[1] 01 06 2017 14:33:51.850:INFO [watcher]: Changed file "C:/projects/temp/quickstart/src/app/app.module.js".
[0] 2:33:51 PM - Compilation complete. Watching for file changes.
[1] 01 06 2017 14:33:51.873:INFO [watcher]: Changed file "C:/projects/temp/quickstart/src/main.js".
[1] 01 06 2017 14:33:51.965:INFO [Chrome 58.0.3029 (Windows 10 0.0.0)]: Connected on socket pXysNFDP8RC3agm8AAAA with id 9156960
[1] 01 06 2017 14:33:52.077:INFO [karma]: Delaying execution, these browsers are not ready: Chrome 58.0.3029 (Windows 10 0.0.0)
</code>```

What needs to change in order for npm test to succeed out of the box on Windows 10?

答:
The Angular quickstart project has largely been superseded by the Angular CLI. I would suggest using the CLI it for any new projects as it not only gives you an initial framework for your application, but it will also generate the additional boilerplate needed as you extend your application.

Before installing Angular CLi, ensure you have an up to date version of Node (6.9.0 or higher) and NPM (3 or higher). Also there may be other prerequisites not listed in the documentation, to install on an Android system I found it also needed Python 2.7 and g++ installed.

Install with:

```<code>npm install -g @angular/cli
</code>```

To create a new project:

```<code>ng new PROJECT-NAME
cd PROJECT-NAME
ng serve
</code>```

ng new will take some time to complete as in addition to building the project structure it also does the npm install.

Run unit tests with ng test and end-to-end tests with ng e2e.
Both ng test and ng serve will run continuously watching for changes and rebuilding the affected code. You can even leave both running in separate windows if you wish.

ng generate BLUEPRINT will generate new code, blueprints include module, component, service, class, directive, enum, guard, interface, pipe
Other useful commands:. You may want to experiment with this a bit before you write a real app: by default each component or service goes into its own subdirectory and is added to the top level app module, but you can explicitly create modules to provide additional structure if you wish.

ng build: builds your application into the output path.

ng doc KEYWORD: opens angular documentation for that keyword.

ng eject: ejects the app and outputs webpack configuration

ng lint: lints the project

ng xi18n: extracts i18n messages from the project.

Body:
The official Angular quickstart is not able to run karma tests after a clean install on Windows 10. I typed the following 4 commands and nothing else:

C:\projects\temp>git clone https://github.com/angular/quickstart.git
C:\projects\temp>cd C:\projects\temp\quickstart
C:\projects\temp\quickstart>npm install
...install logs omitted for brevity
C:\projects\temp\quickstart>npm start
...app launched successfully, but logs omitted for brevity
C:\projects\temp\quickstart>npm test
...Error shown in complete logs below

The full error message resulting after the final command is as follows:

C:\projects\temp\quickstart>npm test

> angular-quickstart@1.0.0 pretest C:\projects\temp\quickstart
> npm run build

> angular-quickstart@1.0.0 build C:\projects\temp\quickstart
> tsc -p src/

> angular-quickstart@1.0.0 test C:\projects\temp\quickstart
> concurrently "npm run build:watch" "karma start karma.conf.js"

[0]
[0] > angular-quickstart@1.0.0 build:watch C:\projects\temp\quickstart
[0] > tsc -p src/ -w
[0]
[1] 01 06 2017 14:33:49.385:WARN [watcher]: Pattern "C:/projects/temp/quickstart/testing/**/*.js" does not match any file.
[1] 01 06 2017 14:33:49.406:WARN [watcher]: Pattern "C:/projects/temp/quickstart/testing/**/*.ts" does not match any file.
[1] 01 06 2017 14:33:49.407:WARN [watcher]: Pattern "C:/projects/temp/quickstart/testing/**/*.js.map" does not match any file.
[1] 01 06 2017 14:33:49.891:WARN [karma]: No captured browser, open http://localhost:9876/
[1] 01 06 2017 14:33:49.906:WARN [karma]: Port 9876 in use
[1] 01 06 2017 14:33:49.908:INFO [karma]: Karma v1.7.0 server started at http://0.0.0.0:9877/
[1] 01 06 2017 14:33:49.908:INFO [launcher]: Launching browser Chrome with unlimited concurrency
[1] 01 06 2017 14:33:49.958:INFO [launcher]: Starting browser Chrome
[1] 01 06 2017 14:33:51.821:INFO [watcher]: Changed file "C:/projects/temp/quickstart/src/app/app.component.js".
[1] 01 06 2017 14:33:51.843:INFO [watcher]: Changed file "C:/projects/temp/quickstart/src/app/app.component.spec.js".
[1] 01 06 2017 14:33:51.850:INFO [watcher]: Changed file "C:/projects/temp/quickstart/src/app/app.module.js".
[0] 2:33:51 PM - Compilation complete. Watching for file changes.
[1] 01 06 2017 14:33:51.873:INFO [watcher]: Changed file "C:/projects/temp/quickstart/src/main.js".
[1] 01 06 2017 14:33:51.965:INFO [Chrome 58.0.3029 (Windows 10 0.0.0)]: Connected on socket pXysNFDP8RC3agm8AAAA with id 9156960
[1] 01 06 2017 14:33:52.077:INFO [karma]: Delaying execution, these browsers are not ready: Chrome 58.0.3029 (Windows 10 0.0.0)

What needs to change in order for npm test to succeed out of the box on Windows 10?

Body:
The Angular quickstart project has largely been superseded by the Angular CLI. I would suggest using the CLI it for any new projects as it not only gives you an initial framework for your application, but it will also generate the additional boilerplate needed as you extend your application.

Before installing Angular CLi, ensure you have an up to date version of Node (6.9.0 or higher) and NPM (3 or higher). Also there may be other prerequisites not listed in the documentation, to install on an Android system I found it also needed Python 2.7 and g++ installed.

Install with:

npm install -g @angular/cli

To create a new project:

ng new PROJECT-NAME
cd PROJECT-NAME
ng serve

ng new will take some time to complete as in addition to building the project structure it also does the npm install.

Run unit tests with ng test and end-to-end tests with ng e2e.
Both ng test and ng serve will run continuously watching for changes and rebuilding the affected code. You can even leave both running in separate windows if you wish.

ng generate BLUEPRINT will generate new code, blueprints include module, component, service, class, directive, enum, guard, interface, pipe
Other useful commands:. You may want to experiment with this a bit before you write a real app: by default each component or service goes into its own subdirectory and is added to the top level app module, but you can explicitly create modules to provide additional structure if you wish.

ng build: builds your application into the output path.

ng doc KEYWORD: opens angular documentation for that keyword.

ng eject: ejects the app and outputs webpack configuration

ng lint: lints the project

ng xi18n: extracts i18n messages from the project.


来源: stackexchange

问:
how to redirect URL containing query string and random numbers in .htaccess
When customers cancel a transaction on my site, they get redirected to the WooCommerce cart page with a query string containing randomly generated numbers at the end.

Example

```<code>https://www.example.com/cart/?woo-paypal-cancel=true&token=EC-5474842406066680S
</code>```

(I need this redirect due to a plugin conflict between WP Rocket cache with CDN activated and WooCommerce. Long story.)

I'm wondering what exactly I would put in my .htaccess file to get it to redirect to

```<code>https://www.example.com/cart/
</code>```

I've tried a number of variations I found on multiple pages here on Stackpath, but it wasn't redirecting. Obviously I'm missing something so I'm turning to the gurus.

Would be very grateful for your help.

答:
To redirect /cart/?woo-paypal-cancel=true&token=<anything> to /cart/ you can try something like the following near the top of your .htaccess file (using mod_rewrite):

```<code>RewriteEngine On
RewriteCond %{QUERY_STRING} ^woo-paypal-cancel=true&token=
RewriteRule ^cart/$ /cart/? [R,L]
</code>```

The ? on the end of the RewriteRule substitution strips the query string from the request.

This is a temporary (302) redirect.

ContentLicense: CC BY-SA 3.0

Body:
When customers cancel a transaction on my site, they get redirected to the WooCommerce cart page with a query string containing randomly generated numbers at the end.

Example

https://www.example.com/cart/?woo-paypal-cancel=true&token=EC-5474842406066680S

(I need this redirect due to a plugin conflict between WP Rocket cache with CDN activated and WooCommerce. Long story.)

I'm wondering what exactly I would put in my .htaccess file to get it to redirect to

https://www.example.com/cart/

I've tried a number of variations I found on multiple pages here on Stackpath, but it wasn't redirecting. Obviously I'm missing something so I'm turning to the gurus.

Would be very grateful for your help.

Body:
To redirect /cart/?woo-paypal-cancel=true&token=<anything> to /cart/ you can try something like the following near the top of your .htaccess file (using mod_rewrite):

RewriteEngine On
RewriteCond %{QUERY_STRING} ^woo-paypal-cancel=true&token=
RewriteRule ^cart/$ /cart/? [R,L]

The ? on the end of the RewriteRule substitution strips the query string from the request.

This is a temporary (302) redirect.


问:
Ionic 2: How to handle the hardware back button which checks confirmation of Exit in app
I am facing an issue how to handle the default mobile's back button which checks the confirmation while exiting from the application, if I pressed the back button there should invoke some handler which shows pop-up, for confirm exiting.
OR there is any method call registerBackButtonAction()? or is it so how to use it in IONIC 2,?
Please help me out. Thanks in Advance.

答:
Ionic latest version 3.xx

app.component.ts file:

```<code>import { Platform, Nav, Config, ToastController } from 'ionic-angular';

constructor(public toastCtrl: ToastController, public platform: Platform) {
    platform.ready().then(() => {
        //back button handle
        //Registration of push in Android and Windows Phone
        var lastTimeBackPress = 0;
        var timePeriodToExit  = 2000;

        platform.registerBackButtonAction(() => {
            // get current active page
            let view = this.nav.getActive();
            if (view.component.name == "TabsPage") {
                //Double check to exit app
                if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
                    this.platform.exitApp(); //Exit from app
                } else {
                    let toast = this.toastCtrl.create({
                        message:  'Press back again to exit App?',
                        duration: 3000,
                        position: 'bottom'
                    });
                    toast.present();
                    lastTimeBackPress = new Date().getTime();
                }
            } else {
                // go to previous page
                this.nav.pop({});
            }
        });
    });
}
</code>```

Body:
Ionic latest version 3.xx

app.component.ts file:

import { Platform, Nav, Config, ToastController } from 'ionic-angular';

constructor(public toastCtrl: ToastController, public platform: Platform) {
    platform.ready().then(() => {
        //back button handle
        //Registration of push in Android and Windows Phone
        var lastTimeBackPress = 0;
        var timePeriodToExit  = 2000;

        platform.registerBackButtonAction(() => {
            // get current active page
            let view = this.nav.getActive();
            if (view.component.name == "TabsPage") {
                //Double check to exit app
                if (new Date().getTime() - lastTimeBackPress < timePeriodToExit) {
                    this.platform.exitApp(); //Exit from app
                } else {
                    let toast = this.toastCtrl.create({
                        message:  'Press back again to exit App?',
                        duration: 3000,
                        position: 'bottom'
                    });
                    toast.present();
                    lastTimeBackPress = new Date().getTime();
                }
            } else {
                // go to previous page
                this.nav.pop({});
            }
        });
    });
}


问:
How to yield the elements in an iterator within a new iterator?
I need an iterator over all leaves in my JSON object. So I wrote this function

```<code>rec = {'a': {'b': [{'c': {'d': [{'e': 'x1','f': 'x2'}],'g': 'x3'}}],'h': 'x4','i': 'x5','j': [{'k': 'x6'}],'l': [{'m': {'n': 'x7'}}]}}

def yield_leaves(rec, lbl = ''):
  if isinstance(rec, dict):
    for key, value in rec.items():
        for to_yield in yield_leaves(value, key):
            yield to_yield
  if isinstance(rec, list):
    for value in rec:
        for to_yield in yield_leaves(value, lbl):
            yield to_yield
  if isinstance(rec, (int, str)):
    for entry in rec.split():
        yield entry, lbl

print(list(yield_leaves(rec)))
>>> [('x5', 'i'), ('x4', 'h'), ('x1', 'e'), ('x2', 'f'), ('x3', 'g'), ('x6', 'k'), ('x7', 'n')]
</code>```

But I think some code is redundant. The following line

```<code>for to_yield in yield_leaves(value, key):
        yield to_yield
</code>```

It iterates over an iterator and returns the values as part of an iterator.

Do you know a more efficient way to code this?

答:
Your last section

```<code>if isinstance(rec, (int, str)):
    for entry in rec.split():
        yield entry, lbl
</code>```

is a bit strange. It will crash if rec is an int, since integers don't have a .split method. And none of your strings contain whitespace, so calling .split on them will just return a list containing a single item: the original string. I guess your real data may contain multi-word strings that you want to split, but if so, you really need to handle that separately from ints.

So assuming that you don't have multi-word values that you want to split, I've simplified your code a little. As you can see, I've only retained the dict and list tests, Since the data is decoded from JSON, any other rec types will be some sort of scalar: int, str, bool, or None, (unless you've created a custom decode), and we can handle all those scalar types identically.

```<code>rec = {
    'a': {
        'b': [
            {
                'c': {
                    'd': [{'e': 'x1', 'f': 'x2'}],
                    'g': 'x3'
                }
            }
        ],
        'h': 'x4',
        'i': 'x5',
        'j': [{'k': 'x6'}],
        'l': [{'m': {'n': 'x7'}}]
    }
}

def yield_leaves(rec, lbl=''):
    if isinstance(rec, dict):
        for key, value in rec.items():
            yield from yield_leaves(value, key)
    elif isinstance(rec, list):
        for value in rec:
            yield from yield_leaves(value, lbl)
    else:
        yield rec, lbl

print(list(yield_leaves(rec)))
</code>```

output

```<code>[('x1', 'e'), ('x2', 'f'), ('x3', 'g'), ('x4', 'h'), ('x5', 'i'), ('x6', 'k'), ('x7', 'n')]
</code>```

This code uses the Python 3 feature yield from; if you're not using Python 3, you should be. :)

Body:
I need an iterator over all leaves in my JSON object. So I wrote this function

rec = {'a': {'b': [{'c': {'d': [{'e': 'x1','f': 'x2'}],'g': 'x3'}}],'h': 'x4','i': 'x5','j': [{'k': 'x6'}],'l': [{'m': {'n': 'x7'}}]}}

def yield_leaves(rec, lbl = ''):
  if isinstance(rec, dict):
    for key, value in rec.items():
        for to_yield in yield_leaves(value, key):
            yield to_yield
  if isinstance(rec, list):
    for value in rec:
        for to_yield in yield_leaves(value, lbl):
            yield to_yield
  if isinstance(rec, (int, str)):
    for entry in rec.split():
        yield entry, lbl

print(list(yield_leaves(rec)))
>>> [('x5', 'i'), ('x4', 'h'), ('x1', 'e'), ('x2', 'f'), ('x3', 'g'), ('x6', 'k'), ('x7', 'n')]

But I think some code is redundant. The following line

for to_yield in yield_leaves(value, key):
        yield to_yield

It iterates over an iterator and returns the values as part of an iterator.

Do you know a more efficient way to code this?

Body:
Your last section

if isinstance(rec, (int, str)):
    for entry in rec.split():
        yield entry, lbl

is a bit strange. It will crash if rec is an int, since integers don't have a .split method. And none of your strings contain whitespace, so calling .split on them will just return a list containing a single item: the original string. I guess your real data may contain multi-word strings that you want to split, but if so, you really need to handle that separately from ints.

So assuming that you don't have multi-word values that you want to split, I've simplified your code a little. As you can see, I've only retained the dict and list tests, Since the data is decoded from JSON, any other rec types will be some sort of scalar: int, str, bool, or None, (unless you've created a custom decode), and we can handle all those scalar types identically.

rec = {
    'a': {
        'b': [
            {
                'c': {
                    'd': [{'e': 'x1', 'f': 'x2'}],
                    'g': 'x3'
                }
            }
        ],
        'h': 'x4',
        'i': 'x5',
        'j': [{'k': 'x6'}],
        'l': [{'m': {'n': 'x7'}}]
    }
}

def yield_leaves(rec, lbl=''):
    if isinstance(rec, dict):
        for key, value in rec.items():
            yield from yield_leaves(value, key)
    elif isinstance(rec, list):
        for value in rec:
            yield from yield_leaves(value, lbl)
    else:
        yield rec, lbl

print(list(yield_leaves(rec)))

output

[('x1', 'e'), ('x2', 'f'), ('x3', 'g'), ('x4', 'h'), ('x5', 'i'), ('x6', 'k'), ('x7', 'n')]

This code uses the Python 3 feature yield from; if you're not using Python 3, you should be. :)


问:
sql statement to fetch data from the database of exactly 5 days past
I was working on something and I needed to query a record from the database that is exactly 5 days from now, but it did not work as expected.

I have tried something but it's just fetching record of from 5 days till now. All I wanted is the record of exactly 5 days past (or ago). Here is my code, please tell me want I am not doing right.

```<code>SELECT * FROM ts_user
WHERE user_registerdate >= DATE_SUB(CURDATE(), INTERVAL 5 day) AND user_registerdate <= CURDATE()
ORDER BY user_registerdate DESC;
</code>```

答:
If user_resgisterdate field from your database is DateTime
Try this

```<code>SELECT * FROM ts_user
WHERE Datediff(day,user_registerdate,getdate()) <= 5;
</code>```

Hope this helps

Body:
I was working on something and I needed to query a record from the database that is exactly 5 days from now, but it did not work as expected.

I have tried something but it's just fetching record of from 5 days till now. All I wanted is the record of exactly 5 days past (or ago). Here is my code, please tell me want I am not doing right.

SELECT * FROM ts_user
WHERE user_registerdate >= DATE_SUB(CURDATE(), INTERVAL 5 day) AND user_registerdate <= CURDATE()
ORDER BY user_registerdate DESC;

Body:
If user_resgisterdate field from your database is DateTime
Try this

SELECT * FROM ts_user
WHERE Datediff(day,user_registerdate,getdate()) <= 5;

Hope this helps


问:
Schema specified is not valid. Errors: The relationship 'Product_CreatedByUser' was not loaded because the type 'User' is not available
I have following code first models and I try to initialized database it giving me error mention below. One user can have multiple products so there is one to many relationship between user and product.

```<code>Schema specified is not valid. Errors: The relationship 'Models.Product_CreatedByUser' was not loaded because the type 'User' is not available.
</code>```

I am using code first approach, can any one help me with this.

User:

```<code>public class User
{
    public long UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}
</code>```

Product:

```<code>public class Product
    {
    public long ProductId { get; set; }
    public string ProductCode { get; set; }
    public string Name { get; set; }
    public DateTime CreatedDate { get; set; }
    public long CreatedBy { get; set; }
    public long ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }
    public bool IsDeleted { get; set; }
    [ForeignKey("CreatedBy")]
    public virtual User CreatedByUser { get; set; }
    [ForeignKey("ModifiedBy")]
    public virtual User ModifiedByUser { get; set; }
}
</code>```

答:
According to the model, Product has 2 many-to-one FK relationships to User - 1 through CreatedBy and 1 through ModifiedBy. However, the User class contains a single Products collection, while EF requires one or zero corresponding navigation property for each relationship. Also, it doesn't know to which of the current FK is supposed to map that collection, so it silently tries to create a 3rd relation :( Since the default mapping doesn't work for such scenarios, you need to use InverseProperty or fluent API to specify the mappings correctly.

For instance, the bidirectional mapping can be specified like this:

```<code>public class User
{
    public long UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [InverseProperty("CreatedByUser")]
    public virtual ICollection<Product> CreatedProducts { get; set; }
    [InverseProperty("ModifiedByUser")]
    public virtual ICollection<Product> ModifiedProducts { get; set; }
}
</code>```

Upate: While the above fixes the mapping issue, it introduces another issue known as multiple cascade paths, because by the default EF conventions cascade delete is on for one-to-many relationships. Since you need fluent configuration anyway to turn the cascade delete off for one or both relationships, you'd better remove ForeignKey and InverseProperty annotations and configure the whole thing fluently:

```<code>modelBuilder.Entity<Product>()
    .HasRequired(e => e.CreatedByUser)
    .WithMany(e => e.CreatedProducts)
    .HasForeignKey(e => e.CreatedBy)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Product>()
    .HasRequired(e => e.ModifiedByUser)
    .WithMany(e => e.ModifiedProducts)
    .HasForeignKey(e => e.ModifiedBy)
    .WillCascadeOnDelete(false);
</code>```

Body:
I have following code first models and I try to initialized database it giving me error mention below. One user can have multiple products so there is one to many relationship between user and product.

Schema specified is not valid. Errors: The relationship 'Models.Product_CreatedByUser' was not loaded because the type 'User' is not available.

I am using code first approach, can any one help me with this.

User:

public class User
{
    public long UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

Product:

public class Product
    {
    public long ProductId { get; set; }
    public string ProductCode { get; set; }
    public string Name { get; set; }
    public DateTime CreatedDate { get; set; }
    public long CreatedBy { get; set; }
    public long ModifiedBy { get; set; }
    public DateTime ModifiedDate { get; set; }
    public bool IsDeleted { get; set; }
    [ForeignKey("CreatedBy")]
    public virtual User CreatedByUser { get; set; }
    [ForeignKey("ModifiedBy")]
    public virtual User ModifiedByUser { get; set; }
}

Body:
According to the model, Product has 2 many-to-one FK relationships to User - 1 through CreatedBy and 1 through ModifiedBy. However, the User class contains a single Products collection, while EF requires one or zero corresponding navigation property for each relationship. Also, it doesn't know to which of the current FK is supposed to map that collection, so it silently tries to create a 3rd relation :( Since the default mapping doesn't work for such scenarios, you need to use InverseProperty or fluent API to specify the mappings correctly.

For instance, the bidirectional mapping can be specified like this:

public class User
{
    public long UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [InverseProperty("CreatedByUser")]
    public virtual ICollection<Product> CreatedProducts { get; set; }
    [InverseProperty("ModifiedByUser")]
    public virtual ICollection<Product> ModifiedProducts { get; set; }
}

Upate: While the above fixes the mapping issue, it introduces another issue known as multiple cascade paths, because by the default EF conventions cascade delete is on for one-to-many relationships. Since you need fluent configuration anyway to turn the cascade delete off for one or both relationships, you'd better remove ForeignKey and InverseProperty annotations and configure the whole thing fluently:

modelBuilder.Entity<Product>()
    .HasRequired(e => e.CreatedByUser)
    .WithMany(e => e.CreatedProducts)
    .HasForeignKey(e => e.CreatedBy)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Product>()
    .HasRequired(e => e.ModifiedByUser)
    .WithMany(e => e.ModifiedProducts)
    .HasForeignKey(e => e.ModifiedBy)
    .WillCascadeOnDelete(false);


问:
Send newrelic application name
I'm using newrelic java agent,
I'm sending informarion to newrelic insights from my java app.
how to send also newrelic application name (exist in newrelic.yml) so that
I can know which application is sending the information.</p>

答:
I open a discussion with newrelic support

https://discuss.newrelic.com/t/how-to-get-app-name-from-my-application/49366

Support answer:

The application name should automatically be included in all Transaction events from APM apps under the appName attribute. You can include additional custom attributes - such as the number of users - in Transaction events by calling the agent API as outlined here: https://docs.newrelic.com/docs/agents/manage-apm-agents/agent-data/collect-custom-attributes#enabling-custom.

For example, in Java:

```<code>NewRelic.addCustomParameter("numberOfUsers", numberOfUsers);
</code>```

Title: Send newrelic application name

Body:
I open a discussion with newrelic support

https://discuss.newrelic.com/t/how-to-get-app-name-from-my-application/49366

Support answer:

The application name should automatically be included in all Transaction events from APM apps under the appName attribute. You can include additional custom attributes - such as the number of users - in Transaction events by calling the agent API as outlined here: https://docs.newrelic.com/docs/agents/manage-apm-agents/agent-data/collect-custom-attributes#enabling-custom.

For example, in Java:

NewRelic.addCustomParameter("numberOfUsers", numberOfUsers);


问:
How to count every row from select
I want to extract the data from my table and I want to have this result:

```<code>1 Valore
2 Valore
3 Valore
4 Valore
</code>```

So I want to numeration every ROW from 1 to N.

This is my query but not works:

```<code>  SELECT COUNT(DISTINCT dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)) AS Count,
         dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) AS NAME
    FROM AA_V_PHR_CCD_ResultsObservation R INNER JOIN
         AA_V_PHR_CCD_ResultsObservationXLanguages RR   ON R.ID = RR.ID
   WHERE CodeSystem = '123456789'
GROUP BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)
</code>```

EDIT

My Database is Tsql

and this is my extract data:

```<code>1 Valore
1 Pippo
1 Pluto
</code>```

Instead of

```<code>1 Valore
2 Pippo
3 Pluto
</code>```

答:
This should do the job:</p>

```<code>SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS Count,
     dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) AS NAME
FROM AA_V_PHR_CCD_ResultsObservation R INNER JOIN
     AA_V_PHR_CCD_ResultsObservationXLanguages RR   ON R.ID = RR.ID
WHERE CodeSystem = '123456789'
GROUP BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)
</code>```

Title: How to count every row from select

Body:
I want to extract the data from my table and I want to have this result:

1 Valore
2 Valore
3 Valore
4 Valore

So I want to numeration every ROW from 1 to N.

This is my query but not works:

  SELECT COUNT(DISTINCT dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)) AS Count,
         dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) AS NAME
    FROM AA_V_PHR_CCD_ResultsObservation R INNER JOIN
         AA_V_PHR_CCD_ResultsObservationXLanguages RR   ON R.ID = RR.ID
   WHERE CodeSystem = '123456789'
GROUP BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)

EDIT

My Database is Tsql

and this is my extract data:

1 Valore
1 Pippo
1 Pluto

Instead of

1 Valore
2 Pippo
3 Pluto

Body:
This should do the job:

SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS Count,
     dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) AS NAME
FROM AA_V_PHR_CCD_ResultsObservation R INNER JOIN
     AA_V_PHR_CCD_ResultsObservationXLanguages RR   ON R.ID = RR.ID
WHERE CodeSystem = '123456789'
GROUP BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)


问:
autoloader conflicts, fail to open stream
I write autoloader in my controller file to load a class file. This load class in the services folder well. But it will cause this issue when load class not in services folder.

[2017-05-11 17:38:23] production.ERROR: exception 'ErrorException'
  with message 'include(/var/www/market/app/services/ProductDomain.php):
  failed to open stream: No such file or directory' in
  /var/www/market/app/controllers/CloudController.php:27

```<code>public function __construct()
{
    spl_autoload_register(function($classname) {
        include app_path() . '/services/' . $classname . '.php';
    });
}
</code>```

This may caused by confilct with other autoloader, may be laravel's autoloader. I want to know how to make my autoloader to just load class file under services folder, remaining other class files to be loaded by laravel framework's autoloader.

How to solve this. Thank you in advance.

答:
I solved this by check the file exist first.  And the autoloaders have loading sequence.

manual,

If there must be multiple autoload functions, spl_autoload_register()
  allows for this. It effectively creates a queue of autoload functions,
  and runs through each of them in the order they are defined. By
  contrast, __autoload() may only be defined once.

```<code>public function __construct()
{
    spl_autoload_register(function($classname) {
        if(file_exists(app_path() . '/services/' . $classname . '.php'))
            include app_path() . '/services/' . $classname . '.php';
    });
}
</code>```

So my defined autoloader will load the php class before laravel framework's autoloader.

Body:
I write autoloader in my controller file to load a class file. This load class in the services folder well. But it will cause this issue when load class not in services folder.

[2017-05-11 17:38:23] production.ERROR: exception 'ErrorException'
  with message 'include(/var/www/market/app/services/ProductDomain.php):
  failed to open stream: No such file or directory' in
  /var/www/market/app/controllers/CloudController.php:27

public function __construct()
{
    spl_autoload_register(function($classname) {
        include app_path() . '/services/' . $classname . '.php';
    });
}

This may caused by confilct with other autoloader, may be laravel's autoloader. I want to know how to make my autoloader to just load class file under services folder, remaining other class files to be loaded by laravel framework's autoloader.

How to solve this. Thank you in advance.

Body:
I solved this by check the file exist first.  And the autoloaders have loading sequence.

manual,

If there must be multiple autoload functions, spl_autoload_register()
  allows for this. It effectively creates a queue of autoload functions,
  and runs through each of them in the order they are defined. By
  contrast, __autoload() may only be defined once.

public function __construct()
{
    spl_autoload_register(function($classname) {
        if(file_exists(app_path() . '/services/' . $classname . '.php'))
            include app_path() . '/services/' . $classname . '.php';
    });
}

So my defined autoloader will load the php class before laravel framework's autoloader.


问:
Spring 3.x JSON status 406 "characteristics not acceptable according to the request "accept" headers ()"
Upon trying to get my response in JSON using Spring 3.x, I get the 406 error "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()."

Here is my environment

```<code>* Spring 3.2.0.RELEASE
* included jackson-mapper-asl-1.7.9.jar, jackson-core-asl-1.7.9.jar
* Tomcat 6.x
* mvc:annotation-driven in Spring configuration XML file
</code>```

My Controller:

```<code>@RequestMapping("/contest")
public class ContestController {

    @RequestMapping(value="{name}", headers="Accept=*/*", method = RequestMethod.GET)
    public @ResponseBody Contest getContestInJSON(@PathVariable String name) {
        Contest contest = new Contest();
        contest.setName(name);
        contest.setStaffName(new String("contestitem1"));

        return contest;
    }

}
</code>```

My Spring Configuration file

```<code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="com.contestframework.controllers" />

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">

<property name="mediaTypes">
    <map>
      <entry key="atom" value="application/atom+xml"/>
      <entry key="html" value="text/html"/>
      <entry key="json" value="application/json"/>
    </map>
 </property>

 <property name="viewResolvers">
 <list>
  <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
 </list>
 </property>

 <property name="defaultViews">
  <list>
   <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
  </list>
 </property>

 </bean>

<mvc:annotation-driven />

</beans>
</code>```

After this I just access the Controller using below:

```<code>http://domain/SpringWebProject/json/contest/abcd
</code>```

and the response I get is Status 406: "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()."

I also tried an alternate mechanism by access this using Javascript AJAX to make sure my request header has application/JSON but this led to the same Status 406 result

```<code>$.getJSON('contest/abcd', function(data) {
console.log(data) }
</code>```

Here is my REQUEST HEADER captured from browser:

```<code>Request URL:http://localhost:8080/SpringWebProject/json/contest/abcd
Request Method:GET
Status Code:406 Not Acceptable

Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:JSESSIONID=59689C95B0B9C21494EB0AB9D9F7BCCD
Host:localhost:8080
Referer:http://localhost:8080/SpringWebProject/json/welcome
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4
X-Requested-With:XMLHttpRequest
Response Headersview source
Content-Length:1070
Content-Type:text/html;charset=utf-8
Date:Fri, 12 Oct 2012 18:23:40 GMT
Server:Apache-Coyote/1.1
</code>```

Appreciate any help in this regard.

答:
Maybe you should update your jackson library. I use Spring v4.3.8 and I use it as follows:</p>

```<code><dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.8.7</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.8.7</version>
</dependency>
</code>```

Body:
Upon trying to get my response in JSON using Spring 3.x, I get the 406 error "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()."

Here is my environment

* Spring 3.2.0.RELEASE
* included jackson-mapper-asl-1.7.9.jar, jackson-core-asl-1.7.9.jar
* Tomcat 6.x
* mvc:annotation-driven in Spring configuration XML file

My Controller:

@RequestMapping("/contest")
public class ContestController {

    @RequestMapping(value="{name}", headers="Accept=*/*", method = RequestMethod.GET)
    public @ResponseBody Contest getContestInJSON(@PathVariable String name) {
        Contest contest = new Contest();
        contest.setName(name);
        contest.setStaffName(new String("contestitem1"));

        return contest;
    }

}

My Spring Configuration file

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="com.contestframework.controllers" />

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">

<property name="mediaTypes">
    <map>
      <entry key="atom" value="application/atom+xml"/>
      <entry key="html" value="text/html"/>
      <entry key="json" value="application/json"/>
    </map>
 </property>

 <property name="viewResolvers">
 <list>
  <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
 </list>
 </property>

 <property name="defaultViews">
  <list>
   <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
  </list>
 </property>

 </bean>

<mvc:annotation-driven />

</beans>

After this I just access the Controller using below:

http://domain/SpringWebProject/json/contest/abcd

and the response I get is Status 406: "The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()."

I also tried an alternate mechanism by access this using Javascript AJAX to make sure my request header has application/JSON but this led to the same Status 406 result

$.getJSON('contest/abcd', function(data) {
console.log(data) }

Here is my REQUEST HEADER captured from browser:

Request URL:http://localhost:8080/SpringWebProject/json/contest/abcd
Request Method:GET
Status Code:406 Not Acceptable

Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:JSESSIONID=59689C95B0B9C21494EB0AB9D9F7BCCD
Host:localhost:8080
Referer:http://localhost:8080/SpringWebProject/json/welcome
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4
X-Requested-With:XMLHttpRequest
Response Headersview source
Content-Length:1070
Content-Type:text/html;charset=utf-8
Date:Fri, 12 Oct 2012 18:23:40 GMT
Server:Apache-Coyote/1.1

Appreciate any help in this regard.

Body:
Maybe you should update your jackson library. I use Spring v4.3.8 and I use it as follows:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.8.7</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.8.7</version>
</dependency>


问:
Does the US map of AnyMap have DC and Puerto Rico
I have explored the gallery of AnyMap. It seems that the current US map doesn't support Washington D.C. and Puerto Rico. I was wondering if there is anyway to add these two "states" to this map? If not, what is the best way to represent data of these two? For example, adding two legends?

Thank you very much in advance!

答:
As far as Anychart uses Geo JSON standard for GeoData, you can use any free or paid source of geo data.
For example, I have found a highcharts map and wrote a simple converter for anychart library.

```<code>chart.geoData(Convertor.convert(Highcharts.maps['countries/us/custom/us-all-territories']));
</code>```

https://jsfiddle.net/mwhn5ce2/

Body:
As far as Anychart uses Geo JSON standard for GeoData, you can use any free or paid source of geo data.
For example, I have found a highcharts map and wrote a simple converter for anychart library.

chart.geoData(Convertor.convert(Highcharts.maps['countries/us/custom/us-all-territories']));

https://jsfiddle.net/mwhn5ce2/


问:
How Make Multiple Phone Call in Twilio
i don't know if this question is already asked before because i didn't see any.

I would like to make multiple phone call to my client at fixed time every day. Every day i like to wake up my client at 9.00AM . I have successful to call one number using click-to-call example by using rails.

But i don't an have idea how can i send request to twilio to make multiple call at once without queueing all my call. How can i do so ? I don't want my call to be in queue. Please guide me.

答:
Twilio developer evangelist here.

You can make multiple calls at the same time with Twilio, but there will be an amount of queueing as each account can make one outgoing call per second.

To make the calls at 9am every morning, you could write a Ruby script that runs through a list of numbers that you want to call (you could hardcode this, get numbers from your database or store them any way you want) and initiates a call using the REST API with them.

To schedule the script to run, you could use a cron job to run the script regularly. If you want to use cron in a Ruby way, then check out the whenever gem. Alternatively, if you are using a platform as a service, like Heroku, they tend to have job schedulers too.

Title: How Make Multiple Phone Call in Twilio


问:
Unable to Build Project after update to android studio preview 3.0 canary 3
I Just update my android studio preview 3.0 canary 3. After this I am trying to run the project but showing following error.</p>

```<code>Error:Could not find com.android.tools.build:gradle:3.0.0.
Searched in the following locations:
    file:/opt/android-studio-preview/gradle/m2repository/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom
    file:/opt/android-studio-preview/gradle/m2repository/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.jar
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.jar
Required by:
    project :
</code>```

答:
Change your build.gradle (project_name) 's one line(classpath) as per update:-

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha3'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
</code>```

Body:
I Just update my android studio preview 3.0 canary 3. After this I am trying to run the project but showing following error.

Error:Could not find com.android.tools.build:gradle:3.0.0.
Searched in the following locations:
    file:/opt/android-studio-preview/gradle/m2repository/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom
    file:/opt/android-studio-preview/gradle/m2repository/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.jar
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.pom
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0/gradle-3.0.0.jar
Required by:
    project :

Body:
Change your build.gradle (project_name) 's one line(classpath) as per update:-

dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha3'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}


问:
Angular Service is reset on each call of it
In my web Angular project I've created an AuthenticationGuard and an AuthenticationService to handle the security.

These files comes from another branch of my project who works perfectly.

Here is how my scripts should works:

Navigate to 'auth/login'

User inputs his credentials

Authservice call the back-end wepApi to get a Bearer Token

Back-end returns the token.

AuthService set his var 'isLoggedIn' to true;

AuthService use to router to navigate to '/home'

AuthGuard check authentication by checking the 'isLoggedIn' of AuthService.

My problem is when AuthGuard access the AuthService : AuthService always return false.

auth.guard.ts

import { Injectable }       from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';
import { AuthService }      from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (this.authService.getIsLoggedIn()) {
      return true;
    }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Navigate to the login page with extras
    this.router.navigate(['/auth/login']);
    return false;
  }
}```
</div>
</div>
</p>

<p>auth.service.ts
<div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';

import { config } from './../shared/smartadmin.config';

import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthService {
    private isLoggedIn: boolean = false;

    public redirectUrl: string;

    constructor(private router: Router, private http: Http) {
    }

    public getIsLoggedIn(): boolean {
        console.log("getIsLoggedIn() = " + this.isLoggedIn); // Always returns false
        return this.isLoggedIn;
    }

    public login(username: string, password: string) {
        this.ProcessLogin(username, password)
            .subscribe(result => {
                if (result === true) {
                    console.log("before attribution");
                    console.log("this.isLoggedIn = " + this.isLoggedIn); // returns false
                    this.isLoggedIn = true;
                    console.log("after attribution");
                    console.log("this.isLoggedIn = " + this.isLoggedIn); // returns true
                    this.router.navigate(this.redirectUrl ? [this.redirectUrl] : ['/home']);
                } else {
                    this.logout();
                }
            });
    }

    public logout(): void {
        localStorage.removeItem('oAuthToken');
        this.isLoggedIn = false;
    }

    private ProcessLogin(username: string, password: string): Observable<boolean> {

        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers });
        let body = 'grant_type=password&username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password);

        let endpoint = config.API_ENDPOINT + 'token';

        return this.http.post(endpoint, body, options)
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let token = response.json() && response.json().access_token;
                if (token) {
                    localStorage.setItem('oAuthToken', token);

                    // return true to indicate successful login
                    return true;
                } else {
                    localStorage.removeItem('oAuthToken');
                    // return false to indicate failed login
                    return false;
                }
            });
    }
}</code>```

答:
I had a  similar problem, which in my case was being caused by the click event being wired to a button element, but in Chrome the entire form was being submitted every time the button was clicked, because CHrome's default action is to treat a button click as a submit if there is no type attribute on the button.

The fix was to add the tag type="button" to the login button in the
  html

Description here

Body:
In my web Angular project I've created an AuthenticationGuard and an AuthenticationService to handle the security.

These files comes from another branch of my project who works perfectly.

Here is how my scripts should works:

Navigate to 'auth/login'

User inputs his credentials

Authservice call the back-end wepApi to get a Bearer Token

Back-end returns the token.

AuthService set his var 'isLoggedIn' to true;

AuthService use to router to navigate to '/home'

AuthGuard check authentication by checking the 'isLoggedIn' of AuthService.

My problem is when AuthGuard access the AuthService : AuthService always return false.

auth.guard.ts

import { Injectable }       from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';
import { AuthService }      from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (this.authService.getIsLoggedIn()) {
      return true;
    }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Navigate to the login page with extras
    this.router.navigate(['/auth/login']);
    return false;
  }
}

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';

import { config } from './../shared/smartadmin.config';

import { Http, Headers, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthService {
    private isLoggedIn: boolean = false;

    public redirectUrl: string;

    constructor(private router: Router, private http: Http) {
    }

    public getIsLoggedIn(): boolean {
        console.log("getIsLoggedIn() = " + this.isLoggedIn); // Always returns false
        return this.isLoggedIn;
    }

    public login(username: string, password: string) {
        this.ProcessLogin(username, password)
            .subscribe(result => {
                if (result === true) {
                    console.log("before attribution");
                    console.log("this.isLoggedIn = " + this.isLoggedIn); // returns false
                    this.isLoggedIn = true;
                    console.log("after attribution");
                    console.log("this.isLoggedIn = " + this.isLoggedIn); // returns true
                    this.router.navigate(this.redirectUrl ? [this.redirectUrl] : ['/home']);
                } else {
                    this.logout();
                }
            });
    }

    public logout(): void {
        localStorage.removeItem('oAuthToken');
        this.isLoggedIn = false;
    }

    private ProcessLogin(username: string, password: string): Observable<boolean> {

        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers });
        let body = 'grant_type=password&username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password);

        let endpoint = config.API_ENDPOINT + 'token';

        return this.http.post(endpoint, body, options)
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let token = response.json() && response.json().access_token;
                if (token) {
                    localStorage.setItem('oAuthToken', token);

                    // return true to indicate successful login
                    return true;
                } else {
                    localStorage.removeItem('oAuthToken');
                    // return false to indicate failed login
                    return false;
                }
            });
    }
}


问:
404 page in angular ui-router
I am using ui-router in an angular single page application. I have some routes defined, and I have a specific 404 route like this:

```<code>app.config(function($urlRouterProvider, $stateProvider){
   $urlProvider.otherwise('404')
   $stateProvider
      .state('example', {
         url: '/example/:id',
         templateUrl: 'example.html',
         controller: 'ExampleController'
      })
      .state('404', {
         url: '*path',
         templateUrl: '404.html'
      })
})
</code>```

Notice how the url for 404 state is '*path', which means it will match any path. I made it so if the user types something like '/some-non-existent-url' he won't be redirected to '/404', but rather stay at '/some-non-existent-url', but see the 404.html template. Here comes the problem: say my app interacts with some REST API inside my ExampleController, and the API may return an object, or it may return 404 Not Found based on the id from the url it receives. So, inside my controller, whenever this happens, I try to redirect to 404:

```<code>app.controller('ExampleController', function($state){
    someAPICall().then(function(response){ // do something},
                       function(response){
                            if(response.status == 404){
                                 $state.go('404');
                            }
                        });
});
</code>```

This is where the weird staff occurs. It displays the 404.html template - for a split second - and then redirects to home page (did not include it in my code here for the sake of brevity). My guess is that the '404' state does not have a real url specified: if I change it's url from '*path' to '/404' for example, this works fine, but I don't want to do this, as the user won't see which was the real url that caused a 404 response. Is there any workaround for this problem?

答: What worked for me was to remove $urlProvider.otherwise('404') and have the 404 state as the last state

Title: 404 page in angular ui-router

Body:
I am using ui-router in an angular single page application. I have some routes defined, and I have a specific 404 route like this:

app.config(function($urlRouterProvider, $stateProvider){
   $urlProvider.otherwise('404')
   $stateProvider
      .state('example', {
         url: '/example/:id',
         templateUrl: 'example.html',
         controller: 'ExampleController'
      })
      .state('404', {
         url: '*path',
         templateUrl: '404.html'
      })
})

Notice how the url for 404 state is '*path', which means it will match any path. I made it so if the user types something like '/some-non-existent-url' he won't be redirected to '/404', but rather stay at '/some-non-existent-url', but see the 404.html template. Here comes the problem: say my app interacts with some REST API inside my ExampleController, and the API may return an object, or it may return 404 Not Found based on the id from the url it receives. So, inside my controller, whenever this happens, I try to redirect to 404:

app.controller('ExampleController', function($state){
    someAPICall().then(function(response){ // do something},
                       function(response){
                            if(response.status == 404){
                                 $state.go('404');
                            }
                        });
});

This is where the weird staff occurs. It displays the 404.html template - for a split second - and then redirects to home page (did not include it in my code here for the sake of brevity). My guess is that the '404' state does not have a real url specified: if I change it's url from '*path' to '/404' for example, this works fine, but I don't want to do this, as the user won't see which was the real url that caused a 404 response. Is there any workaround for this problem?


问:
How Web broswer's ssl works
When a user selects using the ssl of web browser, for example,
a user selects the option of using ssl in FireFox, how the Web browser sets the ssl connection? Does the browser has a public key ?</p>

答: The browser has public keys from root certificate authorities. If a key from a website is signed by one of the root CA's in the browser, it can be verified as trustworthy automatically and ssl communication can start. Otherwise, you get prompted by the unknown/self-signed certificate dialog and decide for yourself whether to trust it or not.</p>

ContentLicense: CC BY-SA 2.5

Title: How Web broswer's ssl works


问:
Calculate difference between two dates and count the number of occurrences
I am trying to calculate the difference between two dates and in the same query trying to count the frequency of occurence.

```<code>SELECT DATEDIFF(day,[Date1],[Date2]) AS 'Mydate'
     , count ([Mydate])
  FROM Table1
 group
    by 'Mydate'
</code>```

I am expecting the query to calculate and count but getting an error msg "Each GROUP BY expression must contain at least one column that is not an outer reference."
what I am expecting is, something like this:

```<code>Mydate  Count
0        5
1        4
2        5
</code>```

Can someone help me please? Thanks

答:
You cannot group by an alias:</p>

```<code>SELECT 'Mydate', Cnt
FROM   (SELECT DATEDIFF(day, [Date1], [Date2]) AS 'Mydate',
               Count(*) Cnt
        FROM   Table1) T1
GROUP BY 'Mydate'
</code>```

Body:
I am trying to calculate the difference between two dates and in the same query trying to count the frequency of occurence.

SELECT DATEDIFF(day,[Date1],[Date2]) AS 'Mydate'
     , count ([Mydate])
  FROM Table1
 group
    by 'Mydate'

I am expecting the query to calculate and count but getting an error msg "Each GROUP BY expression must contain at least one column that is not an outer reference."
what I am expecting is, something like this:

Mydate  Count
0        5
1        4
2        5

Can someone help me please? Thanks

Body:
You cannot group by an alias:

SELECT 'Mydate', Cnt
FROM   (SELECT DATEDIFF(day, [Date1], [Date2]) AS 'Mydate',
               Count(*) Cnt
        FROM   Table1) T1
GROUP BY 'Mydate'


问:
WKWebView xmlhttprequest with file url
I am migrating from UIWebView to WKWebView with my local HTMLs in the app documents folder.
I can load the index page with all css and js files, but every ajax call (xmlhttprequest) fails because of allowed-access-origin.

I don´t want to use a webserver in my application, because I think it would be oversized. How can I make it possible? The app is a simple HTML5 application for an in house app. The device can´t get online or anything so security could be disabled completly.

答:
For those who came though SO to find this topic:

This isn't official to turn off the security in WKWebView, but we could use the private API to allow this just like this guy did for the Cordova project: cordova-plugin-wkwebviewxhrfix

The clue is to create the configuration for the WebView and set the allowFileAccessFromFileURLs property.

```<code>WKWebViewConfiguration* configuration = originalImpSend(_self, selector, settings);

// allow access to file api
@try {
    [configuration.preferences setValue:@TRUE forKey:@"allowFileAccessFromFileURLs"];
}
@catch (NSException *exception) {}

@try {
    [configuration setValue:@TRUE forKey:@"allowUniversalAccessFromFileURLs"];
}
@catch (NSException *exception) {}

return configuration;
</code>```

But as I mentioned this is the private API and it could be a reason to reject your application in Apple's App Review. If you want to publish your app in App Store, please consider to run some lightweight HTTP server instead of violate overall security of the web view. Example: GCDWebServer.

Title: WKWebView xmlhttprequest with file url

Body:
For those who came though SO to find this topic:

This isn't official to turn off the security in WKWebView, but we could use the private API to allow this just like this guy did for the Cordova project: cordova-plugin-wkwebviewxhrfix

The clue is to create the configuration for the WebView and set the allowFileAccessFromFileURLs property.

WKWebViewConfiguration* configuration = originalImpSend(_self, selector, settings);

// allow access to file api
@try {
    [configuration.preferences setValue:@TRUE forKey:@"allowFileAccessFromFileURLs"];
}
@catch (NSException *exception) {}

@try {
    [configuration setValue:@TRUE forKey:@"allowUniversalAccessFromFileURLs"];
}
@catch (NSException *exception) {}

return configuration;

But as I mentioned this is the private API and it could be a reason to reject your application in Apple's App Review. If you want to publish your app in App Store, please consider to run some lightweight HTTP server instead of violate overall security of the web view. Example: GCDWebServer.


问:
How can I select an element in jquery?
I'm a beginner in this programming language. I beg your pardon.

How can I select an element in JQuery?  What is wrong with my code? SOmeone help me.

```<code>    <!DOCTYPE html>
    <html>
         <head>
         <title></title>
         <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
         </head>
    <body>
    <input type="password">

    <script type="text/javascript">
         $(document).ready(function(){

         $('input[type=password]').attr({
              name: 'pass'
              style: [
                  color: 'blue',
                  font-size: '20px'
              ],
            });
        )};
    </script>
</code>```

答:
use .css() for style property

$(document).ready(function() {

  $('input[type=password]').attr({
    name: 'pass'
  }).css({
    "color": "blue",
    "font-size": "20px"
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="password"></code>```

Title: How can I select an element in jquery?

Body:
I'm a beginner in this programming language. I beg your pardon.

How can I select an element in JQuery?  What is wrong with my code? SOmeone help me.

    <!DOCTYPE html>

         <title></title>

    <input type="password">

Body:
use .css() for style property

$(document).ready(function() {

  $('input[type=password]').attr({
    name: 'pass'
  }).css({
    "color": "blue",
    "font-size": "20px"
  });

});

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="password">


问:
Oracle timestamp with timezone : replace date portion to current date
I have a oracle table for maintaining cutoff time. here we are storing cutoff time for various securities.. currently we are defaulting date portion of cutoff to 1st Jan 1970. The requirement is to replace this date portion with current date without changing time and timezone portion of cutoff. </p>

答:
You could calculate the number of days between today and 1970-01-01, and then add that as a day-to-second interval to your cutoff timestamp value:

```<code>create table my_table (cutoff timestamp with time zone);

insert into my_table values (timestamp '1970-01-01 18:00:00 -5:00');

select cutoff + numtodsinterval(trunc(sysdate) - date '1970-01-01', 'DAY') as adjusted
from my_table;

ADJUSTED
-----------------------------------
05-JUN-17 18.00.00.000000000 -05:00
</code>```

or if you prefer, you can generate an interval directly (as @mathguy pointed out):

```<code>select cutoff + (trunc(sysdate) - timestamp '1970-01-01 00:00:00') as adjusted
from my_table;

ADJUSTED
-------------------------
06-JUN-17 18:00:00 -05:00
</code>```

The -05:00 time zone offset ignores daylight savings time, of course, but that seems to be what you intended.

Body:
You could calculate the number of days between today and 1970-01-01, and then add that as a day-to-second interval to your cutoff timestamp value:

create table my_table (cutoff timestamp with time zone);

insert into my_table values (timestamp '1970-01-01 18:00:00 -5:00');

select cutoff + numtodsinterval(trunc(sysdate) - date '1970-01-01', 'DAY') as adjusted
from my_table;

ADJUSTED
-----------------------------------
05-JUN-17 18.00.00.000000000 -05:00

or if you prefer, you can generate an interval directly (as @mathguy pointed out):

select cutoff + (trunc(sysdate) - timestamp '1970-01-01 00:00:00') as adjusted
from my_table;

ADJUSTED
-------------------------
06-JUN-17 18:00:00 -05:00

The -05:00 time zone offset ignores daylight savings time, of course, but that seems to be what you intended.


问:
Changing symmetric.key.master.password not working in 6.0
Same question

While installing new hybris instance, I trying to changed symmetric.key.master.password. But it throw following error while server startup.

Please note: I have created symmetric.key.master.password with random text/number e.g(JOSD53FJPjas1243ojdf9872rIJDFOJS3DioaIUOSI64Dj4foiaew12fIIOAS)

Error :

```<code>  [java] ERROR [main] [EncryptionUtil] pad block corrupted
  [java] javax.crypto.BadPaddingException: pad block corruptedWARN  [main] [CloseAwareApplicationContext] Exception encountered during context initialization - cancelling refresh attempt
  [java]     at org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(Unknown Source)
  [java]     at javax.crypto.Cipher.doFinal(Cipher.java:2165)
  [java]     at de.hybris.platform.util.encryption.EncryptionUtil.loadKey(EncryptionUtil.java:527)
  [java]     at de.hybris.platform.util.encryption.EncryptionUtil.loadKey(EncryptionUtil.java:484)
  [java]     at de.hybris.platform.util.encryption.EncryptionUtil.loadKey(EncryptionUtil.java:429)
  [java]
  [java]     at de.hybris.platform.core.MasterTenant.readKeyFiles(MasterTenant.java:235)
  [java]     at de.hybris.platform.core.MasterTenant.getValueEncryptor(MasterTenant.java:147)
  [java]     at de.hybris.platform.directpersistence.read.DefaultSLDItemDAO.init(DefaultSLDItemDAO.java:69)
  [java]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  [java]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  [java]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  [java]     at java.lang.reflect.Method.invoke(Method.java:498)
  [java]     at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:349)
  [java]     at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:300)
  [java]     at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)
  [java]     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)
  [java]     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566)
  [java]     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
  [java]     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
  [java]     at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
  [java]     at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  [java]     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
  [java]     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
  [java]     at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
</code>```

Edit :-

local.properties changes :

```<code>symmetric.key.file.1=default-128-bit-aes-key.hybris
symmetric.key.file.2=Generated-256-Bit-AES-Key2.hybris
symmetric.key.file.default=2
symmetric.key.master.password=1234567
</code>```

with above configuration hybris server working fine(hybrisserver.sh/ant initialize etc). But if I try to change master.password to 1234568 it throws pad block corrupted while hybrisserver.sh/ant initialize. I also tried with fresh database(drop/create) and do ant initialize, getting same error. It is only working with OOTB master.password (1234567)

答:
If you have access to Hybris wiki, see this link it might help you
Transparent Attribute Encryption</p>

Body:
Same question

While installing new hybris instance, I trying to changed symmetric.key.master.password. But it throw following error while server startup.

Please note: I have created symmetric.key.master.password with random text/number e.g(JOSD53FJPjas1243ojdf9872rIJDFOJS3DioaIUOSI64Dj4foiaew12fIIOAS)

Error :

  [java] ERROR [main] [EncryptionUtil] pad block corrupted
  [java] javax.crypto.BadPaddingException: pad block corruptedWARN  [main] [CloseAwareApplicationContext] Exception encountered during context initialization - cancelling refresh attempt
  [java]     at org.bouncycastle.jce.provider.JCEBlockCipher.engineDoFinal(Unknown Source)
  [java]     at javax.crypto.Cipher.doFinal(Cipher.java:2165)
  [java]     at de.hybris.platform.util.encryption.EncryptionUtil.loadKey(EncryptionUtil.java:527)
  [java]     at de.hybris.platform.util.encryption.EncryptionUtil.loadKey(EncryptionUtil.java:484)
  [java]     at de.hybris.platform.util.encryption.EncryptionUtil.loadKey(EncryptionUtil.java:429)
  [java]
  [java]     at de.hybris.platform.core.MasterTenant.readKeyFiles(MasterTenant.java:235)
  [java]     at de.hybris.platform.core.MasterTenant.getValueEncryptor(MasterTenant.java:147)
  [java]     at de.hybris.platform.directpersistence.read.DefaultSLDItemDAO.init(DefaultSLDItemDAO.java:69)
  [java]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  [java]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  [java]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  [java]     at java.lang.reflect.Method.invoke(Method.java:498)
  [java]     at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:349)
  [java]     at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:300)
  [java]     at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)
  [java]     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)
  [java]     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566)
  [java]     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
  [java]     at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
  [java]     at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
  [java]     at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  [java]     at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
  [java]     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
  [java]     at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)

Edit :-

local.properties changes :

symmetric.key.file.1=default-128-bit-aes-key.hybris
symmetric.key.file.2=Generated-256-Bit-AES-Key2.hybris
symmetric.key.file.default=2
symmetric.key.master.password=1234567

with above configuration hybris server working fine(hybrisserver.sh/ant initialize etc). But if I try to change master.password to 1234568 it throws pad block corrupted while hybrisserver.sh/ant initialize. I also tried with fresh database(drop/create) and do ant initialize, getting same error. It is only working with OOTB master.password (1234567)


问:
Selecting distinct keys and their counts from a dictionary series in python
I have a pandas dictionary series, that takes the values like

```<code>   0 {AA:25,BB:31}
   1 {CC:45,AA:3}
   2 {BB:3,CD:4,AA:5}
</code>```

I want to create a dictionary out of it based on the key and its occurrence in series, like:

```<code>{AA:3,BB:2,CC:1,CD:1}
</code>```

答:
```<code>counter = dict()
for item in series:
    for key in item:
       counter[key] = counter.get(key, 0) + 1
</code>```

Body:
I have a pandas dictionary series, that takes the values like

   0 {AA:25,BB:31}
   1 {CC:45,AA:3}
   2 {BB:3,CD:4,AA:5}

I want to create a dictionary out of it based on the key and its occurrence in series, like:

{AA:3,BB:2,CC:1,CD:1}


问:
get commmon properties of two different object using c#
I need to get common properties (i.e .properties having same name) from objects of two different classes into an array. But I'm not able to provide the correct syntax near Join. This is my code. Please, help

```<code>        PropertyInfo[] objAllProps = SourceInstance.GetType().GetProperties();
        PropertyInfo[] objAllProps_Target = TargetInstance.GetType().GetProperties();

        PropertyInfo[] CommonProperties =
              from allprops in objAllProps join
                   allprop_target in objAllProps_Target on
                       allprops.Name.Equals(allprop_target)
            select new PropertyInfo[] {
                       allprop_target,
                   }
            .ToArray<PropertyInfo>();
</code>```

答:
I suggest different collection's type HashSet<string> instead of PropertyInfo[]:

```<code>   HashSet<string> NamesToFind = new HashSet<string>(SourceInstance
     .GetType()
     .GetProperties()
     .Select(property => property.Name));

   // Common properties: properties of TargetInstance such that
   // there's a property of SourceInstance with the same name
   PropertyInfo[] CommonProperties = TargetInstance
     .GetType()
     .GetProperties()
     .Where(property => NamesToFind.Contains(property.Name))
     .ToArray();
</code>```

Body:
I need to get common properties (i.e .properties having same name) from objects of two different classes into an array. But I'm not able to provide the correct syntax near Join. This is my code. Please, help

        PropertyInfo[] objAllProps = SourceInstance.GetType().GetProperties();
        PropertyInfo[] objAllProps_Target = TargetInstance.GetType().GetProperties();

        PropertyInfo[] CommonProperties =
              from allprops in objAllProps join
                   allprop_target in objAllProps_Target on
                       allprops.Name.Equals(allprop_target)
            select new PropertyInfo[] {
                       allprop_target,
                   }
            .ToArray<PropertyInfo>();

Body:
I suggest different collection's type HashSet<string> instead of PropertyInfo[]:

   HashSet<string> NamesToFind = new HashSet<string>(SourceInstance
     .GetType()
     .GetProperties()
     .Select(property => property.Name));

   // Common properties: properties of TargetInstance such that
   // there's a property of SourceInstance with the same name
   PropertyInfo[] CommonProperties = TargetInstance
     .GetType()
     .GetProperties()
     .Where(property => NamesToFind.Contains(property.Name))
     .ToArray();


问:
Is it ok to use "async" with a ThreadStart method?
I have a Windows Service that uses Thread and SemaphoreSlim to perform some "work" every 60 seconds.

```<code>class Daemon
{
    private SemaphoreSlim _semaphore;
    private Thread _thread;

    public void Stop()
    {
        _semaphore.Release();
        _thread.Join();
    }

    public void Start()
    {
        _semaphore = new SemaphoreSlim(0);
        _thread = new Thread(DoWork);
        _thread.Start();
    }

    private void DoWork()
    {
        while (true)
        {
            // Do some work here

            // Wait for 60 seconds, or exit if the Semaphore is released
            if (_semaphore.Wait(60 * 1000))
            {
                return;
            }
        }
    }
}
</code>```

I'd like to call an asynchronous method from DoWork. In order to use the await keyword I must add async to DoWork:

```<code>private async void DoWork()
</code>```

Is there any reason not to do this?

Is DoWork actually able to run asynchronously, if it's already running inside a dedicated thread?

答:
You can do this, but it wouldn't be a good idea. As soon as the first await hits that is not synchronously completed, the rest of the work will be done on a continuation, not the thread you started (_thread); the thread you start will terminate at the first such await. There is no guarantee that a continuation will go back to the originating thread, and in your scenario, it cannot - that thread is now toast. That means that:

_thread is meaningless and does not represent the state of the operation; as such, your Stop() method with a _thread.Join(); doesn't do what you expect it to do

you've created a thread (allocating threads is expensive, in particular because of the size of the stack) only to have it exit almost immediately

Both of these issues can avoided by using Task.Run to start such operations.

Body:
I have a Windows Service that uses Thread and SemaphoreSlim to perform some "work" every 60 seconds.

class Daemon
{
    private SemaphoreSlim _semaphore;
    private Thread _thread;

    public void Stop()
    {
        _semaphore.Release();
        _thread.Join();
    }

    public void Start()
    {
        _semaphore = new SemaphoreSlim(0);
        _thread = new Thread(DoWork);
        _thread.Start();
    }

    private void DoWork()
    {
        while (true)
        {
            // Do some work here

            // Wait for 60 seconds, or exit if the Semaphore is released
            if (_semaphore.Wait(60 * 1000))
            {
                return;
            }
        }
    }
}

I'd like to call an asynchronous method from DoWork. In order to use the await keyword I must add async to DoWork:

private async void DoWork()

Is there any reason not to do this?

Is DoWork actually able to run asynchronously, if it's already running inside a dedicated thread?


问:
Progress bar loading is not stopped when the activity is called second time
I have created a welcome page(launcher) and included a progress bar.next activity will be displayed after this progress bar loading(for few seconds).For the first time,when the app is run,after few seconds the next activity is displayed.Now,when i press back button,welcome activity is being displayed.But this time,after few seconds,it is now calling the next activity(using Intent) like the first time.How to resolve this?
The code is:</p>

```<code>import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;

public class WelcomeActivity extends AppCompatActivity {
    ProgressBar p;
    private boolean mbActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        p = (ProgressBar) findViewById(R.id.progressBar);
        final Thread timerThread = new Thread() {
            @Override
            public void run() {
                mbActive = true;
                try {
                    int waited = 0;
                    while(mbActive && (waited < 1000)) {
                        sleep(200);
                        if(mbActive) {
                            waited += 200;
                            updateProgress(waited);
                        }
                    }
                } catch(InterruptedException e) {
                } finally {
                    onContinue();
                }
            }
        };
        timerThread.start();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    public void updateProgress(final int timePassed) {
        if(null != p) {
            final int progress = p.getMax() * timePassed / 100;
            p.setProgress(progress);
        }
    }

    public void onContinue() {
        Intent intd=new Intent(this,MainActivity.class);
        startActivity(intd);
    }

}
</code>```

答:
You should use setVisibility(View.GONE);/setVisibility(View.INVISIBLE) .

```<code>public void onContinue()
    {
    p.setVisibility(View.GONE);
    Intent intd=new Intent(this,MainActivity.class);
    startActivity(intd);
    }
</code>```

FYI

CalledFromWrongThreadException is a common error if you tried to send
  UI events to the UI thread from outside the UI thread.

For your crash case . Read runOnUiThread

Body:
I have created a welcome page(launcher) and included a progress bar.next activity will be displayed after this progress bar loading(for few seconds).For the first time,when the app is run,after few seconds the next activity is displayed.Now,when i press back button,welcome activity is being displayed.But this time,after few seconds,it is now calling the next activity(using Intent) like the first time.How to resolve this?
The code is:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;

public class WelcomeActivity extends AppCompatActivity {
    ProgressBar p;
    private boolean mbActive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        p = (ProgressBar) findViewById(R.id.progressBar);
        final Thread timerThread = new Thread() {
            @Override
            public void run() {
                mbActive = true;
                try {
                    int waited = 0;
                    while(mbActive && (waited < 1000)) {
                        sleep(200);
                        if(mbActive) {
                            waited += 200;
                            updateProgress(waited);
                        }
                    }
                } catch(InterruptedException e) {
                } finally {
                    onContinue();
                }
            }
        };
        timerThread.start();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    public void updateProgress(final int timePassed) {
        if(null != p) {
            final int progress = p.getMax() * timePassed / 100;
            p.setProgress(progress);
        }
    }

    public void onContinue() {
        Intent intd=new Intent(this,MainActivity.class);
        startActivity(intd);
    }

}

Body:
You should use setVisibility(View.GONE);/setVisibility(View.INVISIBLE) .

public void onContinue()
    {
    p.setVisibility(View.GONE);
    Intent intd=new Intent(this,MainActivity.class);
    startActivity(intd);
    }

FYI

CalledFromWrongThreadException is a common error if you tried to send
  UI events to the UI thread from outside the UI thread.

For your crash case . Read runOnUiThread


问:
how to set up arangodb with feather generate custom service (generator-feathers)
I've set up a server with feathers-cli

```<code>feathers geneate app
</code>```

Since there's no default service for Arangodb available I did:

```<code>feathers generate service
> A custom service
</code>```

I'm searching for examples/docs now, on how to link custom service calls like create, find, get etc. to arangodb or any db for that matter.

答:
The documentation on how to create your own services can be found in the services API documentation.

An ArangoDB service that stores data in a collection just looks like this:

```<code>class Service {
  constructor(collection) {
    this.collection = collection;
  }

  create(data) {
    return this.collection.save(data);
  }
}
</code>```

And you would implement similar functionality for find, update, patch and remove.

There are now different ways to initialize the database connection and the service. For some patterns you can refer to how the generator sets up MongoDB or Mongoose, for ArangoDB it probably looks something like this:

```<code>const { Database } = require('arangojs');

app.set('arangodb', new Database('http://127.0.0.1:8529'));

db.createDatabase('mydb').then(
  () => {
    db.useDatabase('mydb');
    // Initialize the service here
    app.use('/myservice', new Service(db.collection('people')));
  },
  err => console.error('Failed to create database:', err)
);
</code>```

The code of existing adapters, e.g. feathers-memory or one of the many other database adapters can also be a good reference.

Body:
I've set up a server with feathers-cli

feathers geneate app

Since there's no default service for Arangodb available I did:

feathers generate service
> A custom service

I'm searching for examples/docs now, on how to link custom service calls like create, find, get etc. to arangodb or any db for that matter.

Body:
The documentation on how to create your own services can be found in the services API documentation.

An ArangoDB service that stores data in a collection just looks like this:

class Service {
  constructor(collection) {
    this.collection = collection;
  }

  create(data) {
    return this.collection.save(data);
  }
}

And you would implement similar functionality for find, update, patch and remove.

There are now different ways to initialize the database connection and the service. For some patterns you can refer to how the generator sets up MongoDB or Mongoose, for ArangoDB it probably looks something like this:

const { Database } = require('arangojs');

app.set('arangodb', new Database('http://127.0.0.1:8529'));

db.createDatabase('mydb').then(
  () => {
    db.useDatabase('mydb');
    // Initialize the service here
    app.use('/myservice', new Service(db.collection('people')));
  },
  err => console.error('Failed to create database:', err)
);

The code of existing adapters, e.g. feathers-memory or one of the many other database adapters can also be a good reference.


问:
Exchange Web Services GetAttachment will not stream to disk
We are using Exchange Web Services from java (jaxws). Here's the issue. To get an attachment, you execute the GetAttachment soap call (logical enough :) ). Here's the problem: the entire attachment is returned (with no access to attachment size) in a base64 packet tucked deep inside a soap response along with other info. As a result the entire attachment contents is buffered into memory. With potentially 2GB attachments, this can get the entire java client to blow up out of memory.

There appears to be no way to get just pieces of attachments from EWS. MTOM, etc does not appear to be supported. In short there appears to be no provisions in EWS for streaming.

The only way around this situation would seem to be a very low level proxy to intercept these calls, and stream the contents to disk, replacing it with a "marker flag" to the file on disk. But there appears to be no elegant way to do this?

Any ideas

答: We have succeeded through a SOAP MessageHandler. Right now it streams everything to disk, and the caller must interpret the content as the disk uri. We believe it could be improved. Nonetheless, it IS possible to do</p>


问:
Lombok does not work for Eclipse Neon
I downloaded lombok.jar (lombok-1.16.14.jar) put it into my Downloads. Then I clicked on this jar, the execution correctly identifies the Eclipse instances on my MacOS and then I selected the instance I want.  Lombok is also specified in the pom.xml

      org.projectlombok
      lombok
       1.16.14
       provided

In eclipse.ini I got the addition:
-javaagent:../Eclipse/lombok.jar

lombok.jar was added to the same directory as eclise.ini
/Applications/Eclipse.app/Contents/Eclipse

I am still getting setter/getter errors in Eclipse Problems despite that my mvn build works fine.

The code for a User:

```<code>@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EntityListeners(UserListener.class)
public class User implements Serializable, UserDetails {
...
</code>```

The error:

```<code>The method getRole() is undefined for the type User
</code>```

答:
I had the problem, that the link, which I used to start eclipse, didnt respect the eclipse.ini file.

My environment is:

```<code>IDE: Version: Neon.0 Release (4.6.0)
OS: Ubuntu 16.04.2 LTS
</code>```

The installation routine java -jar lombok-1.16.16.jar works quite well. I.e. it adds the reasonable line -javaagent:<ABSOLUTE_PATH_TO_ECLIPSE_INSTALLATION>/lombok.jar to the eclipse.ini.

But if I start eclipse by using my desktop-shortcut, it starts without lombok (checked by looking at "Help"->"About Eclipse").
If I start eclipse by executing the executable eclipse next to the eclipse.ini file, lombok launches like a charm.

Hence I checked my desktop shortcut (e.g. ~/.local/share/applications/eclipse.desktop) and indeed, it started eclipse without reflecting the eclipse.ini.
Instead it uses something like /usr/bin/java -jar org.eclipse.equinox.launcher.jar ... to start eclipse.

So the solution was to replace the old Exec line in the desktop shortcut by:

```<code>Exec=/opt/eclipse/neon/eclipse
</code>```

where /opt/eclipse/neon/ is the place where I have installed eclipse.

Title: Lombok does not work for Eclipse Neon

Body:
I downloaded lombok.jar (lombok-1.16.14.jar) put it into my Downloads. Then I clicked on this jar, the execution correctly identifies the Eclipse instances on my MacOS and then I selected the instance I want.  Lombok is also specified in the pom.xml

      org.projectlombok
      lombok
       1.16.14
       provided

In eclipse.ini I got the addition:
-javaagent:../Eclipse/lombok.jar

lombok.jar was added to the same directory as eclise.ini
/Applications/Eclipse.app/Contents/Eclipse

I am still getting setter/getter errors in Eclipse Problems despite that my mvn build works fine.

The code for a User:

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EntityListeners(UserListener.class)
public class User implements Serializable, UserDetails {
...

The error:

The method getRole() is undefined for the type User

Body:
I had the problem, that the link, which I used to start eclipse, didnt respect the eclipse.ini file.

My environment is:

IDE: Version: Neon.0 Release (4.6.0)
OS: Ubuntu 16.04.2 LTS

The installation routine java -jar lombok-1.16.16.jar works quite well. I.e. it adds the reasonable line -javaagent:<ABSOLUTE_PATH_TO_ECLIPSE_INSTALLATION>/lombok.jar to the eclipse.ini.

But if I start eclipse by using my desktop-shortcut, it starts without lombok (checked by looking at "Help"->"About Eclipse").
If I start eclipse by executing the executable eclipse next to the eclipse.ini file, lombok launches like a charm.

Hence I checked my desktop shortcut (e.g. ~/.local/share/applications/eclipse.desktop) and indeed, it started eclipse without reflecting the eclipse.ini.
Instead it uses something like /usr/bin/java -jar org.eclipse.equinox.launcher.jar ... to start eclipse.

So the solution was to replace the old Exec line in the desktop shortcut by:

Exec=/opt/eclipse/neon/eclipse

where /opt/eclipse/neon/ is the place where I have installed eclipse.


问:
Where is the github page repo?
According to the guide of github page, when a github page is create, we should be able to find the repo on github.com, with the following rule: if we have username.github.io, then we can find the repo in github.com/username.

However, sometimes, I can't find the repo with the rule above. I would like to know if there is another way to host a github page, or maybe the username.github.io can be private but the website is public ?

Thank you

答:
If you don't see repository, It's no necessary to mean repository isn't exist, it is private repository.

GitHub page for user, projects

Source: https://help.github.com/articles/user-organization-and-project-pages/

Title: Where is the github page repo?


问:
Adding extra Zero's dynamically to Integer in fixed lenght format
I need to display a sql column Amount in a format of 15 Integers and 3 decimal places (18 length).

Add extra zero's dynamically to complete the length 18

Decimal(.) will also be replaced by a Zero

For Example :

$2,494.60 will be displayed as 000000002494060

Is it possible to achieve it using SQL ?

Body:
You can use STR to fix the leading and trailing decimal places, and REPLACE to change spaces and dots into zeroes.

Query:

SELECT Amount
    , PaddedAmount = REPLACE(REPLACE(STR(Amount, 15, 2), '.', '0'), ' ', '0')
FROM
    (VALUES (12345.678), (1231312), (0.12345), (0), (123456789012.45)) AS V (Amount)

Output:

Amount               PaddedAmount
-------------------  ----------------
12345.67800          000000012345068
1231312.00000        000001231312000
0.12345              000000000000012
0.00000              000000000000000
123456789012.45000   123456789012045


问:
Return database connection from function
I'm trying to return $db connection from function, so that I could use it in another function. But someone functions don't understand $db variable.

```<code>function dbConnection(){
   $dbhost = 'localhost';
   $dbuser = '...';
   $dbpass = '...';
   $dbname = '...';

   try {
     $db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=UTF8", $dbuser, $dbpass);
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     return $db;
   } catch (PDOException $e){
     echo 'Connection failed: ' . $e->getMessage();
   }
}
</code>```

Then use it in all of my functions.

```<code>function getCurrentFile(){
   dbConnection();

   $stmt = $db->prepare(...);
   $stmt->execute();

}
</code>```

Are there more preferable way to handle db connections? I used to require_once config.php(where is only db connection) file every time, but I don't want to do it anymore.

答: Write down your db connection code in class and create object to use everywhere else in your system.</p>

Body:
I'm trying to return $db connection from function, so that I could use it in another function. But someone functions don't understand $db variable.

function dbConnection(){
   $dbhost = 'localhost';
   $dbuser = '...';
   $dbpass = '...';
   $dbname = '...';

   try {
     $db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=UTF8", $dbuser, $dbpass);
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     return $db;
   } catch (PDOException $e){
     echo 'Connection failed: ' . $e->getMessage();
   }
}

Then use it in all of my functions.

function getCurrentFile(){
   dbConnection();

   $stmt = $db->prepare(...);
   $stmt->execute();

}

Are there more preferable way to handle db connections? I used to require_once config.php(where is only db connection) file every time, but I don't want to do it anymore.