问:
Add Favicon with React and Webpack
I am attempting to add a favicon to a React-based website that I made using webpack. It has been a total nightmare to add a favicon and I have tried many solutions to no avail. The latest solution that has been recommended to me is called 'favicons-webpack-plugin' which can be found here: https://github.com/jantimon/favicons-webpack-plugin.

If anyone can tell me what I am doing wrong, your assistance would be greatly appreciated.

I get the following error when I run 'npm run start'

This is my directory structure:

This is my webpack.config.js file:

```<code>const path = require('path');
const merge = require('webpack-merge');
const webpack = require('webpack');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const TARGET = process.env.npm_lifecycle_event;
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var favicons = require('favicons'),
    source = 'my-logo.png',           // Source image(s). `string`, `buffer` or array of `{ size: filepath }`
    configuration = {
        appName: null,                  // Your application's name. `string`
        appDescription: null,           // Your application's description. `string`
        developerName: null,            // Your (or your developer's) name. `string`
        developerURL: null,             // Your (or your developer's) URL. `string`
        background: "#fff",             // Background colour for flattened icons. `string`
        path: "/",                      // Path for overriding default icons path. `string`
        url: "/",                       // Absolute URL for OpenGraph image. `string`
        display: "standalone",          // Android display: "browser" or "standalone". `string`
        orientation: "portrait",        // Android orientation: "portrait" or "landscape". `string`
        version: "1.0",                 // Your application's version number. `number`
        logging: false,                 // Print logs to console? `boolean`
        online: false,                  // Use RealFaviconGenerator to create favicons? `boolean`
        icons: {
            android: true,              // Create Android homescreen icon. `boolean`
            appleIcon: true,            // Create Apple touch icons. `boolean`
            appleStartup: true,         // Create Apple startup images. `boolean`
            coast: true,                // Create Opera Coast icon. `boolean`
            favicons: true,             // Create regular favicons. `boolean`
            firefox: true,              // Create Firefox OS icons. `boolean`
            opengraph: true,            // Create Facebook OpenGraph image. `boolean`
            twitter: true,              // Create Twitter Summary Card image. `boolean`
            windows: true,              // Create Windows 8 tile icons. `boolean`
            yandex: true                // Create Yandex browser icon. `boolean`
        }
    },
    callback = function (error, response) {
        if (error) {
            console.log(error.status);  // HTTP error code (e.g. `200`) or `null`
            console.log(error.name);    // Error name e.g. "API Error"
            console.log(error.message); // Error description e.g. "An unknown error has occurred"
        }
        console.log(response.images);   // Array of { name: string, contents: <buffer> }
        console.log(response.files);    // Array of { name: string, contents: <string> }
        console.log(response.html);     // Array of strings (html elements)
    };

favicons(source, configuration, callback);
const pkg = require('./package.json');

const PATHS = {
  app: path.join(__dirname, 'app'),
  build: path.join(__dirname, 'build')
};

process.env.BABEL_ENV = TARGET;

const common = {
  entry: {
    app: PATHS.app
  },
  // Add resolve.extensions
  // '' is needed to allow imports without an extension
  // note the .'s before the extension as it will fail to load without them
  resolve: {
    extensions: ['', '.js', '.jsx', '.json']
  },
  output: {
    path: PATHS.build,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        // Test expects a RegExp! Notethe slashes!
        test: /\.css$/,
        loaders: ['style', 'css'],
        //Include accepts either a path or an array of paths
        include: PATHS.app

      },
      //set up JSX. This accepts js too thanks to RegExp
      {
      test: /\.(js|jsx)$/,
      //enable caching for improved performance during development
      //It uses default OS directory by default. If you need something more custom,
      //pass a path to it. ie: babel?cacheDirectory=<path>
      loaders: [
        'babel?cacheDirectory,presets[]=es2015'
    ],
      //parse only app files Without this it will go thru the entire project.
      //beside being slow this will likely result in an error
      include: PATHS.app
      }
    ]
  }
};

// Default configuration. We will return this if
// Webpack is called outside of npm.
if(TARGET === 'start' || !TARGET){
  module.exports = merge(common, {
    devtool: 'eval-source-map',
    devServer: {
      contentBase: PATHS.build,

      //enable history API fallback so HTML5 HISTORY API based
      // routing works. This is a good default that will come in handy in more
      // complicated setups.
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,

      //display only errors to reduce output amount
      stats: 'errors only',

      //Parse host and port from env so this is easy to customize
      host: process.env.HOST,
      port: process.env.PORT

},

plugins: [
  new webpack.HotModuleReplacementPlugin(),
  new NpmInstallPlugin({
    save: true //--save
  }),
  new FaviconsWebpackPlugin('my-logo.png')

]
});
}

if(TARGET === 'build' || TARGET === 'stats') {
  module.exports = merge(common, {
    entry: {
      vendor: Object.keys(pkg.dependencies).filter(function(v) {
        return v !== 'alt-utils';
      }),
      style: PATHS.style
    },
    output: {
      path: PATHS.build,
      // Output using entry name
      filename: '[name].[chunkhash].js',
      chunkFilename: '[chunkhash].js'
    },
    module: {
      loaders: [
        // Extract CSS during build
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract('style', 'css'),
          include: PATHS.app
        }
      ]
    },
    plugins: [
      // Output extracted CSS to a file
      new ExtractTextPlugin('[name].[chunkhash].css'),
      // Extract vendor and manifest files
      new webpack.optimize.CommonsChunkPlugin({
        names: ['vendor', 'manifest']
      }),
      // Setting DefinePlugin affects React library size!
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"'
      }),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      })
    ]
  });
}
</code>```

This is my server.js file:

```<code>/* Global Requires */

const express    = require('express');
const logger     = require('morgan');
const bodyParser = require('body-parser');
const path       = require('path');
const app        = express();
const ReactDOM = require('react-dom')
var favicon = require('serve-favicon');

if(process.env.NODE_ENV === 'development') {
  console.log('in development.');
  require('dotenv').config();
} else {
  console.log('in production.');
}

/* App Config */
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'build')));
app.use(favicon(__dirname + '/public/favicon.ico'));

app.use(logger('dev'));

/* Server Initialization */
app.get('/', (req, res) => res.sendFile('index.html'));
var port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server initialized on // ${new Date()}`));
</code>```

答:
For future googlers:
You can also use copy-webpack-plugin and add this to webpack's production config:</p>
```<code>plugins: [
  new CopyWebpackPlugin({
    patterns: [
     // relative path is from src
     { from: './static/favicon.ico' }, // <- your path to favicon
    ]
 })
]
</code>```

Title: Add Favicon with React and Webpack

Body:
I am attempting to add a favicon to a React-based website that I made using webpack. It has been a total nightmare to add a favicon and I have tried many solutions to no avail. The latest solution that has been recommended to me is called 'favicons-webpack-plugin' which can be found here: https://github.com/jantimon/favicons-webpack-plugin.

If anyone can tell me what I am doing wrong, your assistance would be greatly appreciated.

I get the following error when I run 'npm run start'

This is my directory structure:

This is my webpack.config.js file:

const path = require('path');
const merge = require('webpack-merge');
const webpack = require('webpack');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const TARGET = process.env.npm_lifecycle_event;
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
var favicons = require('favicons'),
    source = 'my-logo.png',           // Source image(s). `string`, `buffer` or array of `{ size: filepath }`
    configuration = {
        appName: null,                  // Your application's name. `string`
        appDescription: null,           // Your application's description. `string`
        developerName: null,            // Your (or your developer's) name. `string`
        developerURL: null,             // Your (or your developer's) URL. `string`
        background: "#fff",             // Background colour for flattened icons. `string`
        path: "/",                      // Path for overriding default icons path. `string`
        url: "/",                       // Absolute URL for OpenGraph image. `string`
        display: "standalone",          // Android display: "browser" or "standalone". `string`
        orientation: "portrait",        // Android orientation: "portrait" or "landscape". `string`
        version: "1.0",                 // Your application's version number. `number`
        logging: false,                 // Print logs to console? `boolean`
        online: false,                  // Use RealFaviconGenerator to create favicons? `boolean`
        icons: {
            android: true,              // Create Android homescreen icon. `boolean`
            appleIcon: true,            // Create Apple touch icons. `boolean`
            appleStartup: true,         // Create Apple startup images. `boolean`
            coast: true,                // Create Opera Coast icon. `boolean`
            favicons: true,             // Create regular favicons. `boolean`
            firefox: true,              // Create Firefox OS icons. `boolean`
            opengraph: true,            // Create Facebook OpenGraph image. `boolean`
            twitter: true,              // Create Twitter Summary Card image. `boolean`
            windows: true,              // Create Windows 8 tile icons. `boolean`
            yandex: true                // Create Yandex browser icon. `boolean`
        }
    },
    callback = function (error, response) {
        if (error) {
            console.log(error.status);  // HTTP error code (e.g. `200`) or `null`
            console.log(error.name);    // Error name e.g. "API Error"
            console.log(error.message); // Error description e.g. "An unknown error has occurred"
        }
        console.log(response.images);   // Array of { name: string, contents: <buffer> }
        console.log(response.files);    // Array of { name: string, contents: <string> }
        console.log(response.html);     // Array of strings (html elements)
    };

favicons(source, configuration, callback);
const pkg = require('./package.json');

const PATHS = {
  app: path.join(__dirname, 'app'),
  build: path.join(__dirname, 'build')
};

process.env.BABEL_ENV = TARGET;

const common = {
  entry: {
    app: PATHS.app
  },
  // Add resolve.extensions
  // '' is needed to allow imports without an extension
  // note the .'s before the extension as it will fail to load without them
  resolve: {
    extensions: ['', '.js', '.jsx', '.json']
  },
  output: {
    path: PATHS.build,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        // Test expects a RegExp! Notethe slashes!
        test: /\.css$/,
        loaders: ['style', 'css'],
        //Include accepts either a path or an array of paths
        include: PATHS.app

      },
      //set up JSX. This accepts js too thanks to RegExp
      {
      test: /\.(js|jsx)$/,
      //enable caching for improved performance during development
      //It uses default OS directory by default. If you need something more custom,
      //pass a path to it. ie: babel?cacheDirectory=<path>
      loaders: [
        'babel?cacheDirectory,presets[]=es2015'
    ],
      //parse only app files Without this it will go thru the entire project.
      //beside being slow this will likely result in an error
      include: PATHS.app
      }
    ]
  }
};

// Default configuration. We will return this if
// Webpack is called outside of npm.
if(TARGET === 'start' || !TARGET){
  module.exports = merge(common, {
    devtool: 'eval-source-map',
    devServer: {
      contentBase: PATHS.build,

      //enable history API fallback so HTML5 HISTORY API based
      // routing works. This is a good default that will come in handy in more
      // complicated setups.
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,

      //display only errors to reduce output amount
      stats: 'errors only',

      //Parse host and port from env so this is easy to customize
      host: process.env.HOST,
      port: process.env.PORT

},

plugins: [
  new webpack.HotModuleReplacementPlugin(),
  new NpmInstallPlugin({
    save: true //--save
  }),
  new FaviconsWebpackPlugin('my-logo.png')

]
});
}

if(TARGET === 'build' || TARGET === 'stats') {
  module.exports = merge(common, {
    entry: {
      vendor: Object.keys(pkg.dependencies).filter(function(v) {
        return v !== 'alt-utils';
      }),
      style: PATHS.style
    },
    output: {
      path: PATHS.build,
      // Output using entry name
      filename: '[name].[chunkhash].js',
      chunkFilename: '[chunkhash].js'
    },
    module: {
      loaders: [
        // Extract CSS during build
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract('style', 'css'),
          include: PATHS.app
        }
      ]
    },
    plugins: [
      // Output extracted CSS to a file
      new ExtractTextPlugin('[name].[chunkhash].css'),
      // Extract vendor and manifest files
      new webpack.optimize.CommonsChunkPlugin({
        names: ['vendor', 'manifest']
      }),
      // Setting DefinePlugin affects React library size!
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"'
      }),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      })
    ]
  });
}

This is my server.js file:

/* Global Requires */

const express    = require('express');
const logger     = require('morgan');
const bodyParser = require('body-parser');
const path       = require('path');
const app        = express();
const ReactDOM = require('react-dom')
var favicon = require('serve-favicon');

if(process.env.NODE_ENV === 'development') {
  console.log('in development.');
  require('dotenv').config();
} else {
  console.log('in production.');
}

/* App Config */
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'build')));
app.use(favicon(__dirname + '/public/favicon.ico'));

app.use(logger('dev'));

/* Server Initialization */
app.get('/', (req, res) => res.sendFile('index.html'));
var port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server initialized on // ${new Date()}`));

