问:
C# & SQL - Followed examples to write a Parallel.ForEach loop to create threads, but it is throwing exceptions about the connection state
I have tried the code below and it throws exceptions saying that the query requires an open connection, and that the current state is open/opening/closed.

It is a Parallel.ForEach loop creating threads, and I want them to open the connection to the SQL Server database and insert something there. I followed the patterns to handle parallelism in other questions here, but they don't work for me.

Can someone throw some light on this this? How to make this happen?

Connection open error?

Connection closed error

```<code>private static void CreateResultTable()
    {
        Parallel.ForEach(_fakeTableFileFull, tableRow =>
        {
            var fileRow = Regex.Split(tableRow, PatternExFile);
            SearchForConfirm(fileRow[3], fileRow[1], fileRow[2]);
        });
    }

    private static void SearchForConfirm(string id, string number, string date)
    {
        if (tokenChecksum.ContainsKey(id))
        {
            WriteLineToResultFile(number, date, tokenChecksum[id], id);
        }
    }

    private static void WriteLineToResultFile(string number, string date, string confirm, string id)
    {
        using (Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"]
            .ConnectionString))
        {
            Conn.Open();
            SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PanChecksums] " +
                                                     "([number], " +
                                                     "[Id]) " +
                                                     "VALUES " +
                                                     "(" + Int64.Parse(id) +
                                                     "," + "'" + confirm + "'" + ")", Conn);
            cmd.ExecuteNonQuery();

        }

        using (Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"]
            .ConnectionString))
        {
            Conn.Open();
            SqlCommand cmd = new SqlCommand("SET IDENTITY_INSERT IdNumber ON;", Conn);
            cmd.ExecuteNonQuery();

            cmd = new SqlCommand("INSERT INTO [dbo].[IdNumber] " +
                             "([Id], " +
                             "[number], " +
                             "[Month], " +
                             "[Year]) " +
                             "VALUES " +
                             "(" + "'" + id + "'" + "," +
                             Int64.Parse(number) + "," +
                             "'" + date.Substring(0, 2) + "'" + "," +
                             "'" + date.Substring(2, 2) + "'" + ")", Conn);

        cmd.ExecuteNonQuery();

            cmd = new SqlCommand("SET IDENTITY_INSERT IdNumber ON;", Conn);
            cmd.ExecuteNonQuery();
        }
</code>```

答:
Instead of:

```<code>Parallel.ForEach(list, x=> {...});
</code>```

Use light weight tasks from ThreadPool:

```<code>var tasks = list.Select(x=> Task.Run(()=> {...})).ToArray();
Task.WaitAll(tasks);
</code>```

Parallel.ForEach is used for heavy CPU load, not for IO load (which is cause of your error, you simply exhaust SQL connection pool). Another approach is to set DegreeOfParallelism:

```<code>Parallel.ForEach(list, new ParallelOptions(){ MaxDegreeOfParallelism = 4 }, x => {...});
</code>```

It will limit connection creation to 4 at the time, but I don't recomend it because you will need manualy manage ALL of your Parallel.ForEach invokations, which can become quite a pain.

Also, your connection is opened twice in row, in one iteration, which is strange. Simply open one connection and use it across all iterations. It will require from you to pass this dependency in every function which need connection, but it is common practice.

Body:
I have tried the code below and it throws exceptions saying that the query requires an open connection, and that the current state is open/opening/closed.

It is a Parallel.ForEach loop creating threads, and I want them to open the connection to the SQL Server database and insert something there. I followed the patterns to handle parallelism in other questions here, but they don't work for me.

Can someone throw some light on this this? How to make this happen?

Connection open error?

Connection closed error

private static void CreateResultTable()
    {
        Parallel.ForEach(_fakeTableFileFull, tableRow =>
        {
            var fileRow = Regex.Split(tableRow, PatternExFile);
            SearchForConfirm(fileRow[3], fileRow[1], fileRow[2]);
        });
    }

    private static void SearchForConfirm(string id, string number, string date)
    {
        if (tokenChecksum.ContainsKey(id))
        {
            WriteLineToResultFile(number, date, tokenChecksum[id], id);
        }
    }

    private static void WriteLineToResultFile(string number, string date, string confirm, string id)
    {
        using (Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"]
            .ConnectionString))
        {
            Conn.Open();
            SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PanChecksums] " +
                                                     "([number], " +
                                                     "[Id]) " +
                                                     "VALUES " +
                                                     "(" + Int64.Parse(id) +
                                                     "," + "'" + confirm + "'" + ")", Conn);
            cmd.ExecuteNonQuery();

        }

        using (Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"]
            .ConnectionString))
        {
            Conn.Open();
            SqlCommand cmd = new SqlCommand("SET IDENTITY_INSERT IdNumber ON;", Conn);
            cmd.ExecuteNonQuery();

            cmd = new SqlCommand("INSERT INTO [dbo].[IdNumber] " +
                             "([Id], " +
                             "[number], " +
                             "[Month], " +
                             "[Year]) " +
                             "VALUES " +
                             "(" + "'" + id + "'" + "," +
                             Int64.Parse(number) + "," +
                             "'" + date.Substring(0, 2) + "'" + "," +
                             "'" + date.Substring(2, 2) + "'" + ")", Conn);

        cmd.ExecuteNonQuery();

            cmd = new SqlCommand("SET IDENTITY_INSERT IdNumber ON;", Conn);
            cmd.ExecuteNonQuery();
        }

Body:
Instead of:

Parallel.ForEach(list, x=> {...});

Use light weight tasks from ThreadPool:

var tasks = list.Select(x=> Task.Run(()=> {...})).ToArray();
Task.WaitAll(tasks);

Parallel.ForEach is used for heavy CPU load, not for IO load (which is cause of your error, you simply exhaust SQL connection pool). Another approach is to set DegreeOfParallelism:

Parallel.ForEach(list, new ParallelOptions(){ MaxDegreeOfParallelism = 4 }, x => {...});

It will limit connection creation to 4 at the time, but I don't recomend it because you will need manualy manage ALL of your Parallel.ForEach invokations, which can become quite a pain.

Also, your connection is opened twice in row, in one iteration, which is strange. Simply open one connection and use it across all iterations. It will require from you to pass this dependency in every function which need connection, but it is common practice.


来源: stackexchange

问:
[Wordpress 4.6][Query] Ordering not working
I'm currently working on an e-commerce website and we found that the best sales widget wasn't ordering as expected the products.

I tested the query's arguments and they seems right, and whatever ordering i choose, the query refuse to order the products.

Here an example :

```<code>$args = array(
                'post_type'             => 'product',
                'post_status'           => 'publish',
                'numberposts'           => -1,
                'meta_key'              => 'total_sales',
                'orderby'               => 'meta_value_numeric',
                'meta_type'             => 'NUMERIC'
            );

$products = get_posts( $args );

foreach ($products as $key => $product) {
    $sales = get_post_meta($product->ID, 'total_sales');
    echo $sales[0];
}
</code>```

Here the results :

```<code>144
1981
70
26
65
84
148
109
748
48
15
78
</code>```

I checked in the database, and the value are numbers (no array or else).

After checking, they are ordered by date (DESC).

I tried the following :

- Setting orderby with meta_value_num or meta_value.

- Removing the meta and choosing orderby title.

But none of them ordered the results.

I've worked on other websites with this kind of request and never had a problem with the ordering.

Does someone have an idea where the problem could be coming from ?

Thanks,

答:
in your query Try using :

'orderby'  => 'ID'

Or

you can also sort $products array using asort($products).

visit http://php.net/manual/fr/function.asort.php for more informations

ContentLicense: CC BY-SA 3.0

Body:
I'm currently working on an e-commerce website and we found that the best sales widget wasn't ordering as expected the products.

I tested the query's arguments and they seems right, and whatever ordering i choose, the query refuse to order the products.

Here an example :

$args = array(
                'post_type'             => 'product',
                'post_status'           => 'publish',
                'numberposts'           => -1,
                'meta_key'              => 'total_sales',
                'orderby'               => 'meta_value_numeric',
                'meta_type'             => 'NUMERIC'
            );

$products = get_posts( $args );

foreach ($products as $key => $product) {
    $sales = get_post_meta($product->ID, 'total_sales');
    echo $sales[0];
}

Here the results :

144
1981
70
26
65
84
148
109
748
48
15
78

I checked in the database, and the value are numbers (no array or else).

After checking, they are ordered by date (DESC).

I tried the following :

- Setting orderby with meta_value_num or meta_value.

- Removing the meta and choosing orderby title.

But none of them ordered the results.

I've worked on other websites with this kind of request and never had a problem with the ordering.

Does someone have an idea where the problem could be coming from ?

Thanks,


问:
What are global states? How do they affect testability and how to avoid them?
List down the various global states like global variable, singleton object etc.,

I read that they affect the testability of code. Can you explain alternatives to global states that help in improving the testability of the code?

答: Start by reading singletons are pathological liars. </p>

ContentLicense: CC BY-SA 2.5


问:
Passing returned variables into a different method
I'm trying to pass the mark variable I returned into a different method so that it can be checked to determine the grade. When I try to run the program however it tells me that it can't find the symbol "mark" that I'm passing into the determineGrade method. I'm wondering how I'm supposed to pass mark into determineGrade so that the program can run?</p>

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

public class GradeClassifier {

    public static void main(String[] args) {
        title();
        getMark();
        determineGrade(mark);
        displayGrade(mark, grade);
    }

    public static void title() {
        System.out.println("Grade Classifier\n****************");
    }

    public static int getMark() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter exam mark :> ");
        int mark = in.nextInt();

