问:
Is it worth to migrate from Angular 2 to Angular 4?
Hello SO community and Angularians!

So, I am midway developing a huge platform in Angular 2. And I realized that many external libraries and dependencies for Angular 2 are migrating to the new Angular 4. Giving me many errors, obviously.

I could fork these libraries and use the forked versions and subscribe to main library development or, I could just upgrade to Angular 4 my project.

Questions to be answered in order to determinate if it's worth for me to migrate:

Compatibility with Angular 2.4

I have found some adaptations to ensure compatibility with legacy, like this: https://github.com/angular/angular/commit/e99d721

Changes app wide

Do I have to go through my whole app and start fixing things?

I mean, are main functionalities reworked in such way that I will have to review many of them?

Or, are there many build/core incompatibilities that will keep me days occupied fixing compile errors/warnings instead of developing?

I am not asking for someone to do the research for me, I am asking people that maybe already went through this process or simply know well both versions in order to give me some experience tips, clarifications, etc.

At the moment, I am doing my research here:

https://github.com/angular/angular/blob/master/CHANGELOG.md

http://angularjs.blogspot.it/2017/03/angular-400-now-available.html

https://learninglaravel.net/angular-4-new-features-and-improvements

UPDATE

I just migrated to Angular 4. The link that @PierreDuc put in his answer is a very nice tool to have a decent guideline in the migration process.

I would recommend:

Read new features and update yourself with Angular 4. This was specially useful: https://angularjs.blogspot.it/2017/03/angular-400-now-available.html

Follow Angular's guideline and modify your project: https://angular-update-guide.firebaseapp.com/

I would also recommend to commit your current project, create a new branch in your dev repository and proceed with migration in that branch.

An issue that I encountered:

Input, Output and ContentChild will be imported from a wrong path.

My case:

```<code>import { Component, OnInit, OnDestro } from '@angular/core';
import { Input, ContentChild } from "@angular/core/src/metadata/directives";
</code>```

Solution:

```<code>import { Component, OnInit, OnDestroy, Input, ContentChild } from '@angular/core';
</code>```

答:
Angular team has announced , let's not call angular 2 or angular 4 let's call it Angular and there will be major update for every 6 months.I have faced the issue in angular v4.0.0 so change the configuration in webpack

```<code>  new webpack.ContextReplacementPlugin(
                // The (\\|\/) piece accounts for path separators in *nix and Windows
                /angular(\\|\/)core(\\|\/)@angular/,
                helpers.root('./src'), // location of your src
                {} // a map of your routes
            ),
</code>```

And install @angular/animations package and import in app.module.ts file

```<code>import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
    imports: [
        BrowserAnimationsModule
    ]
})
</code>```

I will prefer to update to latest version of angular. Angular V4.0.0 has reduced the packages weight and they have increased the performance.

Body:
Hello SO community and Angularians!

So, I am midway developing a huge platform in Angular 2. And I realized that many external libraries and dependencies for Angular 2 are migrating to the new Angular 4. Giving me many errors, obviously.

I could fork these libraries and use the forked versions and subscribe to main library development or, I could just upgrade to Angular 4 my project.

Questions to be answered in order to determinate if it's worth for me to migrate:

Compatibility with Angular 2.4

I have found some adaptations to ensure compatibility with legacy, like this: https://github.com/angular/angular/commit/e99d721

Changes app wide

Do I have to go through my whole app and start fixing things?

I mean, are main functionalities reworked in such way that I will have to review many of them?

Or, are there many build/core incompatibilities that will keep me days occupied fixing compile errors/warnings instead of developing?

I am not asking for someone to do the research for me, I am asking people that maybe already went through this process or simply know well both versions in order to give me some experience tips, clarifications, etc.

At the moment, I am doing my research here:

https://github.com/angular/angular/blob/master/CHANGELOG.md

http://angularjs.blogspot.it/2017/03/angular-400-now-available.html

https://learninglaravel.net/angular-4-new-features-and-improvements

UPDATE

I just migrated to Angular 4. The link that @PierreDuc put in his answer is a very nice tool to have a decent guideline in the migration process.

I would recommend:

Read new features and update yourself with Angular 4. This was specially useful: https://angularjs.blogspot.it/2017/03/angular-400-now-available.html

Follow Angular's guideline and modify your project: https://angular-update-guide.firebaseapp.com/

I would also recommend to commit your current project, create a new branch in your dev repository and proceed with migration in that branch.

An issue that I encountered:

Input, Output and ContentChild will be imported from a wrong path.

My case:

import { Component, OnInit, OnDestro } from '@angular/core';
import { Input, ContentChild } from "@angular/core/src/metadata/directives";

Solution:

import { Component, OnInit, OnDestroy, Input, ContentChild } from '@angular/core';

Body:
Angular team has announced , let's not call angular 2 or angular 4 let's call it Angular and there will be major update for every 6 months.I have faced the issue in angular v4.0.0 so change the configuration in webpack

  new webpack.ContextReplacementPlugin(
                // The (\\|\/) piece accounts for path separators in *nix and Windows
                /angular(\\|\/)core(\\|\/)@angular/,
                helpers.root('./src'), // location of your src
                {} // a map of your routes
            ),

And install @angular/animations package and import in app.module.ts file

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
    imports: [
        BrowserAnimationsModule
    ]
})

I will prefer to update to latest version of angular. Angular V4.0.0 has reduced the packages weight and they have increased the performance.


来源: stackexchange

问:
Max value 3D array in Python
We have a 3D array (671, 9066, 2):

671 IdUser (bloc)

For each 671 users we have 9066 (rows) movies and proba associated (2 columns)

Example of two columns for 1 user:

```<code>Proba                Idmovie
[  6.93933334e-02,   1.00000000e+00],
[  8.50563031e-02,   2.00000000e+00],
....
[  2.95071098e-02,   3.00000000e+00]
</code>```

We need the maximum proba (here 8.50563031e-02) and the value of the second column associated (here 2.00000000e+00). This for each 671 users!

Thank you very much

答:
The most compact way in numpy is probably something like this:

```<code>x[range(x.shape[0]),np.argmax(x, axis=1)[:,0],:]
</code>```

Explanation:

```<code>np.argmax(x, axis=1)
</code>```

returns the indices of the maximum values along the second ("movies") axis

```<code>np.argmax(x, axis=1)[:,0]
</code>```

reduces this to the first column only since we only need the indices for the maximum proba

Using these indices as an index array, we simply retrieve the respective proba/idmovie tuple for each user. The result is an array of shape (671,2) with the maximum proba and associated movie id for each user.

ContentLicense: CC BY-SA 3.0

Title: Max value 3D array in Python

Body:
We have a 3D array (671, 9066, 2):

671 IdUser (bloc)

For each 671 users we have 9066 (rows) movies and proba associated (2 columns)

Example of two columns for 1 user:

Proba                Idmovie
[  6.93933334e-02,   1.00000000e+00],
[  8.50563031e-02,   2.00000000e+00],
....
[  2.95071098e-02,   3.00000000e+00]

We need the maximum proba (here 8.50563031e-02) and the value of the second column associated (here 2.00000000e+00). This for each 671 users!

Thank you very much

Body:
The most compact way in numpy is probably something like this:

x[range(x.shape[0]),np.argmax(x, axis=1)[:,0],:]

Explanation:

np.argmax(x, axis=1)

returns the indices of the maximum values along the second ("movies") axis

np.argmax(x, axis=1)[:,0]

reduces this to the first column only since we only need the indices for the maximum proba

Using these indices as an index array, we simply retrieve the respective proba/idmovie tuple for each user. The result is an array of shape (671,2) with the maximum proba and associated movie id for each user.


问:
load key value pairs in consul using consul_kv ansible module
we have key value pairs in a file with json format.

```<code>{
  "app1":
 [
     {"key": "key1","value": "val1"},
     {"key": "key2","value": "val2"}

 ],
  "app2":
 [
      {"key": "key1","value": "val1"},
     {"key": "key2","value": "val2"}

 ],
  "app3":
 [
     {"key": "key1","value": "val1"},
     {"key": "key2","value": "val2"}

 ]
}
</code>```

I want to put these values in consul cluster. here is what i am trying

```<code>- debug: msg='key contains {{key}}'
  with_consul_kv:
  - 'config/app1/'
  register: keys

 - name: add a kv pair to the kv store
   consul_kv: key=somekey value=somevalue
   register: new_key
</code>```

答:
when your're not dependant on your JSON structure, you could use a format like:

```<code>myitems:
 - site:
      - {"key": "abcUrl","value": "http://prod.abc.url"}
      - {"key": "user.url","value": "http://prod.abc.login"}
      - {"key": "security.logout.url","value": "http://prod.abc.logout"}
 - site:
      - {"key": "abcUrl","value": "http://prod.abc.url"}
      - {"key": "user.url","value": "http://prod.abc.login"}
      - {"key": "security.logout.url","value": "http://prod.abc.logout"}
 - site:
      - {"key": "abcUrl","value": "http://prod.abc.url"}
      - {"key": "user.url","value": "http://prod.abc.login"}
      - {"key": "security.logout.url","value": "http://prod.abc.logout"}
 - site:
      - {"key": "abcUrl","value": "http://prod.abc.url"}
      - {"key": "user.url","value": "http://prod.abc.login"}
      - {"key": "security.logout.url","value": "http://prod.abc.logout"}
</code>```

(If you need the dc[1-4] inside for somethin, write it on the key/level.)

With this format you could extract key/value like this:

```<code>- name: remove a key from the store
  debug:
    msg: "key is {{ item.1.key }} and the value is {{ item.1.value }}"
  with_subelements:
    - "{{ myitems }}"
    - site
</code>```

ContentLicense: CC BY-SA 4.0

Body:
we have key value pairs in a file with json format.