Body:
For future googlers:
You can also use copy-webpack-plugin and add this to webpack's production config:

plugins: [
  new CopyWebpackPlugin({
    patterns: [
     // relative path is from src
     { from: './static/favicon.ico' }, // <- your path to favicon
    ]
 })
]


来源: stackexchange

问:
get list of sub-set dict from existing list of dict in python
There is a list of dict like below, with each dict contains two keys.

```<code>original_list = [
    {
        'label': 'First Name',
        'value': 'Leo',
    },
    {
        'label': 'Last Name',
        'value': 'Lee',
    },
    {
        'label': 'Gender',
        'value': 'Male',
    },
    {
        'label': 'Age',
        'value': 35,
    },
    {
        'label': 'Telephone',
        'value': '13788995566',
    }
]
</code>```

I want to get a new list of dict with only one key('label') in the dict.

```<code># expecting output like below
new_list =  [
    {
        'label': 'First Name'
    },
    {
        'label': 'Last Name'
    },
    {
        'label': 'Gender'
    },
    {
        'label': 'Age'
    },
    {
        'label': 'Telephone'
    }
]
</code>```

I know one way to get around.

```<code>new_list = [{'label': d['label']} for d in original_list]
print(new_list)
</code>```

Is there any method more convenient?

If the original_list data is in one pandas DataFrame, how to get the same result?

答:
Just like yours! List comprehension, Even bit lengthier :) But definitely one more approach :)</p>

```<code>[{e: i} for d in original_list for e,i in d.items() if e =='label']
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There is a list of dict like below, with each dict contains two keys.

original_list = [
    {
        'label': 'First Name',
        'value': 'Leo',
    },
    {
        'label': 'Last Name',
        'value': 'Lee',
    },
    {
        'label': 'Gender',
        'value': 'Male',
    },
    {
        'label': 'Age',
        'value': 35,
    },
    {
        'label': 'Telephone',
        'value': '13788995566',
    }
]

I want to get a new list of dict with only one key('label') in the dict.

# expecting output like below
new_list =  [
    {
        'label': 'First Name'
    },
    {
        'label': 'Last Name'
    },
    {
        'label': 'Gender'
    },
    {
        'label': 'Age'
    },
    {
        'label': 'Telephone'
    }
]

I know one way to get around.

new_list = [{'label': d['label']} for d in original_list]
print(new_list)

Is there any method more convenient?

If the original_list data is in one pandas DataFrame, how to get the same result?

Body:
Just like yours! List comprehension, Even bit lengthier :) But definitely one more approach :)

[{e: i} for d in original_list for e,i in d.items() if e =='label']


问:
Restricting std::sort to random access iterators
I was just wondering, since you can only pass random access iterators to std::sort anyway, why not enforce that restriction by defining it only for random access iterators in the first place?

```<code>#include <iterator>
#include <type_traits>

template <typename ForwardIterator>
typename std::enable_if<
    std::is_same<
        typename std::iterator_traits<ForwardIterator>::iterator_category,
        std::random_access_iterator_tag>::value,
    void>
::type sort(ForwardIterator begin, ForwardIterator end)
{
    // ...
}
</code>```

I find a single line error message a lot easier to read than pages and pages of error messages resulting from type errors far down in the implementation.

You could do the same with other algorithms. The standard C++ core language has always been expressive enough for that task, right? So, any particular reason why this was not done?

答:
The core language has always been expressive enough to handle such checks, but when the first standard was being prepared (around 1996/1997), the tricks that you can play with SFINAE (what enable_if is based upon) were not yet known and the support for advanced template wizardry was limited in the compilers.

So, the reason why the standard did not mandate it was because the needed techniques were not invented yet.

The reason why compiler/library writers did not add it after the fact is probably just plain economics: not enough people asked for the feature, and when people did start asking for better diagnostics, hope was on the concepts proposal to take care of it. Unfortunately, this proved to be a bit too hard to get finalised in time.

ContentLicense: CC BY-SA 2.5

Body:
I was just wondering, since you can only pass random access iterators to std::sort anyway, why not enforce that restriction by defining it only for random access iterators in the first place?

#include <iterator>
#include <type_traits>

template <typename ForwardIterator>
typename std::enable_if<
    std::is_same<
        typename std::iterator_traits<ForwardIterator>::iterator_category,
        std::random_access_iterator_tag>::value,
    void>
::type sort(ForwardIterator begin, ForwardIterator end)
{
    // ...
}

I find a single line error message a lot easier to read than pages and pages of error messages resulting from type errors far down in the implementation.

You could do the same with other algorithms. The standard C++ core language has always been expressive enough for that task, right? So, any particular reason why this was not done?


问:
Grunt: jit-grunt: Plugin for the "protractor" task not found
I am new to yeoman/grunt/bower and I am working on setting up a angularjs project with:

```<code>yo angular
</code>```

I made some changes to gruntfile myself and recently I found protractor very useful and I wanted to add that to my project. I followed a lot of instructions online (like this one Integrating Protractor with Yeoman via Grunt 2 years ago) but I still cannot get protractor properly installed.

Here is my Gruntfile.js: (only showed relevant parts)

```<code>'use strict';
module.exports = function (grunt) {

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Automatically load required Grunt tasks
  require('jit-grunt')(grunt, {
    useminPrepare: 'grunt-usemin',
    ngtemplates: 'grunt-angular-templates',
    cdnify: 'grunt-google-cdn'
  });

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    ...
    ...

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      test: {
        devDependencies: true,
        src: '<%= karma.unit.configFile %>',
        ignorePath:  /\.\.\//,
        fileTypes:{
          js: {
            block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
              detect: {
                js: /'(.*\.js)'/gi
              },
              replace: {
                js: '\'{{filePath}}\','
              }
            }
          }
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    ...
    ...

    // Test settings

    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    },

    protractor: {
      options: {
        keepalive: true,
        configFile: 'protractor.conf.js'
      },
      run: {}
    }

  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'postcss:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'wiredep',
    'concurrent:test',
    'postcss',
    'connect:test',
    'karma',
    'protractor:run'
  ]);
};
</code>```

Here is my package.json:

```<code>{
  "name": "Website",
  "private": true,
  "devDependencies": {
    "autoprefixer-core": "^5.2.1",
    "compass": "^0.1.1",
    "grunt": "^0.4.5",
    "grunt-angular-templates": "^0.5.7",
    "grunt-concurrent": "^1.0.0",
    "grunt-contrib-clean": "^0.6.0",
    "grunt-contrib-compass": "^1.0.0",
    "grunt-contrib-concat": "^0.5.0",
    "grunt-contrib-connect": "^0.9.0",
    "grunt-contrib-copy": "^0.7.0",
    "grunt-contrib-cssmin": "^0.12.0",
    "grunt-contrib-htmlmin": "^0.4.0",
    "grunt-contrib-imagemin": "^1.0.0",
    "grunt-contrib-jshint": "^0.11.0",
    "grunt-contrib-uglify": "^0.7.0",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-filerev": "^2.1.2",
    "grunt-google-cdn": "^0.4.3",
    "grunt-jscs": "^1.8.0",
    "grunt-karma": "^0.12.2",
    "grunt-newer": "^1.1.0",
    "grunt-ng-annotate": "^0.9.2",
    "grunt-postcss": "^0.5.5",
    "grunt-protractor-runner": "^3.0.0",
    "grunt-svgmin": "^2.0.0",
    "grunt-usemin": "^3.0.0",
    "grunt-wiredep": "^2.0.0",
    "jasmine-core": "^2.4.1",
    "jit-grunt": "^0.9.1",
    "jshint-stylish": "^1.0.0",
    "karma": "^0.13.22",
    "karma-jasmine": "^0.3.8",
    "karma-phantomjs-launcher": "^1.0.0",
    "karma2": "^0.13.22",
    "phantomjs-prebuilt": "^2.1.7",
    "protractor": "^3.0.0",
    "time-grunt": "^1.0.0"
  },
  "engines": {
    "node": ">=0.10.0"
  },
  "scripts": {
    "test": "karma start test/karma.conf.js",
    "install": "node node_modules/protractor/bin/webdriver-manager update"
  },
  "dependencies": {}
}
</code>```

I used jit-grunt ( as default now ) so it will load those plugins for me.

I have surely installed protractor and grunt-protractor-runner following the post I mentioned above and other sources like official website of protractor and grunt-protractor-runner. In my local node_modules:

```<code>$ ls node_modules/ | grep protractor
grunt-protractor-runner
protractor
</code>```

But no matter what I do, I am still getting the error from grunt:

```<code>$ grunt protractor