        return mark;
    }

    public static String determineGrade(int mark) {
        String grade;

        if (100 >= mark >= 70)
            grade = "Grade A (Pass)";
        else if (69 >= mark >= 60)
            grade = "Grade B (Pass)";
        else if (59 >= mark >= 50)
            grade = "Grade C (Pass)";
        else if (49 >= mark >= 40)
            grade = "Grade D (Pass)";
        else if (39 >= mark >= 0)
            grade = "Grade F (Fail)";
        else
            grade = "You did not input a valid number.";

        return grade;
    }

    public static void displayGrade(int mark, String grade) {
        if (100 >= mark >= 0)
            System.out.print("Congratulations, you are awarded a " + grade + ".");
        else
            System.out.print(grade);
    }

}
</code>```

答:
Replace getMark(); with int mark = getMark();

This will create a new int type variable mark and holds the value returned by getMark() which is then passed to determineGrade(mark);.

Also, in method getMark() there is no need to create variable int mark, just return as follow :

```<code>return in.nextInt();
</code>```

Body:
I'm trying to pass the mark variable I returned into a different method so that it can be checked to determine the grade. When I try to run the program however it tells me that it can't find the symbol "mark" that I'm passing into the determineGrade method. I'm wondering how I'm supposed to pass mark into determineGrade so that the program can run?

import java.util.Scanner;

public class GradeClassifier {

    public static void main(String[] args) {
        title();
        getMark();
        determineGrade(mark);
        displayGrade(mark, grade);
    }

    public static void title() {
        System.out.println("Grade Classifier\n****************");
    }

    public static int getMark() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter exam mark :> ");
        int mark = in.nextInt();

        return mark;
    }

    public static String determineGrade(int mark) {
        String grade;

        if (100 >= mark >= 70)
            grade = "Grade A (Pass)";
        else if (69 >= mark >= 60)
            grade = "Grade B (Pass)";
        else if (59 >= mark >= 50)
            grade = "Grade C (Pass)";
        else if (49 >= mark >= 40)
            grade = "Grade D (Pass)";
        else if (39 >= mark >= 0)
            grade = "Grade F (Fail)";
        else
            grade = "You did not input a valid number.";

        return grade;
    }

    public static void displayGrade(int mark, String grade) {
        if (100 >= mark >= 0)
            System.out.print("Congratulations, you are awarded a " + grade + ".");
        else
            System.out.print(grade);
    }

}

Body:
Replace getMark(); with int mark = getMark();

This will create a new int type variable mark and holds the value returned by getMark() which is then passed to determineGrade(mark);.

Also, in method getMark() there is no need to create variable int mark, just return as follow :

return in.nextInt();


问:
SailsJS - Error: EACCES: permission denied, open '/.babel.json'
I'm working on at a SailsJS project and when I push it to serverI get the error

```<code>at Error (native)
at Object.fs.openSync (fs.js:641:18)
at Object.fs.writeFileSync (fs.js:1347:33)
at process._tickCallback (internal/process/next_tick.js:104:9)
at save (/usr/src/app/node_modules/babel-register/lib/cache.js:48:16)
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
Error: EACCES: permission denied, open '/.babel.json'
</code>```

I know the server call babeljs on build and I think the error can be by the babeljs being called in the build and by the sailsjs when it starts, that is, twice.

I found this discussion about the error, but I can't disable the babeljs cache on my server.

My Package.json is:

```<code>{
  "name": "cards",
  "private": true,
  "version": "0.0.0",
  "description": "a Sails-Redux application for multi-player online card game",
  "keywords": [
    "sailsjs",
    "redux",
    "es2015",
    "webpack"
  ],
  "dependencies": {
    "axios": "^0.13.1",
    "babel-plugin-transform-class-properties": "^6.11.5",
    "babel-plugin-transform-object-rest-spread": "^6.6.5",
    "babel-polyfill": "^6.7.2",
    "babel-preset-stage-1": "^6.13.0",
    "connect-mongo": "0.8.2",
    "css-loader": "^0.23.1",
    "ejs": "2.3.4",
    "file-loader": "^0.8.5",
    "grunt": "0.4.5",
    "grunt-babel": "^6.0.0",
    "grunt-contrib-clean": "0.6.0",
    "grunt-contrib-coffee": "0.13.0",
    "grunt-contrib-concat": "0.5.1",
    "grunt-contrib-copy": "0.5.0",
    "grunt-contrib-cssmin": "0.9.0",
    "grunt-contrib-jst": "0.6.0",
    "grunt-contrib-less": "1.1.0",
    "grunt-contrib-uglify": "0.7.0",
    "grunt-contrib-watch": "0.5.3",
    "grunt-sails-linker": "~0.10.1",
    "grunt-sync": "0.2.4",
    "include-all": "~0.1.6",
    "node-sass": "^3.8.0",
    "postcss-modules-extract-imports": "^1.0.0",
    "postcss-modules-scope": "^1.0.0",
    "rc": "1.0.1",
    "react": "^0.14.9",
    "react-dom": "^0.14.9",
    "react-redux": "^4.4.8",
    "react-router": "^2.6.1",
    "react-tap-event-plugin": "^0.2.2",
    "redux": "^3.7.2",
    "redux-form": "^5.3.2",
    "redux-optimist": "0.0.2",
    "redux-optimistic-ui": "^0.3.2",
    "redux-promise": "^0.5.3",
    "redux-thunk": "^2.1.0",
    "redux-undo": "^0.6.1",
    "sails": "~0.12.1",
    "sails-disk": "~0.10.9",
    "sails-hook-babel": "^6.0.1",
    "sails-mongo": "^0.12.2",
    "sails-webpack": "^1.0.13",
    "sass": "^0.5.0",
    "sass-loader": "^3.2.3",
    "style-loader": "^0.13.1",
    "unexpected-react": "^1.0.0",
    "updeep": "^0.16.1",
    "url-loader": "^0.5.7"
  },
  "scripts": {
    "debug": "node debug app.js",
    "start": "node app.js"
  },
  "main": "app.js",
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "fernando",
  "license": "",
  "devDependencies": {
    "axios-mock-adapter": "^1.6.1",
    "babel-core": "^6.7.2",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "css-modules-require-hook": "^4.0.0",
    "jsdom": "^8.1.0",
    "react-tools": "^0.13.3",
    "redux-devtools": "^3.4.0",
    "redux-logger": "^2.6.1",
    "source-map": "^0.5.3",
    "unexpected": "^10.10.8",
    "webpack-dev-server": "^1.14.1"
  }
}
</code>```

答: When you push it to the server, I image you use Git and then you do a npm update/install. If so, you might want to check the permissions on your app folder before running npm install. Sorry, I cannot write this in a comment...</p>

Body:
I'm working on at a SailsJS project and when I push it to serverI get the error

at Error (native)
at Object.fs.openSync (fs.js:641:18)
at Object.fs.writeFileSync (fs.js:1347:33)
at process._tickCallback (internal/process/next_tick.js:104:9)
at save (/usr/src/app/node_modules/babel-register/lib/cache.js:48:16)
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
Error: EACCES: permission denied, open '/.babel.json'

I know the server call babeljs on build and I think the error can be by the babeljs being called in the build and by the sailsjs when it starts, that is, twice.

I found this discussion about the error, but I can't disable the babeljs cache on my server.

My Package.json is:

{
  "name": "cards",
  "private": true,
  "version": "0.0.0",
  "description": "a Sails-Redux application for multi-player online card game",
  "keywords": [
    "sailsjs",
    "redux",
    "es2015",
    "webpack"
  ],
  "dependencies": {
    "axios": "^0.13.1",
    "babel-plugin-transform-class-properties": "^6.11.5",
    "babel-plugin-transform-object-rest-spread": "^6.6.5",
    "babel-polyfill": "^6.7.2",
    "babel-preset-stage-1": "^6.13.0",
    "connect-mongo": "0.8.2",
    "css-loader": "^0.23.1",
    "ejs": "2.3.4",
    "file-loader": "^0.8.5",
    "grunt": "0.4.5",
    "grunt-babel": "^6.0.0",
    "grunt-contrib-clean": "0.6.0",
    "grunt-contrib-coffee": "0.13.0",
    "grunt-contrib-concat": "0.5.1",
    "grunt-contrib-copy": "0.5.0",
    "grunt-contrib-cssmin": "0.9.0",
    "grunt-contrib-jst": "0.6.0",
    "grunt-contrib-less": "1.1.0",
    "grunt-contrib-uglify": "0.7.0",
    "grunt-contrib-watch": "0.5.3",
    "grunt-sails-linker": "~0.10.1",
    "grunt-sync": "0.2.4",
    "include-all": "~0.1.6",
    "node-sass": "^3.8.0",
    "postcss-modules-extract-imports": "^1.0.0",
    "postcss-modules-scope": "^1.0.0",
    "rc": "1.0.1",
    "react": "^0.14.9",
    "react-dom": "^0.14.9",
    "react-redux": "^4.4.8",
    "react-router": "^2.6.1",
    "react-tap-event-plugin": "^0.2.2",
    "redux": "^3.7.2",
    "redux-form": "^5.3.2",
    "redux-optimist": "0.0.2",
    "redux-optimistic-ui": "^0.3.2",
    "redux-promise": "^0.5.3",
    "redux-thunk": "^2.1.0",
    "redux-undo": "^0.6.1",
    "sails": "~0.12.1",
    "sails-disk": "~0.10.9",
    "sails-hook-babel": "^6.0.1",
    "sails-mongo": "^0.12.2",
    "sails-webpack": "^1.0.13",
    "sass": "^0.5.0",
    "sass-loader": "^3.2.3",
    "style-loader": "^0.13.1",
    "unexpected-react": "^1.0.0",
    "updeep": "^0.16.1",
    "url-loader": "^0.5.7"
  },
  "scripts": {
    "debug": "node debug app.js",
    "start": "node app.js"
  },
  "main": "app.js",
  "repository": {
    "type": "git",
    "url": ""
  },
  "author": "fernando",
  "license": "",
  "devDependencies": {
    "axios-mock-adapter": "^1.6.1",
    "babel-core": "^6.7.2",
    "babel-loader": "^6.4.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "css-modules-require-hook": "^4.0.0",
    "jsdom": "^8.1.0",
    "react-tools": "^0.13.3",
    "redux-devtools": "^3.4.0",
    "redux-logger": "^2.6.1",
    "source-map": "^0.5.3",
    "unexpected": "^10.10.8",
    "webpack-dev-server": "^1.14.1"
  }
}


答:
Your connections should be open:

```<code>Conn.Open();
</code>```

only close it when the Parralel.ForEach is done.

A better solution wouldbe to merge multiple insert together into 1 insert:

```<code>INSERT INTO table (column1, column2)
VALUES
  ('',''), -- first insert row
  ('','')  -- second insert row