{
  "app1":
 [
     {"key": "key1","value": "val1"},
     {"key": "key2","value": "val2"}

 ],
  "app2":
 [
      {"key": "key1","value": "val1"},
     {"key": "key2","value": "val2"}

 ],
  "app3":
 [
     {"key": "key1","value": "val1"},
     {"key": "key2","value": "val2"}

 ]
}

I want to put these values in consul cluster. here is what i am trying

- debug: msg='key contains {{key}}'
  with_consul_kv:
  - 'config/app1/'
  register: keys

 - name: add a kv pair to the kv store
   consul_kv: key=somekey value=somevalue
   register: new_key

Body:
when your're not dependant on your JSON structure, you could use a format like:

myitems:
 - site:
      - {"key": "abcUrl","value": "http://prod.abc.url"}
      - {"key": "user.url","value": "http://prod.abc.login"}
      - {"key": "security.logout.url","value": "http://prod.abc.logout"}
 - site:
      - {"key": "abcUrl","value": "http://prod.abc.url"}
      - {"key": "user.url","value": "http://prod.abc.login"}
      - {"key": "security.logout.url","value": "http://prod.abc.logout"}
 - site:
      - {"key": "abcUrl","value": "http://prod.abc.url"}
      - {"key": "user.url","value": "http://prod.abc.login"}
      - {"key": "security.logout.url","value": "http://prod.abc.logout"}
 - site:
      - {"key": "abcUrl","value": "http://prod.abc.url"}
      - {"key": "user.url","value": "http://prod.abc.login"}
      - {"key": "security.logout.url","value": "http://prod.abc.logout"}

(If you need the dc[1-4] inside for somethin, write it on the key/level.)

With this format you could extract key/value like this:

- name: remove a key from the store
  debug:
    msg: "key is {{ item.1.key }} and the value is {{ item.1.value }}"
  with_subelements:
    - "{{ myitems }}"
    - site


问:
Angular2 IE11 Unable to get property 'apply' of undefined or null reference
I am getting the following error after upgrading my angular2 packages to the following versions:

@angular/common": "^2.3.1

@angular/compiler": "^2.3.1

@angular/core": "^2.3.1

@angular/forms": "^2.3.1

@angular/http": "^2.3.1

@angular/platform-browser": "^2.3.1"

@angular/platform-browser-dynamic": "^2.3.1

@angular/platform-server": "^2.3.1

@angular/router": "^3.3.1

Error: Unable to get property 'apply' of undefined or null reference

I am only getting this error in IE11, in Chrome it works fine.

I did some digging and the line that causes the error is in the angular/common module:

```<code>function combine(options) {
  return (_a = ((Object))).assign.apply(_a, [{}].concat(options));
  var _a;
}
</code>```

The typescript file:

@angular/common/src/pipes/intl.ts line 175

```<code>function combine(options: Intl.DateTimeFormatOptions[]): Intl.DateTimeFormatOptions {
  return (<any>Object).assign({}, ...options);
}
</code>```

The code that calls the combine function is
@angular/common/src/pipes/intl.ts line 48:

'yMMMdjms': datePartGetterFactory(combine([

UPDATE

It seems that the actual error is that the .assign method is not implemented in IE11

答:
To Work in IE browser

Step 1:Run:npm i mdn-polyfills --save

Step 2: Open polyfills.ts

Step 3: UnComment the imports in the file under /** IE9, IE10 and IE11 requires all of the following polyfills. **/

Body:
I am getting the following error after upgrading my angular2 packages to the following versions:

@angular/common": "^2.3.1

@angular/compiler": "^2.3.1

@angular/core": "^2.3.1

@angular/forms": "^2.3.1

@angular/http": "^2.3.1

@angular/platform-browser": "^2.3.1"

@angular/platform-browser-dynamic": "^2.3.1

@angular/platform-server": "^2.3.1

@angular/router": "^3.3.1

Error: Unable to get property 'apply' of undefined or null reference

I am only getting this error in IE11, in Chrome it works fine.

I did some digging and the line that causes the error is in the angular/common module:

function combine(options) {
  return (_a = ((Object))).assign.apply(_a, [{}].concat(options));
  var _a;
}

The typescript file:

@angular/common/src/pipes/intl.ts line 175

function combine(options: Intl.DateTimeFormatOptions[]): Intl.DateTimeFormatOptions {
  return (<any>Object).assign({}, ...options);
}

The code that calls the combine function is
@angular/common/src/pipes/intl.ts line 48:

'yMMMdjms': datePartGetterFactory(combine([

UPDATE

It seems that the actual error is that the .assign method is not implemented in IE11


问:
Which is faster php date functions or carbon?
Carbon is simple PHP API extension for DateTime.
I want to know that we can use datetime functions using by installing carbon via composer.

which is faster php datetime functions or carbon ?

答:
I did some testing regarding your comment comparing DateTime to Carbon functions:

Calling Carbon::now() vs. new \DateTime() 100.000 times:

```<code><?php

require "Carbon.php";

use Carbon\Carbon;

$carbonTime = 0;
for ($i = 0; $i < 100000; $i++)
{
    $start = microtime(true);
    $time = Carbon::now();
    $end = microtime(true);

    $carbonTime += $end - $start;
}

echo "carbonTime: ".$carbonTime."\n";

$phpTime = 0;
for ($i = 0; $i < 100000; $i++)
{
    $start = microtime(true);
    $time = new \DateTime();
    $end = microtime(true);

    $phpTime += $end - $start;
}

echo "phpTime: ".$phpTime."\n";
</code>```

Results from 5 runs (meaning 5x 100.000 calls):

```<code>$ php test.php
carbonTime: 5.1191372871399
phpTime: 0.42734241485596

$ php test.php
carbonTime: 5.05357670784
phpTime: 0.41754531860352

$ php test.php
carbonTime: 5.4670262336731
phpTime: 0.42954564094543

$ php test.php
carbonTime: 5.0321266651154
phpTime: 0.44966721534729

$ php test.php
carbonTime: 5.1405448913574
phpTime: 0.4540810585022
</code>```

Confirming what I initially wrote:

Since Carbon inherits \DateTime it actually adds a little overhead to those calls (Carbon -> DateTime instead of directly DateTime). The main purpose of Carbon is not to be faster than DateTime, but to enhance it's functionality with commonly used functions.

Body:
I did some testing regarding your comment comparing DateTime to Carbon functions:

Calling Carbon::now() vs. new \DateTime() 100.000 times:

<?php

require "Carbon.php";

use Carbon\Carbon;

$carbonTime = 0;
for ($i = 0; $i < 100000; $i++)
{
    $start = microtime(true);
    $time = Carbon::now();
    $end = microtime(true);

    $carbonTime += $end - $start;
}

echo "carbonTime: ".$carbonTime."\n";

$phpTime = 0;
for ($i = 0; $i < 100000; $i++)
{
    $start = microtime(true);
    $time = new \DateTime();
    $end = microtime(true);

    $phpTime += $end - $start;
}

echo "phpTime: ".$phpTime."\n";

Results from 5 runs (meaning 5x 100.000 calls):

$ php test.php
carbonTime: 5.1191372871399
phpTime: 0.42734241485596

$ php test.php
carbonTime: 5.05357670784
phpTime: 0.41754531860352

$ php test.php
carbonTime: 5.4670262336731
phpTime: 0.42954564094543

$ php test.php
carbonTime: 5.0321266651154
phpTime: 0.44966721534729

$ php test.php
carbonTime: 5.1405448913574
phpTime: 0.4540810585022

Confirming what I initially wrote:

Since Carbon inherits \DateTime it actually adds a little overhead to those calls (Carbon -> DateTime instead of directly DateTime). The main purpose of Carbon is not to be faster than DateTime, but to enhance it's functionality with commonly used functions.


问:
Averaging a list of tuples
PLEASE HELP ME! I'M SUPER NEW AT THIS AND THINK I'VE GONE COMPLETELY OFF SOMEWHERE.

I Was given a csv file to use and extrapolate data from. Had a pretty extensive list of countries with their corresponding GDPs, unemployment rates and more. I'm mean to 1. Provide the country with the highest GDP in the list, and 2. Determine if this country has below average unemployment rate to go with it. I was able to get through the data definitions OK (I think) but I'm running into problems when I try to find the average unemployment rate in the given list (I used named tuple to organize the list by unemployment rate and country name).

```<code>def highest_gdp(logdp:List[CountryGDP])-> str:
    """
    returns the name of the country with the highest GDP
    """
    #Return "" #body of the stub
    #template from List[CountryGDP]

    highest = logdp[0] #type: CountryGDP
    for gdp in logdp:
        if gdp.cgdp >= highest.cgdp:
            highest = gdp
        return highest.name

def average_unemployment(louemp:List[Unemployment])-> float:
    """
    returns the average unemployment rate of the given list
    """
    #return 0 #body of the stub
    #template from List[Unemployment]

    average = louemp[0] #type: Unemployment
    for uemp in louemp:
        if uemp.rate > 0:
            average = uemp
        return sum(uemp.rate)/float(len(louemp))
</code>```

The first section is correct, I think. No errors were returned when I ran it, but I can't seem to figure out the second one that would be returning the average unemployment rate!! I keep getting various kinds of error messages, no matter what I try! I know this is super basic, but please help!!!

答:
I think you need to place the return statement outside of the for loop. For both cases. I didn't check the logic though.

```<code>def highest_gdp(logdp:List[CountryGDP])-> str:
    """
    returns the name of the country with the highest GDP
    """
    #Return "" #body of the stub
    #template from List[CountryGDP]

    highest = logdp[0] #type: CountryGDP
    for gdp in logdp:
        if gdp.cgdp >= highest.cgdp:
            highest = gdp
    return highest.name

def average_unemployment(louemp:List[Unemployment])-> float:
    """
    returns the average unemployment rate of the given list
    """
    #return 0 #body of the stub
    #template from List[Unemployment]

    average = louemp[0] #type: Unemployment
    for uemp in louemp:
        if uemp.rate > 0:
            average = uemp
    return sum(uemp.rate)/float(len(louemp))
</code>```

Title: Averaging a list of tuples

Body:
PLEASE HELP ME! I'M SUPER NEW AT THIS AND THINK I'VE GONE COMPLETELY OFF SOMEWHERE.

I Was given a csv file to use and extrapolate data from. Had a pretty extensive list of countries with their corresponding GDPs, unemployment rates and more. I'm mean to 1. Provide the country with the highest GDP in the list, and 2. Determine if this country has below average unemployment rate to go with it. I was able to get through the data definitions OK (I think) but I'm running into problems when I try to find the average unemployment rate in the given list (I used named tuple to organize the list by unemployment rate and country name).

def highest_gdp(logdp:List[CountryGDP])-> str:
    """
    returns the name of the country with the highest GDP
    """
    #Return "" #body of the stub
    #template from List[CountryGDP]

    highest = logdp[0] #type: CountryGDP
    for gdp in logdp:
        if gdp.cgdp >= highest.cgdp:
            highest = gdp
        return highest.name

def average_unemployment(louemp:List[Unemployment])-> float:
    """
    returns the average unemployment rate of the given list
    """
    #return 0 #body of the stub
    #template from List[Unemployment]

    average = louemp[0] #type: Unemployment
    for uemp in louemp:
        if uemp.rate > 0:
            average = uemp
        return sum(uemp.rate)/float(len(louemp))

The first section is correct, I think. No errors were returned when I ran it, but I can't seem to figure out the second one that would be returning the average unemployment rate!! I keep getting various kinds of error messages, no matter what I try! I know this is super basic, but please help!!!

Body:
I think you need to place the return statement outside of the for loop. For both cases. I didn't check the logic though.

def highest_gdp(logdp:List[CountryGDP])-> str:
    """
    returns the name of the country with the highest GDP
    """
    #Return "" #body of the stub
    #template from List[CountryGDP]

    highest = logdp[0] #type: CountryGDP
    for gdp in logdp:
        if gdp.cgdp >= highest.cgdp:
            highest = gdp
    return highest.name

def average_unemployment(louemp:List[Unemployment])-> float:
    """
    returns the average unemployment rate of the given list
    """
    #return 0 #body of the stub
    #template from List[Unemployment]

    average = louemp[0] #type: Unemployment
    for uemp in louemp:
        if uemp.rate > 0:
            average = uemp
    return sum(uemp.rate)/float(len(louemp))


问:
PHP with azure database
I am trying to make connection between azure database and php. I come to know that i need to install sqlsrv driver on server.

Is it possible to install sqlsrv driver on linux/ubuntu.Please give your support.

Is there any alternate method to make connection between azure db and php on linux.?

Regards

答:
a great article :

he SQL Server Driver for PHP allows
  PHP developers to access SQL Server
  databases that are hosted on SQL
  Server or SQL Azure. The SQL Server
  Driver for PHP relies on the Microsoft
  SQL Server ODBC Driver to handle
  low-level communication with SQL
  Server. As a result, the SQL Server
  Driver for PHP is only supported on
  Windows and Windows Azure. It can be
  downloaded and installed as a PHP
  extension

ContentLicense: CC BY-SA 2.5

Title: PHP with azure database


问:
getting only one data from laravel collection seems difficult
I don't get this, I have a collection of items.
The collection contains in this case one and only one item at index 1 as it was filtered from a bigger collection.
The point is how do I get the only piece of data I need without having to reset the values of the index and then accessing at index 0 ??
This is a case where I will always have only ONE item in the collection but the index at could be different so I can't use the [0] index by default.

```<code>//returns all items with 'item_color_id" = 1

$item = Item::where(//some constraints);

$filtered = $item->filter(function ($i) {
                return $i->item_color_id == 1;
            });

if (count($filtered)) {

    //need to access a single data inside the collection
    // like for example 'item_brand_id'
    //I can do it like this:

    $filtered = $filtered->values();

    $item_brand_id = $filtered[0]['item_brand_id'];

    //but what sense does it have?? how can we access 'item_brand_id'
    //from $filtered without resetting the indexes?

}
</code>```

it doesn't make any sense to me that we don't have a method to access the data directly, or if we have it I missed it.
For example I coould use max() or min() on $filtered like this:

```<code>$max_brand_id = $filtered->max('item_brand_id');
</code>```

It doesn't make any sense to find the max id in this case I know, but it shows that we can find the data in one passage.
I tried only('item_brand_id); but that returns empty while the data is there.

答:
filter() is used when you want a collection of matching elements, even if that only results in one element.

If you know that you only want one element that matches a truth test, use first() instead. It has the same signature.

```<code>Item::where(...)->get()->first(function ($item) {
    return $item->item_color_id == 1;
})->get('item_brand_id');
</code>```

Body:
I don't get this, I have a collection of items.
The collection contains in this case one and only one item at index 1 as it was filtered from a bigger collection.
The point is how do I get the only piece of data I need without having to reset the values of the index and then accessing at index 0 ??
This is a case where I will always have only ONE item in the collection but the index at could be different so I can't use the [0] index by default.

//returns all items with 'item_color_id" = 1

$item = Item::where(//some constraints);

$filtered = $item->filter(function ($i) {
                return $i->item_color_id == 1;
            });

if (count($filtered)) {

    //need to access a single data inside the collection
    // like for example 'item_brand_id'
    //I can do it like this:

    $filtered = $filtered->values();

    $item_brand_id = $filtered[0]['item_brand_id'];

    //but what sense does it have?? how can we access 'item_brand_id'
    //from $filtered without resetting the indexes?

}

it doesn't make any sense to me that we don't have a method to access the data directly, or if we have it I missed it.
For example I coould use max() or min() on $filtered like this:

$max_brand_id = $filtered->max('item_brand_id');

It doesn't make any sense to find the max id in this case I know, but it shows that we can find the data in one passage.
I tried only('item_brand_id); but that returns empty while the data is there.

Body:
filter() is used when you want a collection of matching elements, even if that only results in one element.

If you know that you only want one element that matches a truth test, use first() instead. It has the same signature.

Item::where(...)->get()->first(function ($item) {
    return $item->item_color_id == 1;
})->get('item_brand_id');


问:
How to setup domain model as actor?
I'm fairly new to both Scala and Akka and I'm trying to figure out how you would create a proper domain model, which also is an Actor.

Let's imagine we have a simple business case where you can open a new Bank Account. Let's say that one of the rules is that you can only create one bank account per last name (not realistic, but just for the sake of simplicity). My first approach, without applying any business rules, would look something like this:

```<code>object Main {
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem("accout")
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher
    val account = system.actorOf(Props[Account])
    account ! CreateAccount("Doe")
  }
}

case class CreateAccount(lastName: String)

class Account extends Actor {

  var lastName: String = null

  override def receive: Receive = {
    case createAccount: CreateAccount =>
      this.lastName = lastName
  }
}
</code>```

Eventually you would persist this data somewhere. However, when adding the rule that there can only be one Bank Account per last name, a query to some data storage needs to be done. Let's say we put that logic inside a repository and the repository eventually returns an Account, we get to the problem where Account isn't an Actor anymore, since the repository won't be able to create Actors.

This is definitely a wrong implementation and not how Actors should be used. My question is, what are ways to solve these kind of problems? I am aware that my knowledge of Akka is not on a decent level yet, so it might be a weird/stupid formulated question.

答:
General Design

Actors should generally be simple dispatchers to business logic and contain as little functionality as possible.  Think of Actors as similar to a Future; when you want concurrency in scala you don't extend the Future class, you just use Future functionality around your existing logic.

Limiting your Actors to bare-bones responsibility has several advantages:

Testing the code can be done without having to construct ActorSystems, probes, ActorRefs, etc...

The business logic can easily be transplanted to other asynchronous libraries, e.g. Futures and akka streams.

It's easier to create a "proper domain model" with plain old classes and functions than it is with Actors.

Placing business logic in Actors naturally emphasizes a more object oriented code/system design rather than a functional approach (we picked scala for a reason).

Business Logic (No Akka)

Here we will setup all of the domain specific logic without using any akka related "stuff".

```<code>object BusinessLogicDomain {

  type FirstName = String
  type LastName = String

  type Balance = Double

  val defaultBalance : Balance = 0.0

  case class Account(firstName : FirstName,
                     lastName : LastName,
                     balance : Balance = defaultBalance)
</code>```

Lets model your account directory as a HashMap:

```<code>  type AccountDirectory = HashMap[LastName, Account]

  val emptyDirectory : AccountDirectory = HashMap.empty[LastName, Account]
</code>```

We can now create a function that matches your requirements for distinct account per last name:

```<code>  val addAccount : (AccountDirectory, Account) => AccountDirectory =
    (accountDirectory, account) =>
      if(accountDirectory contains account.lastName)
        accountDirectory
      else
        accountDirectory + (account.lastName -> account)

}//end object BusinessLogicDomain
</code>```

Repository (Akka)

Now that the unpolluted business code is complete, and isolated, we can add the concurrency layer on top of the foundational logic.

We can use the become functionality of Actors to store the state and respond to requests:

```<code>import BusinessLogicDomain.{Account, AccountDirectory, emptyDirectory, addAccount}

case object QueryAccountDirectory

class RepoActor(accountDirectory : AccountDirectory = emptyDirectory) extends Actor {

  val statefulReceive : AccountDirectory => Receive =
    currentDirectory => {
      case account : Account     =>
        context become statefulReceive(addAccount(currentDirectory, account))
      case QueryAccountDirectory =>
        sender ! currentDirectory
    }

  override def receive : Receive = statefulReceive(accountDirectory)
}
</code>```

Title: How to setup domain model as actor?

Body:
I'm fairly new to both Scala and Akka and I'm trying to figure out how you would create a proper domain model, which also is an Actor.

Let's imagine we have a simple business case where you can open a new Bank Account. Let's say that one of the rules is that you can only create one bank account per last name (not realistic, but just for the sake of simplicity). My first approach, without applying any business rules, would look something like this:

object Main {
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem("accout")
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher
    val account = system.actorOf(Props[Account])
    account ! CreateAccount("Doe")
  }
}

case class CreateAccount(lastName: String)

class Account extends Actor {

  var lastName: String = null

  override def receive: Receive = {
    case createAccount: CreateAccount =>
      this.lastName = lastName
  }
}

Eventually you would persist this data somewhere. However, when adding the rule that there can only be one Bank Account per last name, a query to some data storage needs to be done. Let's say we put that logic inside a repository and the repository eventually returns an Account, we get to the problem where Account isn't an Actor anymore, since the repository won't be able to create Actors.

This is definitely a wrong implementation and not how Actors should be used. My question is, what are ways to solve these kind of problems? I am aware that my knowledge of Akka is not on a decent level yet, so it might be a weird/stupid formulated question.

Body:
General Design

Actors should generally be simple dispatchers to business logic and contain as little functionality as possible.  Think of Actors as similar to a Future; when you want concurrency in scala you don't extend the Future class, you just use Future functionality around your existing logic.

Limiting your Actors to bare-bones responsibility has several advantages:

Testing the code can be done without having to construct ActorSystems, probes, ActorRefs, etc...

The business logic can easily be transplanted to other asynchronous libraries, e.g. Futures and akka streams.

It's easier to create a "proper domain model" with plain old classes and functions than it is with Actors.

Placing business logic in Actors naturally emphasizes a more object oriented code/system design rather than a functional approach (we picked scala for a reason).

Business Logic (No Akka)

Here we will setup all of the domain specific logic without using any akka related "stuff".

object BusinessLogicDomain {

  type FirstName = String
  type LastName = String

  type Balance = Double

  val defaultBalance : Balance = 0.0

  case class Account(firstName : FirstName,
                     lastName : LastName,
                     balance : Balance = defaultBalance)

Lets model your account directory as a HashMap:

  type AccountDirectory = HashMap[LastName, Account]

  val emptyDirectory : AccountDirectory = HashMap.empty[LastName, Account]

We can now create a function that matches your requirements for distinct account per last name:

  val addAccount : (AccountDirectory, Account) => AccountDirectory =
    (accountDirectory, account) =>
      if(accountDirectory contains account.lastName)
        accountDirectory
      else
        accountDirectory + (account.lastName -> account)

}//end object BusinessLogicDomain

Repository (Akka)

Now that the unpolluted business code is complete, and isolated, we can add the concurrency layer on top of the foundational logic.

We can use the become functionality of Actors to store the state and respond to requests:

import BusinessLogicDomain.{Account, AccountDirectory, emptyDirectory, addAccount}

case object QueryAccountDirectory

class RepoActor(accountDirectory : AccountDirectory = emptyDirectory) extends Actor {

  val statefulReceive : AccountDirectory => Receive =
    currentDirectory => {
      case account : Account     =>
        context become statefulReceive(addAccount(currentDirectory, account))
      case QueryAccountDirectory =>
        sender ! currentDirectory
    }

  override def receive : Receive = statefulReceive(accountDirectory)
}


问:
Android: Reset Parse backend object everyday, week and month
I am trying to reset parse int objects everyday, week and month using Alarm Manager. I have three objects dayObject, weekObject and monthObject which runs and updates the text views. But the app is crashing with error Value May Not be Null. Please help!!!

onCreate():

```<code>Intent iToday = new Intent(this, TodayReset.class);
iToday.putExtra("createdAt", createdAt.getTime());
piToday = PendingIntent.getBroadcast(this, 0, iToday, 0);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, today.getTime(), AlarmManager.INTERVAL_DAY, piToday);
</code>```

On Receive(): I am getting today, week and month dates from Calendar. Then I check the conditions and update the Parse backend.

```<code>ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Pattern");

query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());

query.orderByDescending("createdAt");

query.getFirstInBackground(new GetCallback<ParseObject>() {
   @Override
   public void done(ParseObject object, ParseException e) {
     if(e == null && object != null) {
       totalValue = object.getInt("totalValue");
       weekValue = object.getInt("weekValue");
       monthValue = object.getInt("monthValue");
     } else {
       Log.i("RetErr", e.getMessage());
     }
   }
});

ParseObject pattern = new ParseObject("Pattern");

pattern.put("username", ParseUser.getCurrentUser().getUsername());

pattern.put("totalValue", totalValue);
pattern.put("todayValue", 0);
pattern.put("weekValue", weekValue);
pattern.put("monthValue", monthValue);

pattern.save();
</code>```

I am repeating the same for week and month. I am retrieving all objects because when I save only a particular object, then the other objects show not defined. Hence I retrieve the old value and save it again.

答:
Move the creation of the new Parse Object inside done() like below. Because the query is done in the background is doesnt finish before you try and use totalValue etc.</p>

```<code>ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Pattern");

        query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());

        query.orderByDescending("createdAt");

        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {

                if(e == null && object != null) {

                    totalValue = object.getInt("totalValue");
                    weekValue = object.getInt("weekValue");
                    monthValue = object.getInt("monthValue");
                    ParseObject pattern = new ParseObject("Pattern");

        pattern.put("username", ParseUser.getCurrentUser().getUsername());

        pattern.put("totalValue", totalValue);
        pattern.put("todayValue", 0);
        pattern.put("weekValue", weekValue);
        pattern.put("monthValue", monthValue);

            pattern.save();

                } else {

                    Log.i("RetErr", e.getMessage());

                }

            }

        });
</code>```

Body:
I am trying to reset parse int objects everyday, week and month using Alarm Manager. I have three objects dayObject, weekObject and monthObject which runs and updates the text views. But the app is crashing with error Value May Not be Null. Please help!!!

onCreate():

Intent iToday = new Intent(this, TodayReset.class);
iToday.putExtra("createdAt", createdAt.getTime());
piToday = PendingIntent.getBroadcast(this, 0, iToday, 0);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, today.getTime(), AlarmManager.INTERVAL_DAY, piToday);

On Receive(): I am getting today, week and month dates from Calendar. Then I check the conditions and update the Parse backend.

ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Pattern");

query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());

query.orderByDescending("createdAt");

query.getFirstInBackground(new GetCallback<ParseObject>() {
   @Override
   public void done(ParseObject object, ParseException e) {
     if(e == null && object != null) {
       totalValue = object.getInt("totalValue");
       weekValue = object.getInt("weekValue");
       monthValue = object.getInt("monthValue");
     } else {
       Log.i("RetErr", e.getMessage());
     }
   }
});

ParseObject pattern = new ParseObject("Pattern");

pattern.put("username", ParseUser.getCurrentUser().getUsername());

pattern.put("totalValue", totalValue);
pattern.put("todayValue", 0);
pattern.put("weekValue", weekValue);
pattern.put("monthValue", monthValue);

pattern.save();

I am repeating the same for week and month. I am retrieving all objects because when I save only a particular object, then the other objects show not defined. Hence I retrieve the old value and save it again.

Body:
Move the creation of the new Parse Object inside done() like below. Because the query is done in the background is doesnt finish before you try and use totalValue etc.

ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Pattern");

        query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());

        query.orderByDescending("createdAt");

        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {

                if(e == null && object != null) {

                    totalValue = object.getInt("totalValue");
                    weekValue = object.getInt("weekValue");
                    monthValue = object.getInt("monthValue");
                    ParseObject pattern = new ParseObject("Pattern");

        pattern.put("username", ParseUser.getCurrentUser().getUsername());

        pattern.put("totalValue", totalValue);
        pattern.put("todayValue", 0);
        pattern.put("weekValue", weekValue);
        pattern.put("monthValue", monthValue);

            pattern.save();

                } else {

                    Log.i("RetErr", e.getMessage());

                }

            }

        });


问:
Why is User (as in User.Identity.Name) null in my abstract base controller?
I was asking a related question but messed the title up and no-one would understand it. Since I am able now to ask the question more precisely, I decided to reformulate it in a new question and close the old one. Sorry for that.

So what I want to do is passing data (my custom user's nickname as stored in the db) to the LoginUserControl. This login gets rendered from the master page via Html.RenderPartial(), so what I really need to do is making sure that, say ViewData["UserNickname"] is present on every call. But I don't want to populate ViewData["UserNickname"] in each and every action of every controller, so I decided to use this approach and create an abstract base controller which will do the work for me, like so:

```<code>public abstract class ApplicationController : Controller
    {
        private IUserRepository _repUser;

        public ApplicationController()
        {
            _repUser = RepositoryFactory.getUserRepository();
            var loggedInUser = _repUser.FindById(User.Identity.Name); //Problem!
            ViewData["LoggedInUser"] = loggedInUser;
        }
    }
</code>```

This way, whatever my deriving Controller does, the user information will already be present.

So far, so good. Now for the problem:

I can't call User.Identity.Name because User is already null. This is not the case in all of my deriving controllers, so this is specific for the abstract base controller.

I am setting the User.Identity.Name via FormsAuthentication at another place in the code, but I think this can't be the problem - afaik User.Identity.Name can be null, but not User itself.

It looks to me like the HttpContext is not available (since also null ;-) and that I am missing a simple yet important point here. Can anyone give me some hints? I would really appreciate it.

答:
Thanks Raimond. I was too tired to see the obvious.
@Keeney: Yes the context is always null. Raimond pointed out why. Thanks anyway, I didn't see why too :-)

My current working solution (albeit not what I wanted) is a Attribute that I use to decorate all my controller actions. Here is the implementation:

```<code>public class MasterPageDataAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            IUserRepository _repUser = RepositoryFactory.getUserRepository();
            IPrincipal siteUser = filterContext.Controller.ControllerContext.HttpContext.User;
            User loggedInUser = null;

            if (siteUser == null || siteUser.Identity.Name == null)
            {
                //do nothing
            }
            else
            {
                loggedInUser = _repUser.findUserById(siteUser.Identity.Name);
            }
            filterContext.Controller.ViewData["LoggedInUser"] = loggedInUser ?? new User { Nickname = "Guest" };
        }
    }
</code>```

I will be looking into how to get that code executed in a way that follows the DRY principle, since using attributes for that definitely means repeating oneself. Maybe some sort of interceptor (interesting idea) or hook might help.

Cheers for that.

OwnerDisplayName: Masterfu

Body:
I was asking a related question but messed the title up and no-one would understand it. Since I am able now to ask the question more precisely, I decided to reformulate it in a new question and close the old one. Sorry for that.

So what I want to do is passing data (my custom user's nickname as stored in the db) to the LoginUserControl. This login gets rendered from the master page via Html.RenderPartial(), so what I really need to do is making sure that, say ViewData["UserNickname"] is present on every call. But I don't want to populate ViewData["UserNickname"] in each and every action of every controller, so I decided to use this approach and create an abstract base controller which will do the work for me, like so:

public abstract class ApplicationController : Controller
    {
        private IUserRepository _repUser;

        public ApplicationController()
        {
            _repUser = RepositoryFactory.getUserRepository();
            var loggedInUser = _repUser.FindById(User.Identity.Name); //Problem!
            ViewData["LoggedInUser"] = loggedInUser;
        }
    }

This way, whatever my deriving Controller does, the user information will already be present.

So far, so good. Now for the problem:

I can't call User.Identity.Name because User is already null. This is not the case in all of my deriving controllers, so this is specific for the abstract base controller.

I am setting the User.Identity.Name via FormsAuthentication at another place in the code, but I think this can't be the problem - afaik User.Identity.Name can be null, but not User itself.

It looks to me like the HttpContext is not available (since also null ;-) and that I am missing a simple yet important point here. Can anyone give me some hints? I would really appreciate it.

Body:
Thanks Raimond. I was too tired to see the obvious.
@Keeney: Yes the context is always null. Raimond pointed out why. Thanks anyway, I didn't see why too :-)

My current working solution (albeit not what I wanted) is a Attribute that I use to decorate all my controller actions. Here is the implementation:

public class MasterPageDataAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            IUserRepository _repUser = RepositoryFactory.getUserRepository();
            IPrincipal siteUser = filterContext.Controller.ControllerContext.HttpContext.User;
            User loggedInUser = null;

            if (siteUser == null || siteUser.Identity.Name == null)
            {
                //do nothing
            }
            else
            {
                loggedInUser = _repUser.findUserById(siteUser.Identity.Name);
            }
            filterContext.Controller.ViewData["LoggedInUser"] = loggedInUser ?? new User { Nickname = "Guest" };
        }
    }

I will be looking into how to get that code executed in a way that follows the DRY principle, since using attributes for that definitely means repeating oneself. Maybe some sort of interceptor (interesting idea) or hook might help.

Cheers for that.


问:
Getting HTML form elements to be in line
I am using some bootstrap elements along with some buttons and have issues getting them all to show up in one line! I have something like:

```<code><span><input class="form-control" id="filename" value="Select a ZIP file to upload..." disabled style="display: inline" ></span>
<span><input type="button" id="get_file" class="btn btn-primary" value="Browse" style="display: inline"></span>
<span><input type="button" id="get_file" class="btn btn-success" value="Upload" style="display: inline"></span>
<input type="file" id="my_file" accept=".zip" style="display: none">
</code>```

This should basically show a text field with two buttons and I get an output like:

What i would like is for the two buttons to be on the same row as well...

答:
Try this code:</p>

```<code><form class="form-horizontal form-inline">
        <span><input class="form-control" id="filename" value="Select a ZIP file to upload..." disabled ></span>
        <span><input type="button" id="get_file" class="btn btn-primary" value="Browse"></span>
        <span><input type="button" id="get_file" class="btn btn-success" value="Upload"></span>
        <input type="file" id="my_file" accept=".zip" style="display: none" >
    </form>
</code>```

Body:
I am using some bootstrap elements along with some buttons and have issues getting them all to show up in one line! I have something like:

<input class="form-control" id="filename" value="Select a ZIP file to upload..." disabled style="display: inline" >
<input type="button" id="get_file" class="btn btn-primary" value="Browse" style="display: inline">
<input type="button" id="get_file" class="btn btn-success" value="Upload" style="display: inline">
<input type="file" id="my_file" accept=".zip" style="display: none">

This should basically show a text field with two buttons and I get an output like:

What i would like is for the two buttons to be on the same row as well...

Body:
Try this code:

<form class="form-horizontal form-inline">
        <span><input class="form-control" id="filename" value="Select a ZIP file to upload..." disabled ></span>
        <span><input type="button" id="get_file" class="btn btn-primary" value="Browse"></span>
        <span><input type="button" id="get_file" class="btn btn-success" value="Upload"></span>
        <input type="file" id="my_file" accept=".zip" style="display: none" >
    </form>


答:
You could change your database query to just return one element. If the result is always just one, there is no need to load an entire collection.</p>

```<code>$item = Item::where(/*some constraints*/)->where('item_color_id', 1)->first();
if (isset($item))
    echo $item->item_brand_id;
</code>```

Title: getting only one data from laravel collection seems difficult

Body:
You could change your database query to just return one element. If the result is always just one, there is no need to load an entire collection.

$item = Item::where(/*some constraints*/)->where('item_color_id', 1)->first();
if (isset($item))
    echo $item->item_brand_id;


问:
How to use the HWUT unit test tool with java files
I've been using the HWUT unit test tool with C and python and now I'm trying it with Java. In python I can tell HWUT to run all .py files with python if I specify a "hwut-info.dat" file as

```<code>Some title
----------------------
python *.py
</code>```

But for Java I can't do that, because java expects the file names without extension. The java compiler shall consider the '*.java' files but it does
expect the file stem as input, i.e. java FileStem in order to treat FileStem.java.

答:
Later HWUT versions (> 0.28.0) will provide some sophisticated functionality to
pass information about path names, i.e. in those (at the time of this writing)
'future versions' the usage of an extension-less java file can be specified as

```<code>  java -cp mypackages:. {{file.java%}}
</code>```

For the time being, you need a script to run your test, such as 'runjava.sh':

```<code>#! /usr/bin/env bash
java -cp ../../package:. $(basename ${1%.*}) ${@:2}
</code>```

It calls the java interpreter, cuts the extension from the filename and passes
all remaining arguments to the file to be executed. In your 'hwut-info.dat'
file you need to specify:

```<code>My title
--------------------------------------------------------
bash ./runjava.sh *.class
</code>```

This lets HWUT search for *.class files in the current directory. The
'runjava.sh', though, omits the extension and calls 'java' with the file stem.
Inside your Java test application you reflect on the command line like:

```<code>public class Mine {
    public static void main(String[] args) {
        if( args.length >= 1 && args[0].equals("--hwut-info") ) {
            System.out.println("Title ...");
            ...
        }
    }
    ...
}
</code>```

Body:
I've been using the HWUT unit test tool with C and python and now I'm trying it with Java. In python I can tell HWUT to run all .py files with python if I specify a "hwut-info.dat" file as

Some title
----------------------
python *.py

But for Java I can't do that, because java expects the file names without extension. The java compiler shall consider the '*.java' files but it does
expect the file stem as input, i.e. java FileStem in order to treat FileStem.java.

Body:
Later HWUT versions (> 0.28.0) will provide some sophisticated functionality to
pass information about path names, i.e. in those (at the time of this writing)
'future versions' the usage of an extension-less java file can be specified as

  java -cp mypackages:. {{file.java%}}

For the time being, you need a script to run your test, such as 'runjava.sh':

#! /usr/bin/env bash
java -cp ../../package:. $(basename ${1%.*}) ${@:2}

It calls the java interpreter, cuts the extension from the filename and passes
all remaining arguments to the file to be executed. In your 'hwut-info.dat'
file you need to specify:

My title
--------------------------------------------------------
bash ./runjava.sh *.class

This lets HWUT search for *.class files in the current directory. The
'runjava.sh', though, omits the extension and calls 'java' with the file stem.
Inside your Java test application you reflect on the command line like:

public class Mine {
    public static void main(String[] args) {
        if( args.length >= 1 && args[0].equals("--hwut-info") ) {
            System.out.println("Title ...");
            ...
        }
    }
    ...
}


问:
Should I reinitialize critical sections in Windows?
I use critical sections a lot in Windows programming.
As far as I know, a certain "counter" increases every a critical section is being entered and/or leaved.

I don't need this kind of counter, however I wonder if it's safe to initialize a critical section once for my entire application and then leave it initialized until my program exits.

Should I reinitialize (Delete and Initialize) critical sections every time some tasks have been completed and start over or is it safe to "reuse" already initialized critical sections?

Is there a limit on how often a critical section can be entered/leaved?

Also:
With every enter/leave - will there be more and more memory consumption?

答: you need initialize critical sections only once. you not need reinitialize it. no any limitation how many time and threads will be enter/leave CS. and of course no more memory will be used after you initialize critical section</p>


问:
Creating a folder or file in External microSD card
I have searched everywhere for the answer to my problem and i did found a large amount of answer which should have solved my it but yet i can't solved it.

My Goal is to put a SD card with 128GB and to write files into it (csv or text).
I'm trying to open a file or a folder in my microSD card but it do not create it.
also the file is not created. I think the Path that i get from:

```<code>Environment.getExternalStorageDirectory()
</code>```

is not The SD Card Path.

here is my java code :

```<code>package com.example.thermie.test2;

import android.Manifest;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

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

// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;

            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();

            String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
            //create folder
            File folder = new File(dir); //folder name
            boolean result = folder.mkdirs();

            //create file
            File file = new File(dir, "filename.txt");

            if (result){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(dir);
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}
</code>```

My dir is : /storage/emulated/0/myDirectory
Which is not in my SD card , it's the internal memory in an directory without any access.

my results of :

```<code>boolean result = folder.mkdirs();
</code>```

is not true. so no folder opens , i also tried :

```<code>boolean result = folder.mkdir();
</code>```

and my Toasts says:

Read and Write

23 (API)

mounted (sd mounted)

Phone galaxy s5.
andorid version 6.0.1 Marshmallow.

Here is my manifeset :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.thermie.test2">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

</manifest>
</code>```

Hope it is detail enough.
Thanks you all.

答:
have you tried using the
Enviroment.getExternalStoragePublicDirectory()?
As was mentioned above, you can also use
    getExternalFilesDirs()
on context, however, this might now work on some devices.  refer to here for what I am referring to.

Body:
I have searched everywhere for the answer to my problem and i did found a large amount of answer which should have solved my it but yet i can't solved it.

My Goal is to put a SD card with 128GB and to write files into it (csv or text).
I'm trying to open a file or a folder in my microSD card but it do not create it.
also the file is not created. I think the Path that i get from:

Environment.getExternalStorageDirectory()

is not The SD Card Path.

here is my java code :

package com.example.thermie.test2;

import android.Manifest;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

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

// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;

            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();

            String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
            //create folder
            File folder = new File(dir); //folder name
            boolean result = folder.mkdirs();

            //create file
            File file = new File(dir, "filename.txt");

            if (result){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(dir);
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}

My dir is : /storage/emulated/0/myDirectory
Which is not in my SD card , it's the internal memory in an directory without any access.

my results of :

boolean result = folder.mkdirs();

is not true. so no folder opens , i also tried :

boolean result = folder.mkdir();

and my Toasts says:

Read and Write

23 (API)

mounted (sd mounted)

Phone galaxy s5.
andorid version 6.0.1 Marshmallow.

Here is my manifeset :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.thermie.test2">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

</manifest>

Hope it is detail enough.
Thanks you all.


问:
How to initialize correctly the zoom level in a SharpMap object?
I'm working with a MapBox object from SharpMap in a Windows Forms C# app and I can't seem to find how to make the zoom level work. The MapBox object is in a TabControl object.

This class is called after the main InitializeComponent() call in my app.

```<code>public void InitializeMap(SharpMap.Forms.MapBox mapBox)
        {
            mapBox.Map.BackgroundLayer.Add(new SharpMap.Layers.TileAsyncLayer(
                new BruTile.Web.OsmTileSource(), "OSM"));

            mapBox.Map.Zoom = 10; //
            mapBox.Refresh();
        }
</code>```

Whatever value written for the mapBox.Map.Zoom attribute, it's always the same high zoom level.

On the other hand, if I use mapBox.Map.ZoomToExtents() call, it zooms to the extents of the OSM layer correctly.

I suppose I'm doing wrong a simple thing, but I can't seem to find what is the problem.

答:
mapBox.Map.Zoom is always the same as mapBox.Map.Envelope.Width.

Instead of just setting the zoom like that, try using mapBox.Map.ZoomToBox(new GeoAPI.Geometries.Envelope(-5.0, 5.0, -5.0, 5.0)). The map will be positioned and zoomed so that the entirety of the envelope is within the map.

The envelope in my example has a width of 10, but if your map is wider than it is high mapBox.Map.Zoom will be greater than that, since (as I stated above) its value is the same as the width of the visible part of the map.

Body:
I'm working with a MapBox object from SharpMap in a Windows Forms C# app and I can't seem to find how to make the zoom level work. The MapBox object is in a TabControl object.

This class is called after the main InitializeComponent() call in my app.

public void InitializeMap(SharpMap.Forms.MapBox mapBox)
        {
            mapBox.Map.BackgroundLayer.Add(new SharpMap.Layers.TileAsyncLayer(
                new BruTile.Web.OsmTileSource(), "OSM"));

            mapBox.Map.Zoom = 10; //
            mapBox.Refresh();
        }

Whatever value written for the mapBox.Map.Zoom attribute, it's always the same high zoom level.

On the other hand, if I use mapBox.Map.ZoomToExtents() call, it zooms to the extents of the OSM layer correctly.

I suppose I'm doing wrong a simple thing, but I can't seem to find what is the problem.


问:
Why can I see a table in user_tables but can't find it in dba_tables?
I have created a table with the "create table as (select.....)" statement by the user called "X", which is a copy of another table, from a user called "Y".

When I list all the tables from dba_tables, owned by X, there isn't anything, but if I write "select tablespace_name, table_name from user_tables;" I can see the new tabble owned by me (the X user).

答: I write the X user's name with different case letters, but in search, I must write it all in upper case letters. </p>


问:
Displaying custom checkout billing field on email notifications
In WooCommerce, I want to add some custom fields on checkout which will be displayed under the billing section on the e-mail confirmation.
My custom fields and their values, shown on the checkout form and on the order page on back end (WooCommerce -> Orders). So far everything works great.

The problem is that the e-mail that i receive does not contain the custom fields and their values.

Code shown below:

```<code>    add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
    function custom_override_checkout_fields( $fields ) {
        $fields['billing']['billing_field_testing'] = array(
            'label'     => __('TestingField', 'woocommerce'),
            'placeholder'   => _x('TestingField', 'placeholder', 'woocommerce'),
            'required'  => false,
            'class'     => array('form-row-wide'),
            'clear'     => true
             );
        return $fields;
    }

    add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
    function my_custom_checkout_field_display_admin_order_meta($order)
    {
        echo '<p><strong>'.__('TestingField').':</strong> ' . get_post_meta( $order->id, '_billing_field_testing', true ) . '</p>';
    }
</code>```

Please help.

Thanks in advance

答:
Updated: To display your custom checkout field in email notifications below the billing address, use this function hooked in woocommerce_email_customer_details action hook with a priority above 20:

```<code>add_action('woocommerce_email_customer_details','add_custom_checkout_field_to_emails_notifications', 25, 4 );
function add_custom_checkout_field_to_emails_notifications( $order, $sent_to_admin, $plain_text, $email ) {

    $output = '';
    $billing_field_testing = get_post_meta( $order->id, '_billing_field_testing', true );

    if ( !empty($billing_field_testing) )
        $output .= '<div><strong>' . __( "Some text:", "woocommerce" ) . '</strong> <span class="text">' . $billing_field_testing . '</span></div>';

    echo $output;
}
</code>```

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Body:
In WooCommerce, I want to add some custom fields on checkout which will be displayed under the billing section on the e-mail confirmation.
My custom fields and their values, shown on the checkout form and on the order page on back end (WooCommerce -> Orders). So far everything works great.

The problem is that the e-mail that i receive does not contain the custom fields and their values.

Code shown below:

    add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
    function custom_override_checkout_fields( $fields ) {
        $fields['billing']['billing_field_testing'] = array(
            'label'     => __('TestingField', 'woocommerce'),
            'placeholder'   => _x('TestingField', 'placeholder', 'woocommerce'),
            'required'  => false,
            'class'     => array('form-row-wide'),
            'clear'     => true
             );
        return $fields;
    }

    add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
    function my_custom_checkout_field_display_admin_order_meta($order)
    {
        echo '
'.__('TestingField').': ' . get_post_meta( $order->id, '_billing_field_testing', true ) . '
';
    }

Please help.

Thanks in advance

Body:
Updated: To display your custom checkout field in email notifications below the billing address, use this function hooked in woocommerce_email_customer_details action hook with a priority above 20:

add_action('woocommerce_email_customer_details','add_custom_checkout_field_to_emails_notifications', 25, 4 );
function add_custom_checkout_field_to_emails_notifications( $order, $sent_to_admin, $plain_text, $email ) {

    $output = '';
    $billing_field_testing = get_post_meta( $order->id, '_billing_field_testing', true );

    if ( !empty($billing_field_testing) )
        $output .= '<div><strong>' . __( "Some text:", "woocommerce" ) . '</strong> <span class="text">' . $billing_field_testing . '</span></div>';

    echo $output;
}

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.


问:
Not sql files detected when I run flyway info, and when I run flyway migrate files undetected jumping
I'm trying flyway.
I have some files with names VX_XX_X__Description.
Not sql files detected when I run flyway info, and when I run flyway migrate files undetected jumping.

Example

V1_1_1__desc1.sql
V1_1_2__desc2.sql
V1_1_3__desc3.sql

When I run only detects some flyway info

V1_1_1__desc1.sql
V1_1_3__desc3.sql

What are the reasons for not detecting the sql files?

答:
I found this question solving same problem.

In my case I added new sql file only to src directory but I forgot to call maven build. (We have flyway configured to seek sql files in target directory.)


问:
Invalid JSON: undefined in CouchDB with python sockets
I wrote this python script which should compose an http request as a string and send it on a socket connected to couchDB:

```<code>import socket
import json

DB_IP = '127.0.0.1'
DB_PORT = 5984

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((DB_IP, DB_PORT))

db_name = 'temperatures'
doc_id = 'today'

request = "PUT /" + db_name + "/" + doc_id + " HTTP/1.1\n"
request += "Content-Type: application/json\n\n"
request += json.dumps({'min_t': 10, 'max_t': 20})

sock.sendall(request)

result = sock.recv(4096)

print result
</code>```

the output is:

```<code>HTTP/1.1 400 Bad Request
Server: CouchDB/1.6.1 (Erlang OTP/19)
Date: Mon, 27 Mar 2017 20:07:04 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 48
Cache-Control: must-revalidate
</code>```

the couchdb log is:

```<code>[debug] [<0.575.0>] 'PUT' /temperatures/today {1,1} from "127.0.0.1"
Headers: [{'Content-Type',"application/json"}]
[debug] [<0.575.0>] OAuth Params: []
[error] [<0.575.0>] attempted upload of invalid JSON (set log_level to debug to log it)
[debug] [<0.575.0>] Invalid JSON: undefined
[info] [<0.575.0>] 127.0.0.1 - - PUT /temperatures/today 400
[debug] [<0.575.0>] httpd 400 error response:
{"error":"bad_request","reason":"invalid_json"}
</code>```

I bet the error is in the http request string because the exact same query works fine with Postman, but I can't figure out the problem.

答:
You need to include the Content length header, as it seems CouchDB can't guess the length of your JSON body.</p>

```<code>json_data = '{"min_t": 10, "max_t": 20}'
request = "PUT /" + db_name + "/" + doc_id + " HTTP/1.1\n"
request += "Accept: application/json\n"
request += "Content-Length: " + str(len(json_data)) + "\n"
request += "Content-Type: application/json\n\n"
request += json_data
</code>```

Body:
I wrote this python script which should compose an http request as a string and send it on a socket connected to couchDB:

import socket
import json

DB_IP = '127.0.0.1'
DB_PORT = 5984

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((DB_IP, DB_PORT))

db_name = 'temperatures'
doc_id = 'today'

request = "PUT /" + db_name + "/" + doc_id + " HTTP/1.1\n"
request += "Content-Type: application/json\n\n"
request += json.dumps({'min_t': 10, 'max_t': 20})

sock.sendall(request)

result = sock.recv(4096)

print result

the output is:

HTTP/1.1 400 Bad Request
Server: CouchDB/1.6.1 (Erlang OTP/19)
Date: Mon, 27 Mar 2017 20:07:04 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 48
Cache-Control: must-revalidate

the couchdb log is:

[debug] [<0.575.0>] 'PUT' /temperatures/today {1,1} from "127.0.0.1"
Headers: [{'Content-Type',"application/json"}]
[debug] [<0.575.0>] OAuth Params: []
[error] [<0.575.0>] attempted upload of invalid JSON (set log_level to debug to log it)
[debug] [<0.575.0>] Invalid JSON: undefined
[info] [<0.575.0>] 127.0.0.1 - - PUT /temperatures/today 400
[debug] [<0.575.0>] httpd 400 error response:
{"error":"bad_request","reason":"invalid_json"}

I bet the error is in the http request string because the exact same query works fine with Postman, but I can't figure out the problem.

Body:
You need to include the Content length header, as it seems CouchDB can't guess the length of your JSON body.

json_data = '{"min_t": 10, "max_t": 20}'
request = "PUT /" + db_name + "/" + doc_id + " HTTP/1.1\n"
request += "Accept: application/json\n"
request += "Content-Length: " + str(len(json_data)) + "\n"
request += "Content-Type: application/json\n\n"
request += json_data


问:
When Managed Bean creates and property of the beans creates?
In our application we use jsf,we have
to redirect the user to home page
 after their session will be expired.For that i need a  path of the home page which i kept in my logout managed bean as a managed bean property.But after session expired if i try to access that it  will arise null pointer exception(managed bean becomes null).Then
i have decide to try alternative (i.e)create logout class manually and try to access the property, at that time the property which i wants to access is become null.How can i access
that property?
Please help me.
Thanks in advance.</p>

答:
Correct way of doing this is declaring exception handler factory in faces-config.xml, then implementing the factory by subclassing  javax.faces.context.ExceptionHandlerFactory, and then overriding handle() method in your implementation of javax.faces.context.ExceptionHandlerWrapper.
There you should analyze the exception for the ViewExpiredException class and redirect to your view expired page in that case.


问:
How to count sub data of customer in SQL
I have Customer table as following

```<code>CustomerId     CustomerName   CustomerEmail
1              AAA            AAA@AAA.com
2              BBB            BBB@BBB.BBB
</code>```

This is example data I have shown. Like this I have 50000 customer in customer table now their invoices are also stored in invoice table

```<code>InvoiceId      InvoiceAmount   InvoiceCustomerID
1              22.00           1
2              58.00           2
3              21.00           2
4              45.00           2
</code>```

Now I want to count the invoice for each customer when I show the customer listing, for example:

```<code>CustomerId     CustomerName   CustomerEmail  TotalInvoice
1              AAA            AAA@AAA.com    1
2              BBB            BBB@BBB.BBB    3
</code>```

I have used the following query but didnt worked

```<code>SELECT customer.*,COUNT(invoice.InvoiceId) FROM `customer` as customer INNER JOIN invoice as invoice ON customer.CustomerId= invoice.InvoiceCustomerID
</code>```

Can suggest any method to solve this ?

Also there is more then 5 lacks invoice so it's taking to much time to load.

答:
due to bulk data other queries was taking to much time to load

so I have settled the issue using following query

```<code>SELECT c.CustomerId,c.CustomerName,totalinvoice AS ttlinv FROM customer
as c LEFT JOIN (select COUNT(InvoiceId) as totalinvoice,InvoiceCustomerID
from invoice GROUP by InvoiceCustomerID) as io on io.InvoiceCustomerID=c.CustomerId
</code>```

Body:
I have Customer table as following

CustomerId     CustomerName   CustomerEmail
1              AAA            AAA@AAA.com
2              BBB            BBB@BBB.BBB

This is example data I have shown. Like this I have 50000 customer in customer table now their invoices are also stored in invoice table

InvoiceId      InvoiceAmount   InvoiceCustomerID
1              22.00           1
2              58.00           2
3              21.00           2
4              45.00           2

Now I want to count the invoice for each customer when I show the customer listing, for example:

CustomerId     CustomerName   CustomerEmail  TotalInvoice
1              AAA            AAA@AAA.com    1
2              BBB            BBB@BBB.BBB    3

I have used the following query but didnt worked

SELECT customer.*,COUNT(invoice.InvoiceId) FROM `customer` as customer INNER JOIN invoice as invoice ON customer.CustomerId= invoice.InvoiceCustomerID

Can suggest any method to solve this ?

Also there is more then 5 lacks invoice so it's taking to much time to load.

Body:
due to bulk data other queries was taking to much time to load

so I have settled the issue using following query

SELECT c.CustomerId,c.CustomerName,totalinvoice AS ttlinv FROM customer
as c LEFT JOIN (select COUNT(InvoiceId) as totalinvoice,InvoiceCustomerID
from invoice GROUP by InvoiceCustomerID) as io on io.InvoiceCustomerID=c.CustomerId


问:
OpenFileDialog throws "Attempted to read or write protected memory"
I face this error when I'm trying to browse files using OpenFileDialog1 in vb.net

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I'm using this code:

```<code>    Try
        OpenFileDialog1.Filter = "(*.jpg)|*.jpg"
        OpenFileDialog1.InitialDirectory = Nothing
        OpenFileDialog1.FileName = ""
        OpenFileDialog1.ShowDialog()
        If OpenFileDialog1.FileName > "" Then
            TextBox8.Text = OpenFileDialog1.FileName
            PictureBox1.Image = Image.FromFile(TextBox8.Text)
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
        Exit Sub
    End Try
</code>```

Everything works fine on my machine, but this error apears when run the app on the client machine!

Any ideas please?

答:
In my experience with this exception, there are highly two reasons for this issue:

This is the highly cause for your problem: always check your build platform targeting to match the assemblies you are calling, so it's a mixed platform issue as I think.

Always put the disposable components in the designer, or declare it as a private variable so it get's disposed with the form destructor called.

You can set the build option to set your target platform in the project settings dialog.

Body:
I face this error when I'm trying to browse files using OpenFileDialog1 in vb.net

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I'm using this code:

    Try
        OpenFileDialog1.Filter = "(*.jpg)|*.jpg"
        OpenFileDialog1.InitialDirectory = Nothing
        OpenFileDialog1.FileName = ""
        OpenFileDialog1.ShowDialog()
        If OpenFileDialog1.FileName > "" Then
            TextBox8.Text = OpenFileDialog1.FileName
            PictureBox1.Image = Image.FromFile(TextBox8.Text)
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
        Exit Sub
    End Try

Everything works fine on my machine, but this error apears when run the app on the client machine!

Any ideas please?


问:
Sorting of array by substrings
I need to sort array by substrings and also input missing parts.

Current version:

“K1\SK1”

“K1\SK2”

“K1\SK1\SSK1”

“K1\SK1\SSK2”

“K2”

“K2\SK1\SSK1”

“K2\SK1\SSK2”

Expected version:

“K1”

“K1\SK1”

“K1\SK1\SSK1”

“K1\SK1\SSK2”

“K1\SK2”

“K2”

“K2\SK1”

“K2\SK1\SSK1”

“K2\SK1\SSK2”

I already have tried to split strings to arrays by("/") then to sort every part of array separately. But eventually it's too inconvenient and hard algoritm!

Maybe someone knows an easier way how to solve this problem.

Thank you!

答:
Here Python code, not JAVA, but I think it will be easy to adapt this code to usage of sorted set as I wrote is as self-explanatory as I could:  </p>

```<code>def lstAllPositionsOfSeparatorCharInString(strSepChar, strToQuery):
    """Return a list with all the positions of a character strSepChar in a string strToQuery."""
    lstPositions = []
    intPos = strToQuery.find(strSepChar)
    while intPos != -1: # strSepChar was found, proceed
        lstPositions.append(intPos)
        intPos = strToQuery.find(strSepChar, intPos+1)
    #:while
    return lstPositions
#:def

lstStrings=[r"K1\SK1", r"K1\SK2", r"K1\SK1\SSK1", r"K1\SK1\SSK2", r"K2", r"K2\SK1\SSK1", r"K2\SK1\SSK2"]
print(lstStrings)
# Append missing items if any:
strSepChar = r"\ "[0] # strSepChar will contain a single backslash
for item in lstStrings:
    for posNo in lstAllPositionsOfSeparatorCharInString(strSepChar, item):
        if item[0:posNo] not in lstStrings:
            lstStrings.append(item[0:posNo])
#:for :for :if
print( lstStrings )
# sort the list (in place):
lstStrings.sort()
print( lstStrings )
</code>```

<p>The code gives as output first the original list, than the expanded list and finally the sorted list (set): </p>

```<code>"""
'K1\\SK1', 'K1\\SK2', 'K1\\SK1\\SSK1', 'K1\\SK1\\SSK2', 'K2', 'K2\\SK1\\SSK1', 'K2\\SK1\\SSK2']
['K1\\SK1', 'K1\\SK2', 'K1\\SK1\\SSK1', 'K1\\SK1\\SSK2', 'K2', 'K2\\SK1\\SSK1', 'K2\\SK1\\SSK2', 'K1', 'K2\\SK1']
['K1', 'K1\\SK1', 'K1\\SK1\\SSK1', 'K1\\SK1\\SSK2', 'K1\\SK2', 'K2', 'K2\\SK1', 'K2\\SK1\\SSK1', 'K2\\SK1\\SSK2']
"""
</code>```

Title: Sorting of array by substrings

Body:
Here Python code, not JAVA, but I think it will be easy to adapt this code to usage of sorted set as I wrote is as self-explanatory as I could:

def lstAllPositionsOfSeparatorCharInString(strSepChar, strToQuery):
    """Return a list with all the positions of a character strSepChar in a string strToQuery."""
    lstPositions = []
    intPos = strToQuery.find(strSepChar)
    while intPos != -1: # strSepChar was found, proceed
        lstPositions.append(intPos)
        intPos = strToQuery.find(strSepChar, intPos+1)
    #:while
    return lstPositions
#:def

lstStrings=[r"K1\SK1", r"K1\SK2", r"K1\SK1\SSK1", r"K1\SK1\SSK2", r"K2", r"K2\SK1\SSK1", r"K2\SK1\SSK2"]
print(lstStrings)
# Append missing items if any:
strSepChar = r"\ "[0] # strSepChar will contain a single backslash
for item in lstStrings:
    for posNo in lstAllPositionsOfSeparatorCharInString(strSepChar, item):
        if item[0:posNo] not in lstStrings:
            lstStrings.append(item[0:posNo])
#:for :for :if
print( lstStrings )
# sort the list (in place):
lstStrings.sort()
print( lstStrings )

The code gives as output first the original list, than the expanded list and finally the sorted list (set):

"""
'K1\\SK1', 'K1\\SK2', 'K1\\SK1\\SSK1', 'K1\\SK1\\SSK2', 'K2', 'K2\\SK1\\SSK1', 'K2\\SK1\\SSK2']
['K1\\SK1', 'K1\\SK2', 'K1\\SK1\\SSK1', 'K1\\SK1\\SSK2', 'K2', 'K2\\SK1\\SSK1', 'K2\\SK1\\SSK2', 'K1', 'K2\\SK1']
['K1', 'K1\\SK1', 'K1\\SK1\\SSK1', 'K1\\SK1\\SSK2', 'K1\\SK2', 'K2', 'K2\\SK1', 'K2\\SK1\\SSK1', 'K2\\SK1\\SSK2']
"""


问:
How to design an Ecto changeset as a true before_save callback
I've a simple before_save transformation and learned that phoenix uses Ecto changest for this task.

My Stage model has a position attribute which defaults to the current maximum + 1 so tried to implement this as follows:

Stage Model:

```<code>  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, @required_fields, @optional_fields)
    |> validate_required([:name])
    |> set_position
  end

  defp set_position(current_changeset) do
    # get current max position from db
    max_position = Repo.one(
      from s in Stage,
      select: fragment("COALESCE(MAX(?),0)", s.position)
    )

    case current_changeset do
      %Ecto.Changeset{valid?: true} ->
        put_change(current_changeset, :position, max_position+1)
      _ ->
        current_changeset
    end
  end
</code>```

Which works fine when inserting one by one records but fails in bulk insertion; for example in below seed file.

Seed

```<code>alias MyApp.{Repo, Post}

[
  %{name: "Requirements"},
  %{name: "Quotation"},
  %{name: "Development"},
  %{name: "Closing"}
]
|> Enum.map(&Post.changeset(%Post{}, &1))
|> Enum.each(&Repo.insert!(&1))
</code>```

Expected/Current Behavior:

If current max position is say 7, for all inserted 4 records above, position will be set to 8 instead of 8,9,10,11 respectively! That's because the first pipe will prepare all changests then insert them!

Is the way i am seeding wrong? or the changeset? How can i re-design this so the behavior is the same regardless of how i do insertions? any feedback to improve how i am doing it is appreciated!

答:
You can use Ecto.Changeset.prepare_changes/2 to run arbitrary computation inside the database transaction of that changeset. Your set_position/1 function has the correct argument/return value (changeset -> changeset), so you just need to change:

```<code>|> set_position
</code>```

to

```<code>|> prepare_changes(&set_position/1)
</code>```

and set_position will now be executed in the same transaction as and just before your Post is inserted, instead of being executed while the changeset is created.

Body:
I've a simple before_save transformation and learned that phoenix uses Ecto changest for this task.

My Stage model has a position attribute which defaults to the current maximum + 1 so tried to implement this as follows:

Stage Model:

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, @required_fields, @optional_fields)
    |> validate_required([:name])
    |> set_position
  end

  defp set_position(current_changeset) do
    # get current max position from db
    max_position = Repo.one(
      from s in Stage,
      select: fragment("COALESCE(MAX(?),0)", s.position)
    )

    case current_changeset do
      %Ecto.Changeset{valid?: true} ->
        put_change(current_changeset, :position, max_position+1)
      _ ->
        current_changeset
    end
  end

Which works fine when inserting one by one records but fails in bulk insertion; for example in below seed file.

Seed

alias MyApp.{Repo, Post}

[
  %{name: "Requirements"},
  %{name: "Quotation"},
  %{name: "Development"},
  %{name: "Closing"}
]
|> Enum.map(&Post.changeset(%Post{}, &1))
|> Enum.each(&Repo.insert!(&1))

Expected/Current Behavior:

If current max position is say 7, for all inserted 4 records above, position will be set to 8 instead of 8,9,10,11 respectively! That's because the first pipe will prepare all changests then insert them!

Is the way i am seeding wrong? or the changeset? How can i re-design this so the behavior is the same regardless of how i do insertions? any feedback to improve how i am doing it is appreciated!

Body:
You can use Ecto.Changeset.prepare_changes/2 to run arbitrary computation inside the database transaction of that changeset. Your set_position/1 function has the correct argument/return value (changeset -> changeset), so you just need to change:

|> set_position

to

|> prepare_changes(&set_position/1)

and set_position will now be executed in the same transaction as and just before your Post is inserted, instead of being executed while the changeset is created.


问:
I need someone to convert web.config to .htaccess
Hello can anyone convert web.config to .htaccess ? from the code bellow ? i need someone to do this.</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 9">
                    <match url="^([^/]+)/?$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="chat.php?page={R:1}" appendQueryString="true" />
                </rule>
                <rule name="RequestBlockingRule1" patternSyntax="Wildcard" stopProcessing="true">
                    <match url="*" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="192.95.42.181" />
                    </conditions>
                    <action type="AbortRequest" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

答:
```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ chat.php?page=$1
Deny From 192.95.42.181
</code>```

Body:
Hello can anyone convert web.config to .htaccess ? from the code bellow ? i need someone to do this.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Imported Rule 9">
                    <match url="^([^/]+)/?$" ignoreCase="false" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="chat.php?page={R:1}" appendQueryString="true" />
                </rule>
                <rule name="RequestBlockingRule1" patternSyntax="Wildcard" stopProcessing="true">
                    <match url="*" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="192.95.42.181" />
                    </conditions>
                    <action type="AbortRequest" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>


问:
Gulp - the best way of minifying multiple css files into one?
What is the best way of minify multiple css files into one?

The gulp task below causing two issues after the minification and concatenation:

bootstraps glyphicons that I use have disappeared.

some of my styles are broken. The task seems to have re-arranged the position of some styles, for instance .footer{...} was placed below html{...} but it is now above html{...}. How can i stop it from rearranging them?

gulpfile:

```<code>gulp.task('minify-css', function() {
    return gulp.src([
        'node_modules/bootstrap/dist/css/bootstrap.css',
        'vendor/jquery-ui-1.12.1/jquery-ui.min.css',
        'node_modules/bootstrap/dist/css/bootstrap-theme.css',
        'node_modules/jasny-bootstrap/dist/css/jasny-bootstrap.css',
        'css/style.css',
        ])
        .pipe(sourcemaps.init())
        .pipe(cleanCSS({debug: true}))
        .pipe(sourcemaps.write())
        .pipe(concat('bundle.min.css'))
        .pipe(gulp.dest('dist'));
});
</code>```

Any ideas?

答: It's not a common solution but sometimes it helps. I make two min. bundles: 'head.bundle.min.css' and 'foot.bundle.min.css' just like you did. In head.bundle.min.css I collect styles which must be first. And finally I concatenated two min bundles in one. </p>

Body:
What is the best way of minify multiple css files into one?

The gulp task below causing two issues after the minification and concatenation:

bootstraps glyphicons that I use have disappeared.

some of my styles are broken. The task seems to have re-arranged the position of some styles, for instance .footer{...} was placed below html{...} but it is now above html{...}. How can i stop it from rearranging them?

gulpfile:

gulp.task('minify-css', function() {
    return gulp.src([
        'node_modules/bootstrap/dist/css/bootstrap.css',
        'vendor/jquery-ui-1.12.1/jquery-ui.min.css',
        'node_modules/bootstrap/dist/css/bootstrap-theme.css',
        'node_modules/jasny-bootstrap/dist/css/jasny-bootstrap.css',
        'css/style.css',
        ])
        .pipe(sourcemaps.init())
        .pipe(cleanCSS({debug: true}))
        .pipe(sourcemaps.write())
        .pipe(concat('bundle.min.css'))
        .pipe(gulp.dest('dist'));
});

Any ideas?