jit-grunt: Plugin for the "protractor" task not found.
If you have installed the plugin already, please setting the static mapping.
See https://github.com/shootaroo/jit-grunt#static-mappings

Warning: Task "protractor" failed. Use --force to continue.
</code>```

And running grunt test:

```<code>$ grunt test

Running "clean:server" (clean) task
>> 1 path cleaned.

...
...

Running "karma:unit" (karma) task
01 05 2016 15:03:51.048:WARN [watcher]: Pattern
01 05 2016 15:03:51.094:INFO [karma]: Karma v0.13.22 server started at http://localhost:8080/
01 05 2016 15:03:51.112:INFO [launcher]: Starting browser PhantomJS
01 05 2016 15:03:52.259:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket /#68w8QMUehAm8AAf2AAAA with id 17032121
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 2 of 2 SUCCESS (0.003 secs / 0.026 secs)

jit-grunt: Plugin for the "protractor" task not found.
If you have installed the plugin already, please setting the static mapping.
See https://github.com/shootaroo/jit-grunt#static-mappings

Warning: Task "protractor:run" failed. Use --force to continue.

Aborted due to warnings.
</code>```

Is there something I missed? I have been stuck with this for days. Any help is much appreciated.

答:
The accepted answer follows an anti-pattern and defeats the purpose of the JIT (Just In Time) plugin loader for Grunt.

The goal of jit-grunt is to automatically load the required plugins and thus makes the use of grunt.loadNpmTasks obsolete.

The documentation for jit-grunt explains how the plugin loader is looking for the plugins:

Will automatically search for the plugin from the task name. Search in
  the following order:

node_modules/grunt-contrib-task-name

node_modules/grunt-task-name

node_modules/task-name

Since you have a task protractor, the plugin loader will try to find a corresponding plugin in this order:

grunt-contrib-protractor

doesn't exist in packages.json

grunt-protractor

doesn't exist in packages.json

protractor

found in packages.json!

unfortunately there is a mismatch

the required plugin for the task protractor is grunt-protractor-runner

In this case we can set the static mapping, as the error message points out. We do this in the format taskname: grunt_plugin_name:

```<code>// Automatically load required Grunt tasks
require('jit-grunt')(grunt, {
    useminPrepare: 'grunt-usemin',
    ngtemplates: 'grunt-angular-templates',
    cdnify: 'grunt-google-cdn',
    <strong>protractor: 'grunt-protractor-runner'</strong>
});</code>```

This is an old question, but I hope my answer can help other people who encounter this problem.

Body:
I am new to yeoman/grunt/bower and I am working on setting up a angularjs project with:

yo angular

I made some changes to gruntfile myself and recently I found protractor very useful and I wanted to add that to my project. I followed a lot of instructions online (like this one Integrating Protractor with Yeoman via Grunt 2 years ago) but I still cannot get protractor properly installed.

Here is my Gruntfile.js: (only showed relevant parts)

'use strict';
module.exports = function (grunt) {

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Automatically load required Grunt tasks
  require('jit-grunt')(grunt, {
    useminPrepare: 'grunt-usemin',
    ngtemplates: 'grunt-angular-templates',
    cdnify: 'grunt-google-cdn'
  });

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    ...
    ...

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      test: {
        devDependencies: true,
        src: '<%= karma.unit.configFile %>',
        ignorePath:  /\.\.\//,
        fileTypes:{
          js: {
            block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
              detect: {
                js: /'(.*\.js)'/gi
              },
              replace: {
                js: '\'{{filePath}}\','
              }
            }
          }
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    ...
    ...

    // Test settings

    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    },

    protractor: {
      options: {
        keepalive: true,
        configFile: 'protractor.conf.js'
      },
      run: {}
    }

  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'postcss:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'wiredep',
    'concurrent:test',
    'postcss',
    'connect:test',
    'karma',
    'protractor:run'
  ]);
};

Here is my package.json:

{
  "name": "Website",
  "private": true,
  "devDependencies": {
    "autoprefixer-core": "^5.2.1",
    "compass": "^0.1.1",
    "grunt": "^0.4.5",
    "grunt-angular-templates": "^0.5.7",
    "grunt-concurrent": "^1.0.0",
    "grunt-contrib-clean": "^0.6.0",
    "grunt-contrib-compass": "^1.0.0",
    "grunt-contrib-concat": "^0.5.0",
    "grunt-contrib-connect": "^0.9.0",
    "grunt-contrib-copy": "^0.7.0",
    "grunt-contrib-cssmin": "^0.12.0",
    "grunt-contrib-htmlmin": "^0.4.0",
    "grunt-contrib-imagemin": "^1.0.0",
    "grunt-contrib-jshint": "^0.11.0",
    "grunt-contrib-uglify": "^0.7.0",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-filerev": "^2.1.2",
    "grunt-google-cdn": "^0.4.3",
    "grunt-jscs": "^1.8.0",
    "grunt-karma": "^0.12.2",
    "grunt-newer": "^1.1.0",
    "grunt-ng-annotate": "^0.9.2",
    "grunt-postcss": "^0.5.5",
    "grunt-protractor-runner": "^3.0.0",
    "grunt-svgmin": "^2.0.0",
    "grunt-usemin": "^3.0.0",
    "grunt-wiredep": "^2.0.0",
    "jasmine-core": "^2.4.1",
    "jit-grunt": "^0.9.1",
    "jshint-stylish": "^1.0.0",
    "karma": "^0.13.22",
    "karma-jasmine": "^0.3.8",
    "karma-phantomjs-launcher": "^1.0.0",
    "karma2": "^0.13.22",
    "phantomjs-prebuilt": "^2.1.7",
    "protractor": "^3.0.0",
    "time-grunt": "^1.0.0"
  },
  "engines": {
    "node": ">=0.10.0"
  },
  "scripts": {
    "test": "karma start test/karma.conf.js",
    "install": "node node_modules/protractor/bin/webdriver-manager update"
  },
  "dependencies": {}
}

I used jit-grunt ( as default now ) so it will load those plugins for me.

I have surely installed protractor and grunt-protractor-runner following the post I mentioned above and other sources like official website of protractor and grunt-protractor-runner. In my local node_modules:

$ ls node_modules/ | grep protractor
grunt-protractor-runner
protractor

But no matter what I do, I am still getting the error from grunt:

$ grunt protractor

jit-grunt: Plugin for the "protractor" task not found.
If you have installed the plugin already, please setting the static mapping.
See https://github.com/shootaroo/jit-grunt#static-mappings

Warning: Task "protractor" failed. Use --force to continue.

And running grunt test:

$ grunt test

Running "clean:server" (clean) task
>> 1 path cleaned.

...
...

Running "karma:unit" (karma) task
01 05 2016 15:03:51.048:WARN [watcher]: Pattern
01 05 2016 15:03:51.094:INFO [karma]: Karma v0.13.22 server started at http://localhost:8080/
01 05 2016 15:03:51.112:INFO [launcher]: Starting browser PhantomJS
01 05 2016 15:03:52.259:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket /#68w8QMUehAm8AAf2AAAA with id 17032121
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 2 of 2 SUCCESS (0.003 secs / 0.026 secs)

jit-grunt: Plugin for the "protractor" task not found.
If you have installed the plugin already, please setting the static mapping.
See https://github.com/shootaroo/jit-grunt#static-mappings

Warning: Task "protractor:run" failed. Use --force to continue.

Aborted due to warnings.

Is there something I missed? I have been stuck with this for days. Any help is much appreciated.

Body:
The accepted answer follows an anti-pattern and defeats the purpose of the JIT (Just In Time) plugin loader for Grunt.

The goal of jit-grunt is to automatically load the required plugins and thus makes the use of grunt.loadNpmTasks obsolete.

The documentation for jit-grunt explains how the plugin loader is looking for the plugins:

Will automatically search for the plugin from the task name. Search in
  the following order:

node_modules/grunt-contrib-task-name

node_modules/grunt-task-name

node_modules/task-name

Since you have a task protractor, the plugin loader will try to find a corresponding plugin in this order:

grunt-contrib-protractor

doesn't exist in packages.json

grunt-protractor

doesn't exist in packages.json

protractor

found in packages.json!

unfortunately there is a mismatch

the required plugin for the task protractor is grunt-protractor-runner

In this case we can set the static mapping, as the error message points out. We do this in the format taskname: grunt_plugin_name:

// Automatically load required Grunt tasks
require('jit-grunt')(grunt, {
    useminPrepare: 'grunt-usemin',
    ngtemplates: 'grunt-angular-templates',
    cdnify: 'grunt-google-cdn',
    protractor: 'grunt-protractor-runner'
});

This is an old question, but I hope my answer can help other people who encounter this problem.


问:
How to split an SQL Table into half and send the other half of the rows to new columns with SQL Query?
```<code>Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%
</code>```

Output :

```<code>Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%
</code>```

For example there is a table Country which has percentages, I need to divide the table in Half and show the remaining half (i.e. the remaining rows) in the new columns. I've also provided the table structure in text.

答:
Try this</p>

```<code>    declare @t table
(
Country VARCHAR(20),
percentage INT
)
declare @cnt int