</code>```

Just join multiple inserts together with a comma.

Title: C# & SQL - Followed examples to write a Parallel.ForEach loop to create threads, but it is throwing exceptions about the connection state

Body:
Your connections should be open:

Conn.Open();

only close it when the Parralel.ForEach is done.

A better solution wouldbe to merge multiple insert together into 1 insert:

INSERT INTO table (column1, column2)
VALUES
  ('',''), -- first insert row
  ('','')  -- second insert row

Just join multiple inserts together with a comma.


问:
Undoing a git merge
I'm not that experienced with Git and now I have a big problem falling into my lap.

Here's how my current branch look like:

```<code>feature       /---F1-----F2----\
             /                  \
master -----M0-----M1-----M2-----M3-----M4
             \                        /
bugfix        \--B1-----B2-----------/
</code>```

The situation:

Someone did a very bad thing and pushed a really bad merge (M3). I only noticed the bad merge when our models (not source code) wouldn't load after I merged B1 and B2 into M4. Luckily, I haven't pushed M4 yet.

The problem:

How do I set things right again? I want M0, M1, M2, F1, F2, B1, and B2. But I don't want M3 and M4 (since M4 is obviously broken). If I have to abandon changes, then F1 and F2 can be sacrificed :)

I looked at git revert but I'm not confident that I fully understand how it works. So... I'm really hoping for help on how to resolve this.

Thanks in advance.

答:
If you didn't push (publish) the merge commits yet, use git reset. E.g. on the master branch, assuming your working tree is clean, do git reset --hard .

More info:
Undo a Git merge that hasn't been pushed yet

If you did publish your changes you might want to consider making a revert commit instead. More info here:
http://progit.org/2010/03/02/undoing-merges.html

Title: Undoing a git merge

Body:
I'm not that experienced with Git and now I have a big problem falling into my lap.

Here's how my current branch look like:

feature       /---F1-----F2----\
             /                  \
master -----M0-----M1-----M2-----M3-----M4
             \                        /
bugfix        \--B1-----B2-----------/

The situation:

Someone did a very bad thing and pushed a really bad merge (M3). I only noticed the bad merge when our models (not source code) wouldn't load after I merged B1 and B2 into M4. Luckily, I haven't pushed M4 yet.

The problem:

How do I set things right again? I want M0, M1, M2, F1, F2, B1, and B2. But I don't want M3 and M4 (since M4 is obviously broken). If I have to abandon changes, then F1 and F2 can be sacrificed :)

I looked at git revert but I'm not confident that I fully understand how it works. So... I'm really hoping for help on how to resolve this.

Thanks in advance.


问:
After upgrading to Angular 5 my project won't build
After upgrading to Angular 5, my project won't build.  I am using Visual Studio 2017 15.4.3 and am using SystemJs.  My typescript version is 2.4.2.

I get the following 8 errors:

```<code>Error Build:',' expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts    line 34 oolumn 31
Error Build:Type parameter declaration expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts 34  oolumn 33
Error Build:Expression expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts line 34 oolumn 37
Error Build:')' expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts    line 34 oolumn 42
Error Build:';' expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts    line 34 oolumn 50
Error Build:Declaration or statement expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts   34  oolumn 51
Error Build:':' expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts    line 35      oolumn 10
Error Build:',' expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts    line 35      oolumn 28
</code>```

Below is my package.json file:

```<code>            {
              "name": "mic",
              "version": "0.0.0",
              "license": "MIT",
              "scripts": {
                "ng": "ng",
                "start": "webpack-dev-server --port=4200",
                "build": "webpack -p",
                "test": "karma start ./karma.conf.js",
                "lint": "ng lint",
                "e2e": "protractor ./protractor.conf.js",
                "copy": "xcopy \"dist\" \"..\\Mic\\Scripts\\NgApp\" /i /s /r /y /c",
                "prepree2e": "npm start",
                "pree2e": "webdriver-manager update --standalone false --gecko false --quiet"
              },
              "private": true,
              "dependencies": {
                "@angular/animations": "^5.0.2",
                "@angular/common": "^5.0.2",
                "@angular/compiler": "^5.0.2",
                "@angular/core": "^5.0.2",
                "@angular/forms": "^5.0.2",
                "@angular/http": "^5.0.2",
                "@angular/platform-browser": "^5.0.2",
                "@angular/platform-browser-dynamic": "^5.0.2",
                "@angular/platform-server": "^5.0.2",
                "@angular/router": "^5.0.2",
                "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.5",
                "@progress/kendo-angular-buttons": "^1.1.1",
                "@progress/kendo-angular-dateinputs": "^1.4.0",
                "@progress/kendo-angular-dialog": "^1.3.0",
                "@progress/kendo-angular-dropdowns": "^1.2.3",
                "@progress/kendo-angular-excel-export": "^1.0.5",
                "@progress/kendo-angular-grid": "^1.6.1",
                "@progress/kendo-angular-inputs": "^1.3.3",
                "@progress/kendo-angular-intl": "^1.3.0",
                "@progress/kendo-angular-l10n": "^1.0.5",
                "@progress/kendo-angular-popup": "^1.3.0",
                "@progress/kendo-angular-resize-sensor": "^1.0.5",
                "@progress/kendo-data-query": "^1.1.1",
                "@progress/kendo-drawing": "^1.4.0",
                "@progress/kendo-file-saver": "^1.0.4",
                "@progress/kendo-popup-common": "^1.2.3",
                "@progress/kendo-theme-default": "^2.44.0",
                "@telerik/kendo-intl": "^1.3.0",
                "angular2-notifications": "^0.9.6",
                "classlist.js": "^1.1.20150312",
                "core-js": "^2.5.1",
                "intl": "^1.2.5",
                "libphonenumber-js": "^0.4.40",
                "rxjs": "5.5.2",
                "web-animations-js": "^2.3.1",
                "zone.js": "^0.8.18"
              },
              "devDependencies": {
                "@angular/cli": "^1.5.0",
                "@angular/compiler-cli": "^5.0.2",
                "@types/jasmine": "2.5.38",
                "@types/node": "^6.0.92",
                "angular-in-memory-web-api": "^0.3.2",
                "autoprefixer": "^6.5.3",
                "cldr-data": "^31.0.2",
                "codelyzer": "~2.0.0",
                "css-loader": "^0.27.3",
                "cssnano": "^3.10.0",
                "exports-loader": "^0.6.3",
                "file-loader": "^0.10.0",
                "istanbul-instrumenter-loader": "^2.0.0",
                "jasmine-core": "~2.5.2",
                "jasmine-spec-reporter": "~3.2.0",
                "json-loader": "^0.5.4",
                "jszip": "^3.1.3",
                "karma": "~1.4.1",
                "karma-chrome-launcher": "~2.0.0",
                "karma-cli": "~1.0.1",
                "karma-coverage-istanbul-reporter": "^0.2.0",
                "karma-jasmine": "~1.1.0",
                "karma-jasmine-html-reporter": "^0.2.2",
                "karma-sourcemap-loader": "^0.3.7",
                "less-loader": "^4.0.2",
                "postcss-loader": "^1.3.3",
                "postcss-url": "^5.1.2",
                "protractor": "~5.1.0",
                "raw-loader": "^0.5.1",
                "rollup": "^0.43.0",
                "rollup-plugin-commonjs": "^8.0.2",
                "rollup-plugin-node-resolve": "^3.0.0",
                "rollup-plugin-uglify": "^2.0.1",
                "sass-loader": "^6.0.3",
                "script-loader": "^0.7.0",
                "source-map-loader": "^0.1.5",
                "style-loader": "^0.13.1",
                "stylus-loader": "^3.0.1",
                "systemjs": "^0.20.19",
                "systemjs-plugin-babel": "0.0.25",
                "systemjs-plugin-json": "^0.3.0",
                "ts-node": "~2.0.0",
                "tslib": "^1.6.1",
                "tslint": "~4.5.0",
                "typescript": "2.4.2",
                "url-loader": "^0.5.7",
                "webpack-dev-server": "~2.4.2"
              }
            }
</code>```

Below is my tsconfig.json

```<code>    {
      "compileOnSave": true,
      "compilerOptions": {
        "importHelpers": true,
        "baseUrl": "src",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es2017",
        "typeRoots": [
          "node_modules/@types"
        ],
        "lib": [
          "es7",
          "dom"
        ]
      },
      "exclude": [
        "test.ts",
        "**/*.spec.ts",
        "node_modules",
        "dist",
        "../Scripts"
      ]
    }
</code>```

Please help.  This is very frustrating.

Thanks.

答:
Try this packages.json:

```<code>{
              "name": "mic",
              "version": "0.0.0",
              "license": "MIT",
              "scripts": {
                "ng": "ng",
                "start": "webpack-dev-server --port=4200",
                "build": "webpack -p",
                "test": "karma start ./karma.conf.js",
                "lint": "ng lint",
                "e2e": "protractor ./protractor.conf.js",
                "copy": "xcopy \"dist\" \"..\\Mic\\Scripts\\NgApp\" /i /s /r /y /c",
                "prepree2e": "npm start",
                "pree2e": "webdriver-manager update --standalone false --gecko false --quiet"
              },
              "private": true,
              "dependencies": {
                "@angular/animations": "5.0.0",
                "@angular/common": "5.0.0",
                "@angular/compiler": "5.0.0",
                "@angular/core": "5.0.0",
                "@angular/forms": "5.0.0",
                "@angular/http": "5.0.0",
                "@angular/platform-browser": "5.0.0",
                "@angular/platform-browser-dynamic": "5.0.0",
                "@angular/router": "5.0.0",
                "@angular/platform-server": "5.0.0",
                "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.5",
                "@progress/kendo-angular-buttons": "^1.1.1",
                "@progress/kendo-angular-dateinputs": "^1.4.0",
                "@progress/kendo-angular-dialog": "^1.3.0",
                "@progress/kendo-angular-dropdowns": "^1.2.3",
                "@progress/kendo-angular-excel-export": "^1.0.5",
                "@progress/kendo-angular-grid": "^1.6.1",
                "@progress/kendo-angular-inputs": "^1.3.3",
                "@progress/kendo-angular-intl": "^1.3.0",
                "@progress/kendo-angular-l10n": "^1.0.5",
                "@progress/kendo-angular-popup": "^1.3.0",
                "@progress/kendo-angular-resize-sensor": "^1.0.5",
                "@progress/kendo-data-query": "^1.1.1",
                "@progress/kendo-drawing": "^1.4.0",
                "@progress/kendo-file-saver": "^1.0.4",
                "@progress/kendo-popup-common": "^1.2.3",
                "@progress/kendo-theme-default": "^2.44.0",
                "@telerik/kendo-intl": "^1.3.0",
                "angular2-notifications": "^0.9.6",
                "classlist.js": "^1.1.20150312",
                "core-js": "^2.5.1",
                "intl": "^1.2.5",
                "libphonenumber-js": "^0.4.40",
                "rxjs": "5.5.2",
                "web-animations-js": "^2.3.1",
                "zone.js": "^0.8.18"
              },
              "devDependencies": {
                "@angular/cli": "^1.5.0",
                "@angular/compiler-cli": "^5.0.2",
                "@types/jasmine": "2.5.38",
                "@types/node": "^6.0.92",
                "angular-in-memory-web-api": "^0.3.2",
                "autoprefixer": "^6.5.3",
                "cldr-data": "^31.0.2",
                "codelyzer": "~2.0.0",
                "css-loader": "^0.27.3",
                "cssnano": "^3.10.0",
                "exports-loader": "^0.6.3",
                "file-loader": "^0.10.0",
                "istanbul-instrumenter-loader": "^2.0.0",
                "jasmine-core": "~2.5.2",
                "jasmine-spec-reporter": "~3.2.0",
                "json-loader": "^0.5.4",
                "jszip": "^3.1.3",
                "karma": "~1.4.1",
                "karma-chrome-launcher": "~2.0.0",
                "karma-cli": "~1.0.1",
                "karma-coverage-istanbul-reporter": "^0.2.0",
                "karma-jasmine": "~1.1.0",
                "karma-jasmine-html-reporter": "^0.2.2",
                "karma-sourcemap-loader": "^0.3.7",
                "less-loader": "^4.0.2",
                "postcss-loader": "^1.3.3",
                "postcss-url": "^5.1.2",
                "protractor": "~5.1.0",
                "raw-loader": "^0.5.1",
                "rollup": "^0.43.0",
                "rollup-plugin-commonjs": "^8.0.2",
                "rollup-plugin-node-resolve": "^3.0.0",
                "rollup-plugin-uglify": "^2.0.1",
                "sass-loader": "^6.0.3",
                "script-loader": "^0.7.0",
                "source-map-loader": "^0.1.5",
                "style-loader": "^0.13.1",
                "stylus-loader": "^3.0.1",
                "systemjs": "^0.20.19",
                "systemjs-plugin-babel": "0.0.25",
                "systemjs-plugin-json": "^0.3.0",
                "ts-node": "~2.0.0",
                "tslib": "^1.6.1",
                "tslint": "~4.5.0",
                "typescript": "2.6.1",
                "url-loader": "^0.5.7",
                "webpack-dev-server": "~2.4.2"
              }
            }