INSERT INTO @T
VALUES('India',12),('USA',20),('Australia',15),('Quatar',12)

select @cnt = count(1)+1 from @t

;with cte
as
(
    select
    SeqNo = row_number() over(order by Country),
    Country,
    percentage
    from  @t
)
select
*
from cte c1
left join cte c2
on c1.seqno = (c2.SeqNo-@cnt/2)
and c2.SeqNo >= (@cnt/2)
where c1.SeqNo <= (@cnt/2)
</code>```

Body:
Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%

Output :

Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%

For example there is a table Country which has percentages, I need to divide the table in Half and show the remaining half (i.e. the remaining rows) in the new columns. I've also provided the table structure in text.

Body:
Try this

    declare @t table
(
Country VARCHAR(20),
percentage INT
)
declare @cnt int

INSERT INTO @T
VALUES('India',12),('USA',20),('Australia',15),('Quatar',12)

select @cnt = count(1)+1 from @t

;with cte
as
(
    select
    SeqNo = row_number() over(order by Country),
    Country,
    percentage
    from  @t
)
select
*
from cte c1
left join cte c2
on c1.seqno = (c2.SeqNo-@cnt/2)
and c2.SeqNo >= (@cnt/2)
where c1.SeqNo <= (@cnt/2)


问:
MPMoviePlayerController and Auth-Based HLS Backend Server
I am currently serving videos in my iOS application with MPMoviePlayerController. The files are streamed from our backend server that requires authentication. It is key-based authenticated set in the Authorization HTTP Header.

It used to work perfectly with single video files. Now we’re trying to implement HLS adaptive streaming and we have faced a wall. I am currently using a custom NSURLProtocol subclass to catch requests made to our backend server and inject the proper Authorization header. For HLS it simply doesn’t work.

When we looked at the server logs, we clearly saw that the first request to the m3u8 file worked fine. Then all subsequent calls made (other m3u8 files and ts also) are 403 forbidden. It seems that MPMoviePlayerController doesn’t use NSURLProtocol for the other files. (side note: It does work on the simulator thought, but not on a physical device which let me think that both are not implemented in the same way).

MPMoviePlayerController instantiation

```<code>self.videoController = [[MPMoviePlayerController alloc] initWithContentURL:video.videoURL];
</code>```

The URL Protocol interception

```<code>+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
    NSMutableURLRequest *newRequest = request.mutableCopy;
    [newRequest setValue:@"HIDDEN" forHTTPHeaderField:@"Authorization"];
    return newRequest;
}
</code>```

Any Ideas, suggestions, work arounds?

答:
@Marc-Alexandre Bérubé I can think of below workaround:
Run a proxy server in your app to proxy all the video URL's. Download all the video content by injecting the necessary auth headers to the request and relay back the content via the proxy server to the media player to render it. This approach may not work for large videos as the video rendering would only start after entire video is downloaded.</p>

Body:
I am currently serving videos in my iOS application with MPMoviePlayerController. The files are streamed from our backend server that requires authentication. It is key-based authenticated set in the Authorization HTTP Header.

It used to work perfectly with single video files. Now we’re trying to implement HLS adaptive streaming and we have faced a wall. I am currently using a custom NSURLProtocol subclass to catch requests made to our backend server and inject the proper Authorization header. For HLS it simply doesn’t work.

When we looked at the server logs, we clearly saw that the first request to the m3u8 file worked fine. Then all subsequent calls made (other m3u8 files and ts also) are 403 forbidden. It seems that MPMoviePlayerController doesn’t use NSURLProtocol for the other files. (side note: It does work on the simulator thought, but not on a physical device which let me think that both are not implemented in the same way).

MPMoviePlayerController instantiation

self.videoController = [[MPMoviePlayerController alloc] initWithContentURL:video.videoURL];

The URL Protocol interception

+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
    NSMutableURLRequest *newRequest = request.mutableCopy;
    [newRequest setValue:@"HIDDEN" forHTTPHeaderField:@"Authorization"];
    return newRequest;
}

Any Ideas, suggestions, work arounds?


问:
Firebase Collaboration: Share a Single Project in Google IAM?
So I shared a firebase project in Google IAM.  Turns out, the guy emails me with a screenshot and he has write access to all my projects (see below)?  Anyone else notice this, or did I add a member incorrectly?

答:
For understanding the steps to add, please go through the below step:

Log in to https://console.firebase.google.com using your Google account. A screen will be displayed with option Add Project.

Click on the Add Project option. You will be asked to enter App name and country. Then proceed by clicking on Create Project button.

Click on Users and Permission option from Settings/cog wheel icon which is adjacent to Project Overview, present on the left menu list.

You will be redirected to new a webpage(https://console.cloud.google.com/iam-admin/iam) and proceed with accepting the terms.

Click on IAM option from the left menu list. Add member by selecting Add on IAM screen.

Provide email id and role, then click on Add for adding the member.


问:
jQuery time picker
I'm looking to fill a text input with a time that the user can choose in 15 minute intervals. I know there are a few plugins out there. I was wondering if there was any “industry standard” plugin, or strong objective reasons to prefer a particular one in common scenarios.</p>

答:
My advice would be not to do this. I find it bad enough being forced to use a calendar control just to enter a date, especially when not given the option to type a date which I can do way quicker than navigating yet another wacky control.

Time pickers just take this kind of UI fetish to a new extreme. Why not allow your users to either type the time or just use a couple of drop down boxes for hours and mins. Even drop down lists allow a user to just type the time. The time picker in Shog9's answer is all very nice to look at but is incredibly fiddly to use. If I was an end user having to use a data entry app and it had a control like that on the page then it's only going to slow me down and make me want to come and cut off the developers hands. :)

Think about usability first before how slick the app looks.

Just my humble opinion.

OwnerDisplayName: Bernardo

Title: jQuery time picker

OwnerDisplayName: Kev


问:
using python to send json and files to flask
I have this issue where I am trying to send/receive to a flask API some file and JSON in a single function.

On my client ( sender ) I have :

```<code>#my json to be sent
datas = {'var1' : 'var1','var2'  : 'var2',}
#my file to be sent
local_file_to_send = 'user_picture.jpg'
url = "http://10.100.2.6:80/customerupdate"
headers = {'Content-type': 'multipart/form-data'}
files = {'document': open(local_file_to_send, 'rb')}
r = requests.post(url, files=files, data=datas, headers=headers)
</code>```

On my Flask server I have :

```<code>class OPERATIONS(Resource):
        @app.route('/',methods=['GET'])
        def hello_world():
            return 'Hello World!'

        @app.route('/customerupdate',methods=['GET','POST'])
        def customerupdate():
            event_data_2 = json.loads(request.get_data().decode('utf-8'))
            print event_data_2
</code>```

I have this error message telling me that the data is actually not a json format nor a utf8 format. If I print the content of the "get_data" without trying to decode it shows some binary characters..

What would be the syntax on my client to read the json and write the file locally ?

答:
Thanks to Craig answer, I found the solution. I will post both code ( client and server ) to help in case of future use. The CLient server is uploading file and Json in the "form" feature of flask. Then some ast and some dict to make the Payload clearer ( I know this is ugly way, but this is the best scholar approach )

On Client side :

```<code>datas = {'CurrentMail': "AA", 'STRUserUUID1': "BB", 'FirstName': "ZZ",     'LastName': "ZZ",  'EE': "RR", 'JobRole': "TT"  }

#sending user infos to app server using python "requests"
url = "http://10.100.2.6:80/customerupdate"
def send_request():
    payload = datas
    local_file_to_send = 'user_picture.jpg'
    files = {
     'json': (None, json.dumps(payload), 'application/json'),
     'file': (os.path.basename(local_file_to_send), open(local_file_to_send, 'rb'), 'application/octet-stream')
    }
    r = requests.post(url, files=files)

send_request()
</code>```

On Flask Server side :

```<code>import sys, os, logging, time, datetime, json, uuid, requests, ast
from flask import Flask, request , render_template
from werkzeug import secure_filename
from werkzeug.datastructures import ImmutableMultiDict
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)
app.debug = True

class OPERATIONS(Resource):
        @app.route('/',methods=['GET'])
        def hello_world():
            return 'Hello World!'

        @app.route('/customerupdate',methods=['GET','POST'])
        def customerupdate():
            print "************DEBUG 1 ***********"
            RequestValues = request.values
            print RequestValues
            print "************DEBUG 2 ***********"
            RequestForm = request.form
            print RequestForm
            print "************DEBUG 2-1 ***********"
            so = RequestForm
            json_of_metadatas = so.to_dict(flat=False)
            print json_of_metadatas
            print "************DEBUG 2-2 ***********"
            MetdatasFromJSON = json_of_metadatas['json']
            print MetdatasFromJSON
            print "************DEBUG 2-3 ***********"
            MetdatasFromJSON0 = MetdatasFromJSON[0]
            print MetdatasFromJSON0
            print "************DEBUG 3-5 ***********"
            strMetdatasFromJSON0 = str(MetdatasFromJSON0)
            MetdatasDICT = ast.literal_eval(strMetdatasFromJSON0)
            print MetdatasDICT
            print "************DEBUG 3-5 ***********"
            for key in MetdatasDICT :
                print "key: %s , value: %s" % (key, MetdatasDICT[key])
            print "************DEBUG 4 ***********"
            f = request.files['file']
            f.save(secure_filename(f.filename))
            print "FILE SAVED LOCALY"
            return 'JSON of customer posted'