</code>```

delete node_modules folder & run npm install

Body:
After upgrading to Angular 5, my project won't build.  I am using Visual Studio 2017 15.4.3 and am using SystemJs.  My typescript version is 2.4.2.

I get the following 8 errors:

Error Build:',' expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts    line 34 oolumn 31
Error Build:Type parameter declaration expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts 34  oolumn 33
Error Build:Expression expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts line 34 oolumn 37
Error Build:')' expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts    line 34 oolumn 42
Error Build:';' expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts    line 34 oolumn 50
Error Build:Declaration or statement expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts   34  oolumn 51
Error Build:':' expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts    line 35      oolumn 10
Error Build:',' expected. node_modules\@angular\platform-browser\src\browser\transfer_state.d.ts    line 35      oolumn 28

Below is my package.json file:

            {
              "name": "mic",
              "version": "0.0.0",
              "license": "MIT",
              "scripts": {
                "ng": "ng",
                "start": "webpack-dev-server --port=4200",
                "build": "webpack -p",
                "test": "karma start ./karma.conf.js",
                "lint": "ng lint",
                "e2e": "protractor ./protractor.conf.js",
                "copy": "xcopy \"dist\" \"..\\Mic\\Scripts\\NgApp\" /i /s /r /y /c",
                "prepree2e": "npm start",
                "pree2e": "webdriver-manager update --standalone false --gecko false --quiet"
              },
              "private": true,
              "dependencies": {
                "@angular/animations": "^5.0.2",
                "@angular/common": "^5.0.2",
                "@angular/compiler": "^5.0.2",
                "@angular/core": "^5.0.2",
                "@angular/forms": "^5.0.2",
                "@angular/http": "^5.0.2",
                "@angular/platform-browser": "^5.0.2",
                "@angular/platform-browser-dynamic": "^5.0.2",
                "@angular/platform-server": "^5.0.2",
                "@angular/router": "^5.0.2",
                "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.5",
                "@progress/kendo-angular-buttons": "^1.1.1",
                "@progress/kendo-angular-dateinputs": "^1.4.0",
                "@progress/kendo-angular-dialog": "^1.3.0",
                "@progress/kendo-angular-dropdowns": "^1.2.3",
                "@progress/kendo-angular-excel-export": "^1.0.5",
                "@progress/kendo-angular-grid": "^1.6.1",
                "@progress/kendo-angular-inputs": "^1.3.3",
                "@progress/kendo-angular-intl": "^1.3.0",
                "@progress/kendo-angular-l10n": "^1.0.5",
                "@progress/kendo-angular-popup": "^1.3.0",
                "@progress/kendo-angular-resize-sensor": "^1.0.5",
                "@progress/kendo-data-query": "^1.1.1",
                "@progress/kendo-drawing": "^1.4.0",
                "@progress/kendo-file-saver": "^1.0.4",
                "@progress/kendo-popup-common": "^1.2.3",
                "@progress/kendo-theme-default": "^2.44.0",
                "@telerik/kendo-intl": "^1.3.0",
                "angular2-notifications": "^0.9.6",
                "classlist.js": "^1.1.20150312",
                "core-js": "^2.5.1",
                "intl": "^1.2.5",
                "libphonenumber-js": "^0.4.40",
                "rxjs": "5.5.2",
                "web-animations-js": "^2.3.1",
                "zone.js": "^0.8.18"
              },
              "devDependencies": {
                "@angular/cli": "^1.5.0",
                "@angular/compiler-cli": "^5.0.2",
                "@types/jasmine": "2.5.38",
                "@types/node": "^6.0.92",
                "angular-in-memory-web-api": "^0.3.2",
                "autoprefixer": "^6.5.3",
                "cldr-data": "^31.0.2",
                "codelyzer": "~2.0.0",
                "css-loader": "^0.27.3",
                "cssnano": "^3.10.0",
                "exports-loader": "^0.6.3",
                "file-loader": "^0.10.0",
                "istanbul-instrumenter-loader": "^2.0.0",
                "jasmine-core": "~2.5.2",
                "jasmine-spec-reporter": "~3.2.0",
                "json-loader": "^0.5.4",
                "jszip": "^3.1.3",
                "karma": "~1.4.1",
                "karma-chrome-launcher": "~2.0.0",
                "karma-cli": "~1.0.1",
                "karma-coverage-istanbul-reporter": "^0.2.0",
                "karma-jasmine": "~1.1.0",
                "karma-jasmine-html-reporter": "^0.2.2",
                "karma-sourcemap-loader": "^0.3.7",
                "less-loader": "^4.0.2",
                "postcss-loader": "^1.3.3",
                "postcss-url": "^5.1.2",
                "protractor": "~5.1.0",
                "raw-loader": "^0.5.1",
                "rollup": "^0.43.0",
                "rollup-plugin-commonjs": "^8.0.2",
                "rollup-plugin-node-resolve": "^3.0.0",
                "rollup-plugin-uglify": "^2.0.1",
                "sass-loader": "^6.0.3",
                "script-loader": "^0.7.0",
                "source-map-loader": "^0.1.5",
                "style-loader": "^0.13.1",
                "stylus-loader": "^3.0.1",
                "systemjs": "^0.20.19",
                "systemjs-plugin-babel": "0.0.25",
                "systemjs-plugin-json": "^0.3.0",
                "ts-node": "~2.0.0",
                "tslib": "^1.6.1",
                "tslint": "~4.5.0",
                "typescript": "2.4.2",
                "url-loader": "^0.5.7",
                "webpack-dev-server": "~2.4.2"
              }
            }

Below is my tsconfig.json

    {
      "compileOnSave": true,
      "compilerOptions": {
        "importHelpers": true,
        "baseUrl": "src",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es2017",
        "typeRoots": [
          "node_modules/@types"
        ],
        "lib": [
          "es7",
          "dom"
        ]
      },
      "exclude": [
        "test.ts",
        "**/*.spec.ts",
        "node_modules",
        "dist",
        "../Scripts"
      ]
    }

Please help.  This is very frustrating.

Thanks.

Body:
Try this packages.json:

{
              "name": "mic",
              "version": "0.0.0",
              "license": "MIT",
              "scripts": {
                "ng": "ng",
                "start": "webpack-dev-server --port=4200",
                "build": "webpack -p",
                "test": "karma start ./karma.conf.js",
                "lint": "ng lint",
                "e2e": "protractor ./protractor.conf.js",
                "copy": "xcopy \"dist\" \"..\\Mic\\Scripts\\NgApp\" /i /s /r /y /c",
                "prepree2e": "npm start",
                "pree2e": "webdriver-manager update --standalone false --gecko false --quiet"
              },
              "private": true,
              "dependencies": {
                "@angular/animations": "5.0.0",
                "@angular/common": "5.0.0",
                "@angular/compiler": "5.0.0",
                "@angular/core": "5.0.0",
                "@angular/forms": "5.0.0",
                "@angular/http": "5.0.0",
                "@angular/platform-browser": "5.0.0",
                "@angular/platform-browser-dynamic": "5.0.0",
                "@angular/router": "5.0.0",
                "@angular/platform-server": "5.0.0",
                "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.5",
                "@progress/kendo-angular-buttons": "^1.1.1",
                "@progress/kendo-angular-dateinputs": "^1.4.0",
                "@progress/kendo-angular-dialog": "^1.3.0",
                "@progress/kendo-angular-dropdowns": "^1.2.3",
                "@progress/kendo-angular-excel-export": "^1.0.5",
                "@progress/kendo-angular-grid": "^1.6.1",
                "@progress/kendo-angular-inputs": "^1.3.3",
                "@progress/kendo-angular-intl": "^1.3.0",
                "@progress/kendo-angular-l10n": "^1.0.5",
                "@progress/kendo-angular-popup": "^1.3.0",
                "@progress/kendo-angular-resize-sensor": "^1.0.5",
                "@progress/kendo-data-query": "^1.1.1",
                "@progress/kendo-drawing": "^1.4.0",
                "@progress/kendo-file-saver": "^1.0.4",
                "@progress/kendo-popup-common": "^1.2.3",
                "@progress/kendo-theme-default": "^2.44.0",
                "@telerik/kendo-intl": "^1.3.0",
                "angular2-notifications": "^0.9.6",
                "classlist.js": "^1.1.20150312",
                "core-js": "^2.5.1",
                "intl": "^1.2.5",
                "libphonenumber-js": "^0.4.40",
                "rxjs": "5.5.2",
                "web-animations-js": "^2.3.1",
                "zone.js": "^0.8.18"
              },
              "devDependencies": {
                "@angular/cli": "^1.5.0",
                "@angular/compiler-cli": "^5.0.2",
                "@types/jasmine": "2.5.38",
                "@types/node": "^6.0.92",
                "angular-in-memory-web-api": "^0.3.2",
                "autoprefixer": "^6.5.3",
                "cldr-data": "^31.0.2",
                "codelyzer": "~2.0.0",
                "css-loader": "^0.27.3",
                "cssnano": "^3.10.0",
                "exports-loader": "^0.6.3",
                "file-loader": "^0.10.0",
                "istanbul-instrumenter-loader": "^2.0.0",
                "jasmine-core": "~2.5.2",
                "jasmine-spec-reporter": "~3.2.0",
                "json-loader": "^0.5.4",
                "jszip": "^3.1.3",
                "karma": "~1.4.1",
                "karma-chrome-launcher": "~2.0.0",
                "karma-cli": "~1.0.1",
                "karma-coverage-istanbul-reporter": "^0.2.0",
                "karma-jasmine": "~1.1.0",
                "karma-jasmine-html-reporter": "^0.2.2",
                "karma-sourcemap-loader": "^0.3.7",
                "less-loader": "^4.0.2",
                "postcss-loader": "^1.3.3",
                "postcss-url": "^5.1.2",
                "protractor": "~5.1.0",
                "raw-loader": "^0.5.1",
                "rollup": "^0.43.0",
                "rollup-plugin-commonjs": "^8.0.2",
                "rollup-plugin-node-resolve": "^3.0.0",
                "rollup-plugin-uglify": "^2.0.1",
                "sass-loader": "^6.0.3",
                "script-loader": "^0.7.0",
                "source-map-loader": "^0.1.5",
                "style-loader": "^0.13.1",
                "stylus-loader": "^3.0.1",
                "systemjs": "^0.20.19",
                "systemjs-plugin-babel": "0.0.25",
                "systemjs-plugin-json": "^0.3.0",
                "ts-node": "~2.0.0",
                "tslib": "^1.6.1",
                "tslint": "~4.5.0",
                "typescript": "2.6.1",
                "url-loader": "^0.5.7",
                "webpack-dev-server": "~2.4.2"
              }
            }

delete node_modules folder & run npm install


问:
remove array object from nested array if element is undefined using javascript
Raw array

```<code>myArr = [
{name:'abcd',values:[undefined,{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129},undefined]},
{name:'abcd',values:[undefined,undefined,{quarter: "Q4-2016", koordinaten: 19},undefined]}
]
</code>```

Expected array,

```<code> myArr = [
        {name:'abcd',values:[{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129}},
        {name:'abcd',values:[{quarter: "Q4-2016", koordinaten: 19}]}
        ]
</code>```

i want to remove undefined element with index  in result array,

答:
This should do the trick, you basically need to remove all the undefined values by looping through them.

myArr = [
{name:'abcd',values:[undefined,{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129},undefined]},
{name:'abcd',values:[undefined,undefined,{quarter: "Q4-2016", koordinaten: 19},undefined]}
]

myArr.forEach(arrItem => {
 arrItem.values = arrItem.values.filter(x => !!x);
});

console.log(myArr);```

Body:
Raw array

myArr = [
{name:'abcd',values:[undefined,{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129},undefined]},
{name:'abcd',values:[undefined,undefined,{quarter: "Q4-2016", koordinaten: 19},undefined]}
]

Expected array,

 myArr = [
        {name:'abcd',values:[{quarter: "Q2-2016", koordinaten: 119},{quarter: "Q3-2016", koordinaten: 129}},
        {name:'abcd',values:[{quarter: "Q4-2016", koordinaten: 19}]}
        ]

i want to remove undefined element with index  in result array,


问:
SceneKit. How to rotate SCNNode around its axis
I'm trying to achieve same rotation as in scene editor but with code so object always rotate around selected axis, however if I look at angles(x,y,z) in editor they changes quite randomly

![Local node axis][1]

I've tried to use quaternions, but can't get it working

PS. my bad was using rotation property instead of orientation both SCNVector4, have read doc properly)

答:
Seems you was really close, you had to swap parameters in GLKQuaternionMultiply call. I used solution in https://stackoverflow.com/a/39813058/4124265 to achieve rotation only by Z axis:

```<code>    let orientation = modelNode.orientation
    var glQuaternion = GLKQuaternionMake(orientation.x, orientation.y, orientation.z, orientation.w)

    // Rotate around Z axis
    let multiplier = GLKQuaternionMakeWithAngleAndAxis(0.5, 0, 0, 1)
    glQuaternion = GLKQuaternionMultiply(glQuaternion, multiplier)

    modelNode.orientation = SCNQuaternion(x: glQuaternion.x, y: glQuaternion.y, z: glQuaternion.z, w: glQuaternion.w)
</code>```

To rotate arround Y:

```<code>    // Rotate around Y axis
    let multiplier = GLKQuaternionMakeWithAngleAndAxis(0.5, 0, 1, 0)
    glQuaternion = GLKQuaternionMultiply(glQuaternion, multiplier)
</code>```

Body:
Seems you was really close, you had to swap parameters in GLKQuaternionMultiply call. I used solution in https://stackoverflow.com/a/39813058/4124265 to achieve rotation only by Z axis:

    let orientation = modelNode.orientation
    var glQuaternion = GLKQuaternionMake(orientation.x, orientation.y, orientation.z, orientation.w)

    // Rotate around Z axis
    let multiplier = GLKQuaternionMakeWithAngleAndAxis(0.5, 0, 0, 1)
    glQuaternion = GLKQuaternionMultiply(glQuaternion, multiplier)

    modelNode.orientation = SCNQuaternion(x: glQuaternion.x, y: glQuaternion.y, z: glQuaternion.z, w: glQuaternion.w)

To rotate arround Y:

    // Rotate around Y axis
    let multiplier = GLKQuaternionMakeWithAngleAndAxis(0.5, 0, 1, 0)
    glQuaternion = GLKQuaternionMultiply(glQuaternion, multiplier)


问:
Drools-Spring MVC Integration | Failed to read schema document | No declaration can be found for element 'kie:kmodule'
I am trying to do a POC to integrate Spring MVC with Drools.

My mvc-dispatcher-servlet.xml file tries to read the kie-spring.xsd file .

The file location on drools website gives 404.As a result the schema is not accessible and it gives warning as below.

"WARNING: Ignored XML validation warning
org.xml.sax.SAXParseException; lineNumber: 25; columnNumber: 35; schema_reference.4: Failed to read schema document 'http://drools.org/schema/kie-spring.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not ."

The above warning seems to result in error at line 25 .I the file it shows error as "The matching wildcard is strict, but no declaration can be found for element 'kie:kmodule'."
When Below is the error::

"SEVERE: Context initialization failed
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 25 in XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 25; columnNumber: 35; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'kie:kmodule'."

I found the same issue mentioned in another Stackoverflow question here.
However the two solutions mentioned for it did not resolve the issue.

Below is the mvc-dispatcher-servlet.xml::

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

    <context:component-scan base-package="com.kiespring.mvc.controller" />

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

  <bean id="kieUtil" class="org.kie.spring.KieSpringUtil"/>

  <kie:kmodule id="sample_module">
    <kie:kbase name="kbase1" packages="org.drools.spring.sample"/>
  </kie:kmodule>

  <bean id="kiePostProcessor" class="org.kie.spring.KModuleBeanFactoryPostProcessor"/>
</beans>
</code>```

POM file:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.kie.sample</groupId>
    <artifactId>kie-springmvc</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>kie-springmvc Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    <kie.spring.version>6.0.1.FINAL</kie.spring.version>
    </properties>

    <dependencies>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-spring</artifactId>
      <version>${kie.spring.version}</version>
    </dependency>
    </dependencies>

    <build>
        <finalName>kie-springmvc</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I have made changes in settings.xml for http in my maven installation global and user settings.

Any feedback or suggestion is welcome.

答:
Google for a suitable kie-spring.xsd. E.g:

github.com/kiegroup/droolsjbpm-integration/blob/master/kie-spring/src/main/resources/org/kie/spring/kie-spring-6.0.0.xsd

Copy it to a location you can control. Change the URL.

Body:
I am trying to do a POC to integrate Spring MVC with Drools.

My mvc-dispatcher-servlet.xml file tries to read the kie-spring.xsd file .

The file location on drools website gives 404.As a result the schema is not accessible and it gives warning as below.

"WARNING: Ignored XML validation warning
org.xml.sax.SAXParseException; lineNumber: 25; columnNumber: 35; schema_reference.4: Failed to read schema document 'http://drools.org/schema/kie-spring.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not ."

The above warning seems to result in error at line 25 .I the file it shows error as "The matching wildcard is strict, but no declaration can be found for element 'kie:kmodule'."
When Below is the error::

"SEVERE: Context initialization failed
org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 25 in XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 25; columnNumber: 35; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'kie:kmodule'."

I found the same issue mentioned in another Stackoverflow question here.
However the two solutions mentioned for it did not resolve the issue.

Below is the mvc-dispatcher-servlet.xml::

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

    <context:component-scan base-package="com.kiespring.mvc.controller" />

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

  <bean id="kieUtil" class="org.kie.spring.KieSpringUtil"/>

  <kie:kmodule id="sample_module">
    <kie:kbase name="kbase1" packages="org.drools.spring.sample"/>
  </kie:kmodule>

  <bean id="kiePostProcessor" class="org.kie.spring.KModuleBeanFactoryPostProcessor"/>
</beans>

POM file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.kie.sample</groupId>
    <artifactId>kie-springmvc</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>kie-springmvc Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    <kie.spring.version>6.0.1.FINAL</kie.spring.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-spring</artifactId>
      <version>${kie.spring.version}</version>
    </dependency>
    </dependencies>

    <build>
        <finalName>kie-springmvc</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

I have made changes in settings.xml for http in my maven installation global and user settings.

Any feedback or suggestion is welcome.


问:
HIVE - INSERT OVERWRITE using WITH CLAUSE
I have a generated query starts with the WITH clause which is working fine when i am running it in console, when i try to run the query with INSERT OVERWRITE to load the output into a separate hive table

```<code>INSERT OVERWRITE TABLE $proc_db.$master_table PARTITION(created_dt, country) $master_query
</code>```

it throws the following error

```<code>cannot recognize input near 'WITH' 't' 'as' in statement
</code>```

The query as follows:

```<code>master_query="
WITH t
AS (
SELECT subscription_id
    ,country
    ,email_type
    ,email_priority
    ,created_dt
FROM crm_arrow.birthday
WHERE created_dt = '2016-07-07'
    AND (COUNTRY = 'SG')
GROUP BY subscription_id
    ,country
    ,email_type
    ,email_priority
    ,created_dt

UNION ALL

SELECT subscription_id
    ,country
    ,email_type
    ,email_priority
    ,created_dt
FROM crm_arrow.wishlist
WHERE created_dt = '2016-07-07'
    AND (COUNTRY = 'SG')
GROUP BY subscription_id
    ,country
    ,email_type
    ,email_priority
    ,created_dt

UNION ALL
.....
)
SELECT q.subscription_id
,q.country
,q.email_type
FROM (
SELECT t1.subscription_id
    ,t1.country
    ,DENSE_RANK() OVER (
        PARTITION BY t1.subscription_id
        ,t1.country ORDER BY t1.email_priority
        ) global_rank
    ,CASE
        WHEN t1.email_type = t2.email_type
            THEN t1.email_type
        END email_type
FROM t t1
LEFT JOIN t t2 ON t1.country = t2.country
    AND t1.subscription_id = t2.subscription_id
) q
WHERE q.email_type IS NOT NULL
AND (
    q.global_rank <= 2
    AND country = 'SG'
    )
"
</code>```

How can i make an efficient self join with a huge inner query ? I have also tried to enclose select statement across the master_query but it's still not working.

答:
You need to change your query to something like this, so that INSERT OVERWRITE comes before SELECT q.subscription_id clause in your query:-

Please see this sample. Use 1 or multiple with on top, then write INSERT OVERWRITE immediately followed by select query:-

```<code>WITH TABLE1
AS
(
    SELECT
    cod_index,
    CAST(test_1 AS VARCHAR(200)),
    CAST(test_2 AS VARCHAR(200)),
    CAST(test_3 AS VARCHAR(200))
    FROM db_h_gss.tb_h_test_orig
)
INSERT INTO TABLE db_h_gss.tb_h_test_insert PARTITION (cod_index = 1)
SELECT
    test_1,
    test_2,
    test_3
FROM TABLE1 WHERE cod_index = 1;
</code>```

Body:
I have a generated query starts with the WITH clause which is working fine when i am running it in console, when i try to run the query with INSERT OVERWRITE to load the output into a separate hive table

INSERT OVERWRITE TABLE $proc_db.$master_table PARTITION(created_dt, country) $master_query

it throws the following error

cannot recognize input near 'WITH' 't' 'as' in statement

The query as follows:

master_query="
WITH t
AS (
SELECT subscription_id
    ,country
    ,email_type
    ,email_priority
    ,created_dt
FROM crm_arrow.birthday
WHERE created_dt = '2016-07-07'
    AND (COUNTRY = 'SG')
GROUP BY subscription_id
    ,country
    ,email_type
    ,email_priority
    ,created_dt

UNION ALL

SELECT subscription_id
    ,country
    ,email_type
    ,email_priority
    ,created_dt
FROM crm_arrow.wishlist
WHERE created_dt = '2016-07-07'
    AND (COUNTRY = 'SG')
GROUP BY subscription_id
    ,country
    ,email_type
    ,email_priority
    ,created_dt

UNION ALL
.....
)
SELECT q.subscription_id
,q.country
,q.email_type
FROM (
SELECT t1.subscription_id
    ,t1.country
    ,DENSE_RANK() OVER (
        PARTITION BY t1.subscription_id
        ,t1.country ORDER BY t1.email_priority
        ) global_rank
    ,CASE
        WHEN t1.email_type = t2.email_type
            THEN t1.email_type
        END email_type
FROM t t1
LEFT JOIN t t2 ON t1.country = t2.country
    AND t1.subscription_id = t2.subscription_id
) q
WHERE q.email_type IS NOT NULL
AND (
    q.global_rank <= 2
    AND country = 'SG'
    )
"

How can i make an efficient self join with a huge inner query ? I have also tried to enclose select statement across the master_query but it's still not working.

Body:
You need to change your query to something like this, so that INSERT OVERWRITE comes before SELECT q.subscription_id clause in your query:-

Please see this sample. Use 1 or multiple with on top, then write INSERT OVERWRITE immediately followed by select query:-

WITH TABLE1
AS
(
    SELECT
    cod_index,
    CAST(test_1 AS VARCHAR(200)),
    CAST(test_2 AS VARCHAR(200)),
    CAST(test_3 AS VARCHAR(200))
    FROM db_h_gss.tb_h_test_orig
)
INSERT INTO TABLE db_h_gss.tb_h_test_insert PARTITION (cod_index = 1)
SELECT
    test_1,
    test_2,
    test_3
FROM TABLE1 WHERE cod_index = 1;

ContentLicense: CC BY-SA 4.0


问:
Finding the idNumber element from this below HTML code
```<code><div id="rightContent" style="display: inline-block; width: 700px; vertical-align: top;">
                <div>
                    <h1><em class="SomethingHeading">Something</em></h1>
                </div>

<div class="content scaffold-list" role="main">
    <h1>Search</h1>

    <form action="/SomethingArchiveUI/search/search" method="post">
        <table>
            <tbody>
            <tr>
                <td>ID/Registration Number:</td>
                <td>
                    <**input type="text" name="idNumber" maxlength="20" value="" id="idNumber"**>
                </td>
            </tr>
            <tr>
                <td>Client Name:</td>
                <td>
                    <input type="text" name="clientName" maxlength="50" value="" id="clientName">
                </td>
            </tr>
            <tr>
                <td>Client Surname:</td>
                <td>
                    <input type="text" name="clientSurname" maxlength="50" value="" id="clientSurname">
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="hidden" name="_dateRange"><input type="checkbox" name="dateRange" value="true" id="dateRange"><label for="dateRange"> Use date range?</label>
                </td>
            </tr>
            <tr>
                <td colspan="2"><p>From: <input type="text" name="fromDate" value="" maxlength="10" id="fromDate" class="hasDatepicker"> To: <input type="text" name="toDate" value="" maxlength="10" id="toDate" class="hasDatepicker"></p></td>
            </tr>
            </tbody>
        </table>
        <div style="display: inline;">
            <div id="divSubmit">
                <input type="submit" name="cmdSearch" class="buttons" value="Search" id="cmdSearch">
            </div>
            <div id="divBusy" style="display: none;">
                Busy Searching...
            </div>
        </div>
    </form>

    <table id="customerIdentificationList" style="display: block;">

    </table>
    <div id="loadingMessage" style="display: none;">
        Loading. Please wait.
    </div>
</div>

            </div>
</code>```

I used this code below for logging into the Application, but similar code doesn't seem to work on this form above. I'm trying to find the 'idNumber' element:

```<code>driver.findElement(By.xpath("//*[@id='idnumber']")).sendKeys("Username");
driver.findElement(By.xpath("//*[@id=\'password\']")).sendKeys("Password");
driver.findElement(By.xpath("//*[@id=\'submit\']")).click();
</code>```

The error i get is: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":

Looking forward to your responses.

答:
Try using the below way -

First get the root element and keep it to a WebElement object. Then find for input element idNumber

```<code>WebElement elem = driver.findElement(By.cssSelector("#rightContent > div.content.scaffold-list > form"));
elem.findElement(By.id("idNumber")).sendKeys("Username");
</code>```

Body:
Something

Search

    <form action="/SomethingArchiveUI/search/search" method="post">

                ID/Registration Number:

                    <**input type="text" name="idNumber" maxlength="20" value="" id="idNumber"**>

                Client Name:

                    <input type="text" name="clientName" maxlength="50" value="" id="clientName">

                Client Surname:

                    <input type="text" name="clientSurname" maxlength="50" value="" id="clientSurname">

                    <input type="hidden" name="_dateRange"><input type="checkbox" name="dateRange" value="true" id="dateRange"> Use date range?

From: <input type="text" name="fromDate" value="" maxlength="10" id="fromDate" class="hasDatepicker"> To: <input type="text" name="toDate" value="" maxlength="10" id="toDate" class="hasDatepicker">

                <input type="submit" name="cmdSearch" class="buttons" value="Search" id="cmdSearch">

                Busy Searching...

    </form>

        Loading. Please wait.

I used this code below for logging into the Application, but similar code doesn't seem to work on this form above. I'm trying to find the 'idNumber' element:

driver.findElement(By.xpath("//*[@id='idnumber']")).sendKeys("Username");
driver.findElement(By.xpath("//*[@id=\'password\']")).sendKeys("Password");
driver.findElement(By.xpath("//*[@id=\'submit\']")).click();

The error i get is: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":

Looking forward to your responses.

Body:
Try using the below way -

First get the root element and keep it to a WebElement object. Then find for input element idNumber

WebElement elem = driver.findElement(By.cssSelector("#rightContent > div.content.scaffold-list > form"));
elem.findElement(By.id("idNumber")).sendKeys("Username");


问:
Find valid time period for given date
I issue is to find valid price for given date using two SQL tables.
First table columns look like:

```<code>Item_ID | Date
</code>```

and the second is like:

```<code>Item_ID | FromDate1 | Price1 | FromDate2 | Price2 | FromDate3 | Price3 | FromDate4 | Price4 | EndDate
</code>```

I want to write Query, where the result will be like :

```<code>Item_ID | Date | Valid_Price
</code>```

As you probably guessed Valid_Price depends on the date. E.g.

If first.FromDate(x) < second.Date < first.FromDate(x+1)

result.Valid_Price = first.Price(x)

Of course Item_ID must be the same in both tables, but I know i can do it with WHERE or ON. Do You have any ideas how to include above conditions in SQL query?

P.S. sometimes only few columns are filled. E.g. there might be only FromDate1, Price1, EndDate, and rest of values are NULLs.

答:
Case statement was very helpful. This block of code finally looks like:

```<code>     CASE WHEN first.[Date] >= FromDate6 THEN Price6
          WHEN first.[Date] >= FromDate5 THEN Price5
          WHEN first.[Date] >= FromDate4 THEN Price4
          WHEN first.[Date] >= FromDate3 THEN Price3
          WHEN first.[Date] >= FromDate2 THEN Price2
          WHEN first.[Date] >= FromDate1 THEN Price1
          ELSE NULL
     END AS price
</code>```

(...)

```<code>ON FIRST.[Date] <= EndDate
</code>```

Title: Find valid time period for given date

Body:
I issue is to find valid price for given date using two SQL tables.
First table columns look like:

Item_ID | Date

and the second is like:

Item_ID | FromDate1 | Price1 | FromDate2 | Price2 | FromDate3 | Price3 | FromDate4 | Price4 | EndDate

I want to write Query, where the result will be like :

Item_ID | Date | Valid_Price

As you probably guessed Valid_Price depends on the date. E.g.

If first.FromDate(x) < second.Date < first.FromDate(x+1)

result.Valid_Price = first.Price(x)

Of course Item_ID must be the same in both tables, but I know i can do it with WHERE or ON. Do You have any ideas how to include above conditions in SQL query?

P.S. sometimes only few columns are filled. E.g. there might be only FromDate1, Price1, EndDate, and rest of values are NULLs.

Body:
Case statement was very helpful. This block of code finally looks like:

     CASE WHEN first.[Date] >= FromDate6 THEN Price6
          WHEN first.[Date] >= FromDate5 THEN Price5
          WHEN first.[Date] >= FromDate4 THEN Price4
          WHEN first.[Date] >= FromDate3 THEN Price3
          WHEN first.[Date] >= FromDate2 THEN Price2
          WHEN first.[Date] >= FromDate1 THEN Price1
          ELSE NULL
     END AS price

(...)

ON FIRST.[Date] <= EndDate


问:
Multiple concurrent event handling in jQuery
I am attempting to handle multiple concurrent events using jQuery but I am having problems finely managing when the events are fired.

```<code><html>
  <head>
  <title></title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  </head>
  <body>

    <div id="edit" contenteditable="true">Edit some content</div>
    <button id="button" type="button">Click the button</button>

    <script type="text/javascript">
      $(document).ready(function () {
        $('#button').click(function (e) {
          alert('I have been clicked.');
        });
        $('#edit').blur(function (e) {
          alert('I have been edited.')
        });
      });
    </script>

  </body>
</html>
</code>```

What I wish to achieve is for the content of the DIV to be edited by a user and when the button is clicked, for that event to be raised before the blur event on the DIV. It may be the case that the button is never clicked in which case the blur event may fire on its own. As you can see using the code above, once you edit the content and click the button only the blur event is fired.

Please can someone advise how I may achieve the desired functionality?

答:
One — admittingly very hacky — way would look like this:

```<code>$(document).ready(function() {
    var buttonClicked = false;
    $('#button').bind('click', function(e) {
        buttonClicked = true;
        alert('I have been clicked.');
    });
    $('#edit').bind('blur', function(e) {
        setTimeout(function() {
            if (!buttonClicked) alert('I have been edited.');
            buttonClicked = false;
        }, 100);

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

This example doesn't prevent the firing of the event, though. It only handles the callback.

Here it is working: http://jsfiddle.net/Dp6b5/1/
You can adjust the timeout delay and don't necessarily have to use bind in this case either.

It's an interesting question, but I don't see any "proper" way to handle this atm., since the blur event is de facto fired before the click. Maybe someone else has a better idea I can't see atm..

Body:
I am attempting to handle multiple concurrent events using jQuery but I am having problems finely managing when the events are fired.

  <title></title>

Edit some content

    <button id="button" type="button">Click the button</button>

What I wish to achieve is for the content of the DIV to be edited by a user and when the button is clicked, for that event to be raised before the blur event on the DIV. It may be the case that the button is never clicked in which case the blur event may fire on its own. As you can see using the code above, once you edit the content and click the button only the blur event is fired.

Please can someone advise how I may achieve the desired functionality?

Body:
One — admittingly very hacky — way would look like this:

$(document).ready(function() {
    var buttonClicked = false;
    $('#button').bind('click', function(e) {
        buttonClicked = true;
        alert('I have been clicked.');
    });
    $('#edit').bind('blur', function(e) {
        setTimeout(function() {
            if (!buttonClicked) alert('I have been edited.');
            buttonClicked = false;
        }, 100);

    });
});

This example doesn't prevent the firing of the event, though. It only handles the callback.

Here it is working: http://jsfiddle.net/Dp6b5/1/
You can adjust the timeout delay and don't necessarily have to use bind in this case either.

It's an interesting question, but I don't see any "proper" way to handle this atm., since the blur event is de facto fired before the click. Maybe someone else has a better idea I can't see atm..


问:
Optional monad and the Law of Demeter in Java
while I was reviewing some code, I came across this snippet.

```<code>List<User> users = /* Some code that initializes the list */;
users.stream()
     .filter(user -> user.getAddress().isPresent())
     .map(/* Some code */)
// And so on...
</code>```

The call of method user.getAddress() returns an Optional<Address>. Following the famous Law of Demeter (LoD), the above code is not clean. However, I cannot figure out how to refactor it to make it cleaner.

As a first attempt could be to add to the User class a method hasAddress(), but this method overcomes the need of having an Optional<Address>, IMO.

How should I refactor the above code? In this case, is it worth to satisfy the LoD?

EDIT: I missed specifying that in the map method I do not want to return the address.

答:
Don't know if it's cleaner (as you need to use the fact that getAddress returns an optional anyway), but in Java 9 you can do:

```<code>users.stream()
    .map(User::getAddress)
    .flatMap(Optional::stream)
    .map(/* Some code */)
</code>```

or

```<code>users.stream()
    .flatMap(user -> user.getAddress().stream())
    .map(/* Some code */)
</code>```

Body:
while I was reviewing some code, I came across this snippet.

List<User> users = /* Some code that initializes the list */;
users.stream()
     .filter(user -> user.getAddress().isPresent())
     .map(/* Some code */)
// And so on...

The call of method user.getAddress() returns an Optional<Address>. Following the famous Law of Demeter (LoD), the above code is not clean. However, I cannot figure out how to refactor it to make it cleaner.

As a first attempt could be to add to the User class a method hasAddress(), but this method overcomes the need of having an Optional<Address>, IMO.

How should I refactor the above code? In this case, is it worth to satisfy the LoD?

EDIT: I missed specifying that in the map method I do not want to return the address.

Body:
Don't know if it's cleaner (as you need to use the fact that getAddress returns an optional anyway), but in Java 9 you can do:

users.stream()
    .map(User::getAddress)
    .flatMap(Optional::stream)
    .map(/* Some code */)

or

users.stream()
    .flatMap(user -> user.getAddress().stream())
    .map(/* Some code */)


问:
difference between withRegion() and withEndpointConfiguration() method in aws s3 or sqs client
what is difference between withRegion() and withEndpointConfiguration() method in aws S3 or SQS client.

UsingEndpointConfiguration needs endPoint and signingRegion. Is this signingRegion same as of s3 bucket? If yes, then why we need to specify it twice as region will be part of endpoint also.
Example: us-west-2 in s3-us-west-2.amazonaws.com

答: You can either use withRegion() or withEndpointConfiguration(). If you use withRegion() it's not mandated to use withEndpointConfiguration(), because the AWS api will take care of the remaining(forming the endpoint). if you are using withEndpointConfiguration(), the parameters of EndpointConfiguration(String serviceEndpoint,String signingRegion) are both the type of string, the AWS api won't create a substring to get the region from the first parameter, as Region is a mandated one, otherwise it will use the DEFAULT_REGION_PROVIDER to set the Region. For more see AwsClientBuilder


问:
Using AWK to sort lines and columns together
I'm doing an assignment where I've been asked to find files between a certain size and sha1sum them.  I've specifically been asked to provide the output in the following format:

Filename Sha1 File Size

all on one line.  I'm not able to create additional files.

I've tried the following:

```<code>for listed in $(find /my/output -type f -size -20000c):
do
sha1sum "$listed" | awk '{print $1}'
ls -l "$listed" | awk '{print $9 $5}'
done
</code>```

which gives me the required output fields, but not in the requested format, i.e.

```<code>sha1sum
filename filesize
</code>```

Could anyone suggest a manner in which I'd be able to get all of this on a single line?

Thank you :)

答:
With single pipeline:

```<code>find /my/path-type f -size -20000c -printf "%s " -exec sha1sum {} \; | awk '{ print $3,$2,$1 }'
</code>```

An exemplary output (as a result of my local test) in the needed format FILENAME SHA1 FILESIZE:

```<code>./GSE11111/GSE11111_RAW.tar 9ed615fcbcb0b771fcba1f2d2e0aef6d3f0f8a11 25446400
./artwork_tmp 3a43f1be6648cde0b30fecabc3fa795a6ae6d30a 40010166
</code>```

Body:
I'm doing an assignment where I've been asked to find files between a certain size and sha1sum them.  I've specifically been asked to provide the output in the following format:

Filename Sha1 File Size

all on one line.  I'm not able to create additional files.

I've tried the following:

for listed in $(find /my/output -type f -size -20000c):
do
sha1sum "$listed" | awk '{print $1}'
ls -l "$listed" | awk '{print $9 $5}'
done

which gives me the required output fields, but not in the requested format, i.e.

sha1sum
filename filesize

Could anyone suggest a manner in which I'd be able to get all of this on a single line?

Thank you :)

Body:
With single pipeline:

find /my/path-type f -size -20000c -printf "%s " -exec sha1sum {} \; | awk '{ print $3,$2,$1 }'

An exemplary output (as a result of my local test) in the needed format FILENAME SHA1 FILESIZE:

./GSE11111/GSE11111_RAW.tar 9ed615fcbcb0b771fcba1f2d2e0aef6d3f0f8a11 25446400
./artwork_tmp 3a43f1be6648cde0b30fecabc3fa795a6ae6d30a 40010166


问:
Change color of error messages in RMarkdown code output (HTML, PDF)
Is there a way to automatically make text color of errors red in R Markdown without manually editing the HTML later.

```<code>---
title: ""
---

#### Example 1

```{r e1, error = TRUE}
2 + "A"
```

#### Example 2

```{r e2, error = TRUE}
2 + 2
```
</code>```

In the above code, output of Example 1 would have to be red. Currently, I edit the generated HTML (add style="color:red;" to the appropriate tag) but I am wondering if there is an automatic way. Assume that it is not known before knitting whether the code will generate error.

答:
1. Use a knitr hook

The preferred solution is to use the output hook for errors:

```<code>```{r}
knitr::knit_hooks$set(error = function(x, options) {
  paste0("
", x, "```")
})
```
```
<p>Output hooks in general allow us to control the output of different parts of our R code (the whole chunk, the source code, errors, warnings, ...). For details check https://yihui.name/knitr/hooks/#output-hooks.</p>
<p><img src="https://i.stack.imgur.com/JXQXwm.png" alt="enter image description here" /></p>
<hr />
<h2>2. Quick and dirty solution using JS/jQuery</h2>
<p>And this is my "quick and dirty" solution using jQuery/Javascript. Just add it beneath the YAML header.
Might not be bulletproof, since it checks for error messages using the string "Error" which might occur in other applications as well.</p>
```
```

Body:
Is there a way to automatically make text color of errors red in R Markdown without manually editing the HTML later.

---
title: ""
---

#### Example 1

```{r e1, error = TRUE}
2 + "A"
```

#### Example 2

```{r e2, error = TRUE}
2 + 2
```

In the above code, output of Example 1 would have to be red. Currently, I edit the generated HTML (add style="color:red;" to the appropriate tag) but I am wondering if there is an automatic way. Assume that it is not known before knitting whether the code will generate error.

Body:
1. Use a knitr hook

The preferred solution is to use the output hook for errors:

```{r}
knitr::knit_hooks$set(error = function(x, options) {
  paste0("<pre style=\"color: red;\"><code>", x, "</code></pre>")
})
```

Output hooks in general allow us to control the output of different parts of our R code (the whole chunk, the source code, errors, warnings, ...). For details check https://yihui.name/knitr/hooks/#output-hooks.

2. Quick and dirty solution using JS/jQuery

And this is my "quick and dirty" solution using jQuery/Javascript. Just add it beneath the YAML header.
Might not be bulletproof, since it checks for error messages using the string "Error" which might occur in other applications as well.

<script type="text/javascript">
$(document).ready(function() {
  var $chks = $("pre:not(.r) > code");
  $chks.each(function(key, val) {
    cntnt = $(this).html();
    if (cntnt.indexOf("Error") != -1) {
      $(this).css('color', 'red');
    }
  })
})
</script>


问:
Fitting elements into a grid in a responsive way
Consider a
 element that contains <button> elements:

```<code><div id="box">
    <button class="button">1</button>
    <button class="button">2</button>
    <button class="button">3</button>
    ...
</div>
</code>```

I want to fit these elements into a grid pattern, so that

buttons are of equal dimensions and have a fixed minimum width,

a maximal amount of buttons is stacked on each row,

button width is adjusted so that each row is filled completely,

and this behavior persists when #box is resized.

Is there a way to do so using native HTML/CSS features (without using JavaScript)? I tried using the new CSS Flexbox layout:

```<code>#box {
    display: flex;
    width: 500px;
    height: 500px;
}

.button {
    flex: 1 1 auto;
    min-width: 40px;
    height: 40px;
}
</code>```

But this doesn't work..

Thanks for your help!

答:
You can easily use CSS grid layout.
I prefer it over flexbox.

```<code><div id='grid'>
      <button class='button'>1</button>
      <button class='button'>2</button>
      <button class='button'>3</button>
      <button class='button'>4</button>
      <button class='button'>5</button>
      <button class='button'>6</button>
      <button class='button'>7</button>
      <button class='button'>8</button>
      <button class='button'>9</button>
      <button class='button'>10</button>
      <button class='button'>11</button>
      <button class='button'>12</button>
      <button class='button'>13</button>
      <button class='button'>14</button>
      <button class='button'>15</button>
      <button class='button'>16</button>
</div>

<style>
  #grid {
    display: grid;
    grid: 50px / auto-flow;
  }
</style>
</code>```

Here is the codepen.

https://codepen.io/kenanbalija/pen/bYYarj

Body:
Consider a
 element that contains <button> elements:

    <button class="button">1</button>
    <button class="button">2</button>
    <button class="button">3</button>
    ...

I want to fit these elements into a grid pattern, so that

buttons are of equal dimensions and have a fixed minimum width,

a maximal amount of buttons is stacked on each row,

button width is adjusted so that each row is filled completely,

and this behavior persists when #box is resized.

Is there a way to do so using native HTML/CSS features (without using JavaScript)? I tried using the new CSS Flexbox layout:

#box {
    display: flex;
    width: 500px;
    height: 500px;
}

.button {
    flex: 1 1 auto;
    min-width: 40px;
    height: 40px;
}

But this doesn't work..

Thanks for your help!

Body:
You can easily use CSS grid layout.
I prefer it over flexbox.

<div id='grid'>
      <button class='button'>1</button>
      <button class='button'>2</button>
      <button class='button'>3</button>
      <button class='button'>4</button>
      <button class='button'>5</button>
      <button class='button'>6</button>
      <button class='button'>7</button>
      <button class='button'>8</button>
      <button class='button'>9</button>
      <button class='button'>10</button>
      <button class='button'>11</button>
      <button class='button'>12</button>
      <button class='button'>13</button>
      <button class='button'>14</button>
      <button class='button'>15</button>
      <button class='button'>16</button>
</div>

<style>
  #grid {
    display: grid;
    grid: 50px / auto-flow;
  }
</style>

Here is the codepen.

https://codepen.io/kenanbalija/pen/bYYarj


问:
Splitting a string into an array then splitting the array again
I have this string:

```<code>   fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 : 80, FarCry 4 : 55 : 862
</code>```

I want to use a loop to split this string into an array at the comma [,] example:

```<code>[0]fname lname
[1]GTA V: 120 : 00000
[2]Minecraft : 20 : 10
[3]Assassin’s Creed IV : 90 : 800
[4]Payday 2 : 190 : 2001
[5]Wolfenstein TNO : 25 : 80
[6]FarCry 4 : 55 : 862
</code>```

Then I want to use another loop to split this further at : into another array example

```<code>[0]fname lname
[1]GTA V
[2]120
[3]00000
[4]Minecraft
[5]20
[6]10
....
</code>```

Is there a better way of doing this?

currently I have:

```<code>    List<String> lines = new ArrayList<String>();
    while (scan.hasNextLine())
    {
      lines.add(scan.nextLine());
    }

    //converts the list array to string array

    String[] scanarray = lines.toArray(new String[0]);

    //converts the string array into one large string

    String str_array = Arrays.toString(scanarray);

    String[] arraysplit;

    arraysplit = str_array.split("\\s*:\\s*");

    for (int i=0; i<arraysplit.length; i++)
    {
        arraysplit[i] = arraysplit[i].trim();
        //              ^^^^^^^^^^^^ has values with spaces
        System.out.println(scanarray[i]);
    }
</code>```

EDIT:

Currently my program creates 3 identical arrays, containing the example you can see in the second block of code above.

答:
You can use the split method from String class with multiple delimiters</p>

```<code>public static void main(String[] args) {
    String myOriginalString = "   fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 : 80, FarCry 4 : 55 : 862";
    // | is the regex OR operator
    String[] splited = myOriginalString.split(",|:");
    for(String s : splited)
    System.out.println(s.trim());
}
</code>```

Body:
I have this string:

   fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 : 80, FarCry 4 : 55 : 862

I want to use a loop to split this string into an array at the comma [,] example:

[0]fname lname
[1]GTA V: 120 : 00000
[2]Minecraft : 20 : 10
[3]Assassin’s Creed IV : 90 : 800
[4]Payday 2 : 190 : 2001
[5]Wolfenstein TNO : 25 : 80
[6]FarCry 4 : 55 : 862

Then I want to use another loop to split this further at : into another array example

[0]fname lname
[1]GTA V
[2]120
[3]00000
[4]Minecraft
[5]20
[6]10
....

Is there a better way of doing this?

currently I have:

    List<String> lines = new ArrayList<String>();
    while (scan.hasNextLine())
    {
      lines.add(scan.nextLine());
    }

    //converts the list array to string array

    String[] scanarray = lines.toArray(new String[0]);

    //converts the string array into one large string

    String str_array = Arrays.toString(scanarray);

    String[] arraysplit;

    arraysplit = str_array.split("\\s*:\\s*");

    for (int i=0; i<arraysplit.length; i++)
    {
        arraysplit[i] = arraysplit[i].trim();
        //              ^^^^^^^^^^^^ has values with spaces
        System.out.println(scanarray[i]);
    }

EDIT:

Currently my program creates 3 identical arrays, containing the example you can see in the second block of code above.

Body:
You can use the split method from String class with multiple delimiters

public static void main(String[] args) {
    String myOriginalString = "   fname lname, GTA V: 120 : 00000, Minecraft : 20 : 10, Assassin’s Creed IV : 90 : 800, Payday 2 : 190 : 2001 ,Wolfenstein TNO : 25 : 80, FarCry 4 : 55 : 862";
    // | is the regex OR operator
    String[] splited = myOriginalString.split(",|:");
    for(String s : splited)
    System.out.println(s.trim());
}