</code>```

Body:
I have this issue where I am trying to send/receive to a flask API some file and JSON in a single function.

On my client ( sender ) I have :

#my json to be sent
datas = {'var1' : 'var1','var2'  : 'var2',}
#my file to be sent
local_file_to_send = 'user_picture.jpg'
url = "http://10.100.2.6:80/customerupdate"
headers = {'Content-type': 'multipart/form-data'}
files = {'document': open(local_file_to_send, 'rb')}
r = requests.post(url, files=files, data=datas, headers=headers)

On my Flask server I have :

class OPERATIONS(Resource):
        @app.route('/',methods=['GET'])
        def hello_world():
            return 'Hello World!'

        @app.route('/customerupdate',methods=['GET','POST'])
        def customerupdate():
            event_data_2 = json.loads(request.get_data().decode('utf-8'))
            print event_data_2

I have this error message telling me that the data is actually not a json format nor a utf8 format. If I print the content of the "get_data" without trying to decode it shows some binary characters..

What would be the syntax on my client to read the json and write the file locally ?

Body:
Thanks to Craig answer, I found the solution. I will post both code ( client and server ) to help in case of future use. The CLient server is uploading file and Json in the "form" feature of flask. Then some ast and some dict to make the Payload clearer ( I know this is ugly way, but this is the best scholar approach )

On Client side :

datas = {'CurrentMail': "AA", 'STRUserUUID1': "BB", 'FirstName': "ZZ",     'LastName': "ZZ",  'EE': "RR", 'JobRole': "TT"  }

#sending user infos to app server using python "requests"
url = "http://10.100.2.6:80/customerupdate"
def send_request():
    payload = datas
    local_file_to_send = 'user_picture.jpg'
    files = {
     'json': (None, json.dumps(payload), 'application/json'),
     'file': (os.path.basename(local_file_to_send), open(local_file_to_send, 'rb'), 'application/octet-stream')
    }
    r = requests.post(url, files=files)

send_request()

On Flask Server side :

import sys, os, logging, time, datetime, json, uuid, requests, ast
from flask import Flask, request , render_template
from werkzeug import secure_filename
from werkzeug.datastructures import ImmutableMultiDict
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)
app.debug = True

class OPERATIONS(Resource):
        @app.route('/',methods=['GET'])
        def hello_world():
            return 'Hello World!'

        @app.route('/customerupdate',methods=['GET','POST'])
        def customerupdate():
            print "************DEBUG 1 ***********"
            RequestValues = request.values
            print RequestValues
            print "************DEBUG 2 ***********"
            RequestForm = request.form
            print RequestForm
            print "************DEBUG 2-1 ***********"
            so = RequestForm
            json_of_metadatas = so.to_dict(flat=False)
            print json_of_metadatas
            print "************DEBUG 2-2 ***********"
            MetdatasFromJSON = json_of_metadatas['json']
            print MetdatasFromJSON
            print "************DEBUG 2-3 ***********"
            MetdatasFromJSON0 = MetdatasFromJSON[0]
            print MetdatasFromJSON0
            print "************DEBUG 3-5 ***********"
            strMetdatasFromJSON0 = str(MetdatasFromJSON0)
            MetdatasDICT = ast.literal_eval(strMetdatasFromJSON0)
            print MetdatasDICT
            print "************DEBUG 3-5 ***********"
            for key in MetdatasDICT :
                print "key: %s , value: %s" % (key, MetdatasDICT[key])
            print "************DEBUG 4 ***********"
            f = request.files['file']
            f.save(secure_filename(f.filename))
            print "FILE SAVED LOCALY"
            return 'JSON of customer posted'


问:
WPF -Child datacontext set from the parent ViewModel doesnot contains the modified values in the parent ViewModel
In my WPF application I have a MainWindow.xaml which has many User Controls embedded into it. I have separate viewmodel for both the main window as well as the user controls. In the Main Window ViewModel I create an instance of the child ViewModel and set it as the child's datacontext.

Parent VM
ChildUserControlVM ChildVM = new ChildUserControlVM (ParentModel.ChildModel);

MainWindow.xaml

But this approach is not working as I am not getting the values set in the parent viewmodel in the child one and vice versa.

On the contrary, if I set the Child model object as the datacontext from the parent that is working both way.

I need some solution so that I can use MVVM in the user controls also ensuring data gets passed from parent to child and vice versa.
In the usercontrol I am going to have some buttons whose action I want to handle in the child Viewmodel through ICommand.
Adding the code snippets for reference
MainWindow.xaml

```<code><Grid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0">
    <local:ProfileIdentitySettings Visibility="{Binding ProfileIdentitySettingsVisibility,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" DataContext="{Binding ChildProfileIdentityVM}"/>
</Grid>
</code>```

MainWindowVM.cs

```<code> ProfileIdentitySettingsVM ChildProfileIdentityVM = new ProfileIdentitySettingsVM(DeviceEditorModel.ProfileIdentitySettings);
</code>```

ProfileIdentitySettings.xaml

```<code>DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MainWindowVM}">
</code>```

答:
The parent view model should contain the child view models as properties, like

```<code>public class ParentViewModel
{
    public ChildViewModel1 ChildViewModel1 { get; set; }
    public ChildViewModel2 ChildViewModel2 { get; set; }
}
</code>```

Your UserControls should not have any view models of their own. Instead they should expose dependency properties like

```<code>public partial class MyView1 : UserControl
{
    public string MyProperty { get; set; } // this must be a dependency property
}
</code>```

which can be bound when the UserControl is used, e.g. in your MainWindow's XAML, like

```<code><MyView1 MyProperty="{Binding ChildViewModel1.SomeProperty}" />
</code>```

If there are many of these bindable properties, you may set the UserControl's DataContext once to the appropriate child view model:

```<code><MyView1 DataContext="{Binding ChildViewModel1}"
         MyProperty="{Binding SomeProperty}" />
</code>```

Body:
In my WPF application I have a MainWindow.xaml which has many User Controls embedded into it. I have separate viewmodel for both the main window as well as the user controls. In the Main Window ViewModel I create an instance of the child ViewModel and set it as the child's datacontext.

Parent VM
ChildUserControlVM ChildVM = new ChildUserControlVM (ParentModel.ChildModel);

MainWindow.xaml

But this approach is not working as I am not getting the values set in the parent viewmodel in the child one and vice versa.

On the contrary, if I set the Child model object as the datacontext from the parent that is working both way.

I need some solution so that I can use MVVM in the user controls also ensuring data gets passed from parent to child and vice versa.
In the usercontrol I am going to have some buttons whose action I want to handle in the child Viewmodel through ICommand.
Adding the code snippets for reference
MainWindow.xaml

<Grid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0">
    <local:ProfileIdentitySettings Visibility="{Binding ProfileIdentitySettingsVisibility,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" DataContext="{Binding ChildProfileIdentityVM}"/>
</Grid>

MainWindowVM.cs

 ProfileIdentitySettingsVM ChildProfileIdentityVM = new ProfileIdentitySettingsVM(DeviceEditorModel.ProfileIdentitySettings);

ProfileIdentitySettings.xaml

DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MainWindowVM}">

Body:
The parent view model should contain the child view models as properties, like

public class ParentViewModel
{
    public ChildViewModel1 ChildViewModel1 { get; set; }
    public ChildViewModel2 ChildViewModel2 { get; set; }
}

Your UserControls should not have any view models of their own. Instead they should expose dependency properties like

public partial class MyView1 : UserControl
{
    public string MyProperty { get; set; } // this must be a dependency property
}

which can be bound when the UserControl is used, e.g. in your MainWindow's XAML, like

<MyView1 MyProperty="{Binding ChildViewModel1.SomeProperty}" />

If there are many of these bindable properties, you may set the UserControl's DataContext once to the appropriate child view model:

<MyView1 DataContext="{Binding ChildViewModel1}"
         MyProperty="{Binding SomeProperty}" />


问:
Does LiClipse (for Mac) include its own copy of the JRE?
Does the LiClipse development environment (IDE) for Mac OS X include its own copy of the JRE (Java Runtime Environment), or does it use the system's JRE to run?

LiClipse is built on the Eclipse IDE, which is written in the Java language, and so needs a JRE to run. The answer for Eclipse and for LiClipse may be the same. Mac OS permits applications to be packaged as "bundles", a camouflaged form of a directory tree, so it is possible for an app to include support software such as a JRE.  "Bundles" are a Mac OS specific structure, so the answer for Windows and Linux versions of Eclipse or LiClipse might differ.

I am using LiClipse 4.4.0 on Mac OS X El Capitan 10.11.6. I expect the answer may be the same for several versions of LiClipse, Eclipse, and Mac OS X, but not for all.

答:
Yes, LiClipse does include a JRE (depending on each platform it may be on a different place).

The JRE is actually put there on a post-build step (before creating native installers for each platform).

This means that starting LiClipse doesn't require the user to have a JRE installed on the machine (although it should still be possible to specify a different Java VM if needed as explained in https://wiki.eclipse.org/Eclipse.ini).


问:
Python 3.6 startup error
I am very new to python, I have installed Python 3.6 on my Windows 10 machine ( and I believe it has version 2.7 installed ). The installation was ok but when I try to start up it gives me error as shown below

```<code>Fatal Python error: Py_Initialize: unable to load the file system codec
  File "C:\csvn\Python25\\lib\encodings\__init__.py", line 123
    raise CodecRegistryError,\
                            ^
SyntaxError: invalid syntax

Current thread 0x00002c78 (most recent call first):
</code>```

Please someone would help me to identify this error and how to fix it.
Thank you so much in advance for any help.

答:
The error can be resolved by adding an environment variable "PYTHONPATH" which point to the installation location of Python.

Refer to the following link,

Py_Initialize fails - unable to load the file system codec

Title: Python 3.6 startup error

Body:
I am very new to python, I have installed Python 3.6 on my Windows 10 machine ( and I believe it has version 2.7 installed ). The installation was ok but when I try to start up it gives me error as shown below

Fatal Python error: Py_Initialize: unable to load the file system codec
  File "C:\csvn\Python25\\lib\encodings\__init__.py", line 123
    raise CodecRegistryError,\
                            ^
SyntaxError: invalid syntax

Current thread 0x00002c78 (most recent call first):

Please someone would help me to identify this error and how to fix it.
Thank you so much in advance for any help.


问:
Program will print largest number and smallest number
I have some trouble when I try to code a program.

```<code>double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
    System.out.println("Give the " + (i + 1) + " number");
    array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
    if (array[i] > max) {
        max = array[i];
    }
    for (i = 0; i < 10; i++) {
        if (array[i] < min) {
            min = array[i];
        }
    }
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
</code>```

When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0

Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.

答:
you Initializing max and min before entering number into the array , when tring to find the max and the min , first enter the numbers to the array then compare them with the array[0].
second thing is that you dont need to for loops to check whether you need to change max or min , you can do it in one for loop .
try this : </p>

```<code>    double array[] = new double[10];
    int i;
    Scanner input = new Scanner(System.in);
    for (i = 0; i < 10; i++) {
        System.out.println("Give the " + (i + 1) + " number");
        array[i] = input.nextDouble();
    }
    double max = array[0], min = array[0];
    for (i = 0; i < 10; i++) {
        if (array[i] > max) {
            max = array[i];

        }

        if (array[i] < min) {
            min = array[i];
        }
    }
    System.out.println("The Max is :" + max);
    System.out.println("The Min is :" + min);
</code>```

Body:
I have some trouble when I try to code a program.

double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
    System.out.println("Give the " + (i + 1) + " number");
    array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
    if (array[i] > max) {
        max = array[i];
    }
    for (i = 0; i < 10; i++) {
        if (array[i] < min) {
            min = array[i];
        }
    }
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);

When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0

Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.

Body:
you Initializing max and min before entering number into the array , when tring to find the max and the min , first enter the numbers to the array then compare them with the array[0].
second thing is that you dont need to for loops to check whether you need to change max or min , you can do it in one for loop .
try this :

    double array[] = new double[10];
    int i;
    Scanner input = new Scanner(System.in);
    for (i = 0; i < 10; i++) {
        System.out.println("Give the " + (i + 1) + " number");
        array[i] = input.nextDouble();
    }
    double max = array[0], min = array[0];
    for (i = 0; i < 10; i++) {
        if (array[i] > max) {
            max = array[i];

        }

        if (array[i] < min) {
            min = array[i];
        }
    }
    System.out.println("The Max is :" + max);
    System.out.println("The Min is :" + min);


问:
how to create HTML5 playlist loop feature
I'm trying to create a playlist like youtube but I have a problem with autoplay all videos one by one, i created an on ended event to play the next video when the current playback ends
This is the code

$('video').on('ended', function() {
  // Remove .active class from the active li, select next li sibling.
  var next = $('ul.nav-tabs li.active').removeClass('active').next('li');
  var tabNext = $('.tab-content .active').removeClass('active').next('div');
  var tabNextIn = $('.tab-content .in').removeClass('in').next('div');

  // Did we reach the last element? if so: select first sibling
  if (!next.length) next = next.prevObject.siblings(':first');
  if (!tabNext.length) next = next.prevObject.siblings(':first');
  if (!tabNextIn.length) next = next.prevObject.siblings(':first');

  // Add .active class to the li next in line.
  next.addClass('active');
  tabNext.addClass('active');
  tabNextIn.addClass('in');
});

if ($('.tab-pane').hasClass('active')) {
  $('.active video').attr('autoplay', '');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

I don't understand why the next video not play

I just need to add autoplay attribute to the next video!

https://codepen.io/kemozzz/full/gXEzrp/

答:
It is because your IF statement has nothing to trigger it.

```<code>$('video').on('ended',function(){
    // Remove .active class from the active li, select next li sibling.
    var next = $('ul.nav-tabs li.active').removeClass('active').next('li');
    var tabNext = $('.tab-content .active').removeClass('active').next('div');
    var tabNextIn = $('.tab-content .in').removeClass('in').next('div');

    // Did we reach the last element? if so: select first sibling
    if (!next.length) next = next.prevObject.siblings(':first');
    if (!tabNext.length) next = next.prevObject.siblings(':first');
    if (!tabNextIn.length) next = next.prevObject.siblings(':first');

    // Add .active class to the li next in line.
    next.addClass('active');
    tabNext.addClass('active');
    tabNextIn.addClass('in');

    if ($('.tab-pane').hasClass('active')) {
        $('.active video').attr('autoplay','');
    }
  });
});
</code>```

Codepen: https://codepen.io/anon/pen/EbzBBW

Body:
I'm trying to create a playlist like youtube but I have a problem with autoplay all videos one by one, i created an on ended event to play the next video when the current playback ends
This is the code

$('video').on('ended', function() {
  // Remove .active class from the active li, select next li sibling.
  var next = $('ul.nav-tabs li.active').removeClass('active').next('li');
  var tabNext = $('.tab-content .active').removeClass('active').next('div');
  var tabNextIn = $('.tab-content .in').removeClass('in').next('div');

  // Did we reach the last element? if so: select first sibling
  if (!next.length) next = next.prevObject.siblings(':first');
  if (!tabNext.length) next = next.prevObject.siblings(':first');
  if (!tabNextIn.length) next = next.prevObject.siblings(':first');

  // Add .active class to the li next in line.
  next.addClass('active');
  tabNext.addClass('active');
  tabNextIn.addClass('in');
});

if ($('.tab-pane').hasClass('active')) {
  $('.active video').attr('autoplay', '');
}

I don't understand why the next video not play

I just need to add autoplay attribute to the next video!

https://codepen.io/kemozzz/full/gXEzrp/

Body:
It is because your IF statement has nothing to trigger it.

$('video').on('ended',function(){
    // Remove .active class from the active li, select next li sibling.
    var next = $('ul.nav-tabs li.active').removeClass('active').next('li');
    var tabNext = $('.tab-content .active').removeClass('active').next('div');
    var tabNextIn = $('.tab-content .in').removeClass('in').next('div');

    // Did we reach the last element? if so: select first sibling
    if (!next.length) next = next.prevObject.siblings(':first');
    if (!tabNext.length) next = next.prevObject.siblings(':first');
    if (!tabNextIn.length) next = next.prevObject.siblings(':first');

    // Add .active class to the li next in line.
    next.addClass('active');
    tabNext.addClass('active');
    tabNextIn.addClass('in');

    if ($('.tab-pane').hasClass('active')) {
        $('.active video').attr('autoplay','');
    }
  });
});

Codepen: https://codepen.io/anon/pen/EbzBBW


问:
Why doesn't this function with boolean variable work?
I wrote simple code to show/hide some layers after clicking buttons (5 in total) and to change color of the clicked buttons. That works fine. But then I wanted to show a certain element - an arrow - only after clicking first button using a boolean variable and it's not working, the if statement never returns first (hooray) part. What am I missing?

var click01 = false;

function allowright1() {
  if (click01 == true) {
    console.log('hoooray');
    $('#right_arrow').removeClass('hidden').addClass('visible');
  } else {
    console.log('not working');
  }
};

$('#tile1_p1').click(function() {
  if ($('#1layers1').css('display') == 'none') {
    $('#1layers2, #1layers3, #1layers4, #1layers5').removeClass('block').addClass('none');
      $('#tile2_p1, #tile3_p1, #tile4_p1, #tile5_p1').removeClass('orange');
      $('#1layers1').removeClass('none').addClass('block'); $('#tile1_p1').removeClass('white').addClass('orange');
      var click01 = true;
      console.log('click01 ' + click01);
      allowright1();
    }
    else if ($('#1layers1').css('display') == 'block') {
      $('#1layers1').removeClass('block').addClass('none');
      $('#tile1_p1').removeClass('orange').addClass('white');
    }
  });
```

答:
You are not resassigning the top level variable click01.

By specifying var click01 = true; you are declaring a variable inside of your click handler that is different to the top level variable. If you remove the var it should work for you, e.g.

```<code>$(...).click(function() {
  ...
  click01 = true; // by removing var we reassign the top level variable
  ...
});
</code>```

Body:
You are not resassigning the top level variable click01.

By specifying var click01 = true; you are declaring a variable inside of your click handler that is different to the top level variable. If you remove the var it should work for you, e.g.

$(...).click(function() {
  ...
  click01 = true; // by removing var we reassign the top level variable
  ...
});


问:
Callback after_[anything]
I've faced a situation, when I need to fire a callback for any event of the model. It's about cache reseting. I have Follow entity, where follower_id and following_id. If something happens with this entity (create/update/destroy and anything else that is possible) I need to reset some specific cache for both follower and following.

Right now I've finished with:

```<code>class Follow < ActiveRecord::Base
  after_save :reset_cache
  after_destroy :reset_cache

  def reset_cache
    ...
  end
end
</code>```

Questions:

Does this cover all possible cases which can happen with model object?

Is there any one line approach to do this?

Thanks

答:
Here is a one line approach

```<code>class Follow < ActiveRecord::Base
  after_commit :reset_cache, on: [:update, :destroy]

  def reset_cache
  end
end
</code>```

See: http://guides.rubyonrails.org/active_record_callbacks.html

Title: Callback after_[anything]

Body:
I've faced a situation, when I need to fire a callback for any event of the model. It's about cache reseting. I have Follow entity, where follower_id and following_id. If something happens with this entity (create/update/destroy and anything else that is possible) I need to reset some specific cache for both follower and following.

Right now I've finished with:

class Follow < ActiveRecord::Base
  after_save :reset_cache
  after_destroy :reset_cache

  def reset_cache
    ...
  end
end

Questions:

Does this cover all possible cases which can happen with model object?

Is there any one line approach to do this?

Thanks

Body:
Here is a one line approach

class Follow < ActiveRecord::Base
  after_commit :reset_cache, on: [:update, :destroy]

  def reset_cache
  end
end

See: http://guides.rubyonrails.org/active_record_callbacks.html


问:
Is there a faster method of deleting shapes in Excel
I've successfully added shapes into cells (msoShapeOval) in a pivot table.

I need to clear and recreate these shapes if the pivot / slicer selection changes.

My current method works, but it is slow.

Is there any better method to clear shapes in bulk?
Note: I do know the exact cell range where all these shapes exist.

I've also appied :

```<code>Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
</code>```

Current code:

```<code>  Dim Shp as Shape
  For Each Shp In rng.Parent.Shapes
     If InStrB(Shp.Name, "$") > 0 Then Shp.Delete
  Next
</code>```

答:
To delete all shapes except slicers:</p>

```<code>Sub RemoveAllExceptSlicers()

    Dim sh As Shape

    For Each sh In ActiveSheet.Shapes
        If Not sh.Type = MsoShapeType.msoSlicer Then
            sh.Delete
        End If
    Next

End Sub
</code>```

Body:
I've successfully added shapes into cells (msoShapeOval) in a pivot table.

I need to clear and recreate these shapes if the pivot / slicer selection changes.

My current method works, but it is slow.

Is there any better method to clear shapes in bulk?
Note: I do know the exact cell range where all these shapes exist.

I've also appied :

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

Current code:

  Dim Shp as Shape
  For Each Shp In rng.Parent.Shapes
     If InStrB(Shp.Name, "$") > 0 Then Shp.Delete
  Next

Body:
To delete all shapes except slicers:

Sub RemoveAllExceptSlicers()

    Dim sh As Shape

    For Each sh In ActiveSheet.Shapes
        If Not sh.Type = MsoShapeType.msoSlicer Then
            sh.Delete
        End If
    Next

End Sub


问:
ZF, ZFDoctrine and PHPUnit setup
Does anyone here use Zend Framework, ZFDoctrine and PHPUnit together?

How to rebuild the database on each test run?
How to separate local/production/testing environments?

Would you share your unit testing setup?

I have been trying something like that:

```<code>// /tests/bootstrap.php
// ... setup paths and constants here
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

$application->bootstrap('doctrine');
$provider = new ZFDoctrine_Tool_DoctrineProvider;
$provider->generateModelsFromYaml();
//$provider->buildProject(true);
</code>```

But this ends in:

```<code>Notice: Constant APPLICATION_PATH already defined in /home/user/www/library/ZendFramework/1.10.7/library/Zend/Tool/Project/Context/Zf/BootstrapFile.php on line 106

Fatal error: Call to a member function getResponse() on a non-object in /home/user/www/library/zf-doctrine/library/ZFDoctrine/Tool/DoctrineProvider.php on line 271
</code>```

Models are not generated.

I get similar errors running:

```<code>$provider->createDatabase();
</code>```

But in this case database is created.

The other provider commands do not work.

The solution:

```<code>$provider = new ZFDoctrine_Tool_DoctrineProvider;
$registry = new Zend_Tool_Framework_Registry;
$provider->setRegistry($registry);
@$provider->buildProject(true);
</code>```

If anybody knows a better approach, please correct me.

答:
I haven't used ZFDoctrine, but just plain Doctrine 1.2. I don't know if my solution is better but I figured I post if any1 is interested, here's the bootstrap.php in my tests folder:

```<code><?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../application'));

// Define application environment
/**
 * In the application.ini:
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
doctrine.dsn = "mysql://my_user:passwd@localhost/my_phpunit_test_db"
 */
define('APPLICATION_ENV', 'testing');

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path()
)));

/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/../configs/application.ini'
);

$application->getBootstrap()->bootstrap();

// Can run out if too small
ini_set('memory_limit', '512M');

// Get the doctrine settings
$config = $application->getOption('doctrine');
$cli = new Doctrine_Cli($config);
$cli->run(array("doctrine", "build-all-reload","force"));
</code>```

The key here is actually the last line that rebuilds all databases creating a clean environment for each testing.

Title: ZF, ZFDoctrine and PHPUnit setup

Body:
Does anyone here use Zend Framework, ZFDoctrine and PHPUnit together?

How to rebuild the database on each test run?
How to separate local/production/testing environments?

Would you share your unit testing setup?

I have been trying something like that:

// /tests/bootstrap.php
// ... setup paths and constants here
require_once 'Zend/Application.php';
// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

$application->bootstrap('doctrine');
$provider = new ZFDoctrine_Tool_DoctrineProvider;
$provider->generateModelsFromYaml();
//$provider->buildProject(true);

But this ends in:

Notice: Constant APPLICATION_PATH already defined in /home/user/www/library/ZendFramework/1.10.7/library/Zend/Tool/Project/Context/Zf/BootstrapFile.php on line 106

Fatal error: Call to a member function getResponse() on a non-object in /home/user/www/library/zf-doctrine/library/ZFDoctrine/Tool/DoctrineProvider.php on line 271

Models are not generated.

I get similar errors running:

$provider->createDatabase();

But in this case database is created.

The other provider commands do not work.

The solution:

$provider = new ZFDoctrine_Tool_DoctrineProvider;
$registry = new Zend_Tool_Framework_Registry;
$provider->setRegistry($registry);
@$provider->buildProject(true);

If anybody knows a better approach, please correct me.

Body:
I haven't used ZFDoctrine, but just plain Doctrine 1.2. I don't know if my solution is better but I figured I post if any1 is interested, here's the bootstrap.php in my tests folder:

<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../../application'));

// Define application environment
/**
 * In the application.ini:
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
doctrine.dsn = "mysql://my_user:passwd@localhost/my_phpunit_test_db"
 */
define('APPLICATION_ENV', 'testing');

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path()
)));

/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/../configs/application.ini'
);

$application->getBootstrap()->bootstrap();

// Can run out if too small
ini_set('memory_limit', '512M');

// Get the doctrine settings
$config = $application->getOption('doctrine');
$cli = new Doctrine_Cli($config);
$cli->run(array("doctrine", "build-all-reload","force"));

The key here is actually the last line that rebuilds all databases creating a clean environment for each testing.


问:
Angular2 RC6: '<component> is not a known element'
I am getting the following error in the browser console when trying to run my Angular 2 RC6 app:

```<code>> Error: Template parse errors: 'header-area' is not a known element:
> 1. If 'header-area' is an Angular component, then verify that it is part of this module.
> 2. If 'header-area' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component
> to suppress this message.("

    <div class="page-container">
        [ERROR->]<header-area></header-area>
        <div class="container-fluid">

> "): PlannerComponent@1:2
</code>```

I don't get why the component isn't found. My PlannerModule looks like this:

```<code>@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
    ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
    ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {}
</code>```

and as far as I understood the concept of Modules in ng2, the parts of the modules are declared in 'declarations'. For completeness, here is the PlannerComponent:

```<code>@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}
</code>```

and the HeaderAreaComponent:

```<code>@Component({
  selector: 'header-area',
  templateUrl: './header-area.component.html',
  styleUrls: ['./header-area.component.styl']
})
export default class HeaderAreaComponent {
}
</code>```

The -Tag is located in planner.component.html:

```<code><div class="page-container">
  <header-area></header-area>
  <div class="container-fluid">

    <div class="row">...
</code>```

Did I get something wrong?

Update: Complete code

planner.module.ts:

```<code>import HeaderAreaComponent from '../header-area/header-area.component';
import NavbarAreaComponent from '../navbar-area/navbar-area.component';
import GraphAreaComponent from '../graph-area/graph-area.component';
import EreignisbarAreaComponent from '../ereignisbar-area/ereignisbar-area.component';
import PlannerComponent from './planner.component';
import {NgModule} from '@angular/core';
import {nvD3} from 'ng2-nvd3';
import {RouterModule} from '@angular/router';
import {CommonModule} from '@angular/common';
import {ModalModule} from 'ng2-bootstrap/ng2-bootstrap';

@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
  ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
  ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {
  // TODO: get rid of the "unused class" warning
}
</code>```

planner.component.ts

```<code>import {Component} from '@angular/core';
import CalculationService from '../_shared/services/calculation.service/calculation.service';
import HeaderAreaComponent from '../header-area/header-area.component';

@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}
</code>```

planner.component.html

```<code><div class="page-container">
  <header-area></header-area>
  <div class="container-fluid">

    <div class="row">
      <div class="col-xs-2 col-sm-1 sidebar">
        <navbar-area></navbar-area>
      </div>
      <div class="col-xs-10 col-sm-11">
        <graph-area></graph-area>
      </div>
    </div><!--/.row-->

    <div class="row">
      <div class="col-xs-10 col-sm-11 offset-sm-1">
        <ereignisbar-area></ereignisbar-area>
      </div>
    </div><!--/.row-->

  </div><!--/.container-->
</div><!--/.page-container-->
</code>```

答:
When I had this problem, it was because I used 'templateUrl' instead of just 'template' in the decorator, since I use webpack and need to use require in it. Just be careful with the decorator name, in my case I generated the boilerplate code using a snippet, the decorator was created as:

```<code>@Component({
  selector: '',
  templateUrl: 'PATH_TO_TEMPLATE'
})
</code>```

but for webpack the decorator should be just 'template' NOT 'templateUrl', like so:

```<code>@Component({
  selector: '',
  template: require('PATH_TO_TEMPLATE')
})
</code>```

changing this solved the problem for me.

wanna know more about the two methods? read this medium post about template vs templateUrl

ContentLicense: CC BY-SA 4.0

Body:
I am getting the following error in the browser console when trying to run my Angular 2 RC6 app:

> Error: Template parse errors: 'header-area' is not a known element:
> 1. If 'header-area' is an Angular component, then verify that it is part of this module.
> 2. If 'header-area' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component
> to suppress this message.("

        [ERROR->]

> "): PlannerComponent@1:2

I don't get why the component isn't found. My PlannerModule looks like this:

@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
    ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
    ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {}

and as far as I understood the concept of Modules in ng2, the parts of the modules are declared in 'declarations'. For completeness, here is the PlannerComponent:

@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}

and the HeaderAreaComponent:

@Component({
  selector: 'header-area',
  templateUrl: './header-area.component.html',
  styleUrls: ['./header-area.component.styl']
})
export default class HeaderAreaComponent {
}

The -Tag is located in planner.component.html:

...

Did I get something wrong?

Update: Complete code

planner.module.ts:

import HeaderAreaComponent from '../header-area/header-area.component';
import NavbarAreaComponent from '../navbar-area/navbar-area.component';
import GraphAreaComponent from '../graph-area/graph-area.component';
import EreignisbarAreaComponent from '../ereignisbar-area/ereignisbar-area.component';
import PlannerComponent from './planner.component';
import {NgModule} from '@angular/core';
import {nvD3} from 'ng2-nvd3';
import {RouterModule} from '@angular/router';
import {CommonModule} from '@angular/common';
import {ModalModule} from 'ng2-bootstrap/ng2-bootstrap';

@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
  ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
  ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {
  // TODO: get rid of the "unused class" warning
}

planner.component.ts

import {Component} from '@angular/core';
import CalculationService from '../_shared/services/calculation.service/calculation.service';
import HeaderAreaComponent from '../header-area/header-area.component';

@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}

planner.component.html

        <navbar-area></navbar-area>

        <graph-area></graph-area>

        <ereignisbar-area></ereignisbar-area>

Body:
When I had this problem, it was because I used 'templateUrl' instead of just 'template' in the decorator, since I use webpack and need to use require in it. Just be careful with the decorator name, in my case I generated the boilerplate code using a snippet, the decorator was created as:

@Component({
  selector: '',
  templateUrl: 'PATH_TO_TEMPLATE'
})

but for webpack the decorator should be just 'template' NOT 'templateUrl', like so:

@Component({
  selector: '',
  template: require('PATH_TO_TEMPLATE')
})

changing this solved the problem for me.

wanna know more about the two methods? read this medium post about template vs templateUrl


问:
Solr highlighting does not work with multiple fields hl.fl when dynamic field is present
I have a dynamic text field bar_* in my index and want Solr to return highlightings for that field. So what I run is:

```<code>q=gold&hl=true&hl.fl=bar_*
</code>```

It works as expected BUT in case I add some more fields to hl.fl it stops working. E.g.

```<code>q=gold&hl=true&hl.fl=bar_*,foo
</code>```

Notes:

bar_* and foo fields are in the index/schema and there is no error here.

just rewriting request as q=gold&hl=true&hl.fl=bar_*&hl.fl=foo or q=gold&hl=true&hl.fl=bar_* foo does NOT help.

I didn't find any bugs in Solr JIRA on that topic.

Does anyone have an idea how to bit this. The possible workarounds that I see are:

Use hl.fl=*. But this one is not good for performance.

Explicitly specify all possible fields names for my dynamic field. But I don't like that at all.

答:
try </p>

```<code>q=gold&hl=true&hl.fl=bar_*&hl.fl=foo
</code>```

Body:
I have a dynamic text field bar_* in my index and want Solr to return highlightings for that field. So what I run is:

q=gold&hl=true&hl.fl=bar_*

It works as expected BUT in case I add some more fields to hl.fl it stops working. E.g.

q=gold&hl=true&hl.fl=bar_*,foo

Notes:

bar_* and foo fields are in the index/schema and there is no error here.

just rewriting request as q=gold&hl=true&hl.fl=bar_*&hl.fl=foo or q=gold&hl=true&hl.fl=bar_* foo does NOT help.

I didn't find any bugs in Solr JIRA on that topic.

Does anyone have an idea how to bit this. The possible workarounds that I see are:

Use hl.fl=*. But this one is not good for performance.

Explicitly specify all possible fields names for my dynamic field. But I don't like that at all.

Body:
try

q=gold&hl=true&hl.fl=bar_*&hl.fl=foo


问:
Simple multithreading program with emscripten
I am trying to create a simple program with thread support using Emscripten:

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

void *myThreadFun(void *vargp) {
  printf("From Thread \n");
  return NULL;
}

int main(int argc, char *argv[]) {

    pthread_t tid;
    printf("Before Thread\n");
    pthread_create(&tid, NULL, myThreadFun, NULL);
    printf("Before join\n");
    pthread_join(tid, NULL);
    printf("After Thread\n");

    return 0;
}
</code>```

I am executed it in Firefox and I compile using -s USE_PTHREADS=1.
This is the output I got in the console:

```<code>Before Thread
Preallocating 1 workers for a pthread spawn pool.
Before join
</code>```

But I expected:

```<code>Before Thread
Preallocating 1 workers for a pthread spawn pool.
Before join
After Thread
</code>```

It is like the thread is not ending. Am I missing something?

答: I had the same issue. I fixed it by compiling with -s PTHREAD_POOL_SIZE=x with x = number of thread created.

Body:
I am trying to create a simple program with thread support using Emscripten:

#include <stdio.h>
#include <pthread.h>

void *myThreadFun(void *vargp) {
  printf("From Thread \n");
  return NULL;
}

int main(int argc, char *argv[]) {

    pthread_t tid;
    printf("Before Thread\n");
    pthread_create(&tid, NULL, myThreadFun, NULL);
    printf("Before join\n");
    pthread_join(tid, NULL);
    printf("After Thread\n");

    return 0;
}

I am executed it in Firefox and I compile using -s USE_PTHREADS=1.
This is the output I got in the console:

Before Thread
Preallocating 1 workers for a pthread spawn pool.
Before join

But I expected:

Before Thread
Preallocating 1 workers for a pthread spawn pool.
Before join
After Thread

It is like the thread is not ending. Am I missing something?


问:
How to split an SQL Table into half and send the other half of the rows to new columns with SQL Query?
```<code>Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%
</code>```

Output :

```<code>Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%
</code>```

For example there is a table Country which has percentages, I need to divide the table in Half and show the remaining half (i.e. the remaining rows) in the new columns. I've also provided the table structure in text.

答:
My variant</p>

```<code>SELECT 'A' Country,1 Percentage INTO #Country
UNION ALL SELECT 'B' Country,2 Percentage
UNION ALL SELECT 'C' Country,3 Percentage
UNION ALL SELECT 'D' Country,4 Percentage
UNION ALL SELECT 'E' Country,5 Percentage

;WITH numCTE AS(
  SELECT
    *,
    ROW_NUMBER()OVER(ORDER BY Country) RowNum,
    COUNT(*)OVER() CountOfCountry
  FROM #Country
),
set1CTE AS(
  SELECT Country,Percentage,ROW_NUMBER()OVER(ORDER BY Country) RowNum
  FROM numCTE
  WHERE RowNum<=CEILING(CountOfCountry/2.)
),
set2CTE AS(
  SELECT Country,Percentage,ROW_NUMBER()OVER(ORDER BY Country) RowNum
  FROM numCTE
  WHERE RowNum>CEILING(CountOfCountry/2.)
)
SELECT
  s1.Country,s1.Percentage,
  s2.Country,s2.Percentage
FROM set1CTE s1
LEFT JOIN set2CTE s2 ON s1.RowNum=s2.RowNum

DROP TABLE #Country
</code>```

Body:
Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%

Output :

Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%

For example there is a table Country which has percentages, I need to divide the table in Half and show the remaining half (i.e. the remaining rows) in the new columns. I've also provided the table structure in text.

Body:
My variant

SELECT 'A' Country,1 Percentage INTO #Country
UNION ALL SELECT 'B' Country,2 Percentage
UNION ALL SELECT 'C' Country,3 Percentage
UNION ALL SELECT 'D' Country,4 Percentage
UNION ALL SELECT 'E' Country,5 Percentage

;WITH numCTE AS(
  SELECT
    *,
    ROW_NUMBER()OVER(ORDER BY Country) RowNum,
    COUNT(*)OVER() CountOfCountry
  FROM #Country
),
set1CTE AS(
  SELECT Country,Percentage,ROW_NUMBER()OVER(ORDER BY Country) RowNum
  FROM numCTE
  WHERE RowNum<=CEILING(CountOfCountry/2.)
),
set2CTE AS(
  SELECT Country,Percentage,ROW_NUMBER()OVER(ORDER BY Country) RowNum
  FROM numCTE
  WHERE RowNum>CEILING(CountOfCountry/2.)
)
SELECT
  s1.Country,s1.Percentage,
  s2.Country,s2.Percentage
FROM set1CTE s1
LEFT JOIN set2CTE s2 ON s1.RowNum=s2.RowNum

DROP TABLE #Country


问:
create transaction to stored procedures calls under c#
I am using stored procedures in sql server.
I have several stored procedures calls written in c#. I want to wrap them inside transaction:

```<code>//Begin Transaction here
sp1Call();
sp2Call();
sp3Call();
//Commit here
//Rollback if failed
</code>```

is there any way to do it?

Update:
I am using the enterprise library. example to sp1Call():

```<code>public static void sp1Call(string itemName)
    {
        DbCommand command = db.GetStoredProcCommand("dbo.sp1_insertItem");
        db.AddInParameter(command, "@item_name", DbType.String, itemName);
        db.ExecuteNonQuery(command);
    }
</code>```

答:
Just a quick search comes up with DBTransaction:</p>

```<code>   using (DbConnection connection = db.CreateConnection())
   {
     connection.Open();
     DbTransaction transaction = connection.BeginTransaction();
     try
     {
        DbCommand command = db.GetStoredProcCommand("dbo.sp1_insertItem");
        db.AddInParameter(command, "@item_name", DbType.String, itemName);
        db.ExecuteNonQuery(command, transaction);
        transaction.Commit();
     }
     catch
     {
       //Roll back the transaction.
       transaction.Rollback();
     }
   }
</code>```

Body:
I am using stored procedures in sql server.
I have several stored procedures calls written in c#. I want to wrap them inside transaction:

//Begin Transaction here
sp1Call();
sp2Call();
sp3Call();
//Commit here
//Rollback if failed

is there any way to do it?

Update:
I am using the enterprise library. example to sp1Call():

public static void sp1Call(string itemName)
    {
        DbCommand command = db.GetStoredProcCommand("dbo.sp1_insertItem");
        db.AddInParameter(command, "@item_name", DbType.String, itemName);
        db.ExecuteNonQuery(command);
    }

Body:
Just a quick search comes up with DBTransaction:

   using (DbConnection connection = db.CreateConnection())
   {
     connection.Open();
     DbTransaction transaction = connection.BeginTransaction();
     try
     {
        DbCommand command = db.GetStoredProcCommand("dbo.sp1_insertItem");
        db.AddInParameter(command, "@item_name", DbType.String, itemName);
        db.ExecuteNonQuery(command, transaction);
        transaction.Commit();
     }
     catch
     {
       //Roll back the transaction.
       transaction.Rollback();
     }
   }