问:
Accessing session in ASP.NET app via Context
I have a mvc action method, similar to the below construct.

```<code>public ActionResult About()
{
    System.Web.HttpContext.Current.Session["testValue"] = "about";
    ViewBag.Message = "Your application description page.";

    var sc = SynchronizationContext.Current;

    Task t = Task.Run(( ) => {

        string sessionValue = null;

        sc.Post((state)=> {
            //How do I access Session value here ?

        },null);

    });

    return View();
}
</code>```

I'm wondering how I access the "Session Value" in sc.Post method ? Basically, when the new thread starts, it needs to access the HttpSession of the parent.

答:
Since the Session is derived from the current thread, you have to inject the session from the originating request thread:

```<code>var session = System.Web.HttpContext.Current.Session;
</code>```

Then use session inside your thread delegate. Note that the session can be destructed in the meantime if the originating request is terminated.

```<code>session["testValue"] = "abc";
</code>```

Body:
I have a mvc action method, similar to the below construct.

public ActionResult About()
{
    System.Web.HttpContext.Current.Session["testValue"] = "about";
    ViewBag.Message = "Your application description page.";

    var sc = SynchronizationContext.Current;

    Task t = Task.Run(( ) => {

        string sessionValue = null;

        sc.Post((state)=> {
            //How do I access Session value here ?

        },null);

    });

    return View();
}

I'm wondering how I access the "Session Value" in sc.Post method ? Basically, when the new thread starts, it needs to access the HttpSession of the parent.

Body:
Since the Session is derived from the current thread, you have to inject the session from the originating request thread:

var session = System.Web.HttpContext.Current.Session;

Then use session inside your thread delegate. Note that the session can be destructed in the meantime if the originating request is terminated.

session["testValue"] = "abc";


来源: stackexchange

问:
Extracting, and then use in a comparison, the object type within a vector appropriately. c++
I have a vector of pointers to vehicles which contains vehicles like cars, lorries, motorcycles. These vehicles have positions associated with them and these positions are tracked and drawn using drawPoint() in QT. I would like to know how to implement an alternative way of checking the object type of each element, i.e, without using typeid.

```<code>for (unsigned int jV = 0; jV < fRoadDisp->getCurrentLane(iLane)->getNVehiclesinLane(); jV++)
   {
       //QPainter painter(this); //already done outside loop
       QPen pointpenv(Qt::red);
       pointpenv.setWidth(5);
       QPen pointpenC(Qt::blue); // For a Car
       pointpenC.setWidth(5);
       QPen pointpenL(Qt::green); // For a Lorry
       pointpenL.setWidth(5);
       QPen pointpenM(Qt::yellow); // For a Motorcycle
       pointpenM.setWidth(5);

       double position = fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)->getPosition();

       if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Car*)){painter.setPen(pointpenC);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Lorry*)){painter.setPen(pointpenL);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Motorcycle*)){painter.setPen(pointpenM);}

       painter.drawPoint(((iLane * (width()/fRoadDisp->getNLanes())) + width()/(2 *   fRoadDisp->getNLanes())), position * height()/300);
   }
</code>```

The above loops over all the vehicles in a vector of pointers to vehicles and just makes available different coloured pens for different vehicles, and, depending on which type of vehicle is being drawn, I would like the appropriate pen to be activated.

Currently, any points just appear white. A possible solution (I have been told) is to use static public variables, but I am not sure how to implement this in place of typeid.

Any help would be appreciated.

答:
I like the approach suggested by vahancho, but, given the necessary refactoring, I wouldn't add an enum to the scene and directly give a penColor property to  abstract Vehicle's, to avoid inspecting their type:

```<code>class Vehicle
{
public:
    virtual QColor penColor() const { return Qt::red; }
};
class Car : public Vehicle
{
  public:
  QColor penColor() const { return Qt::blue; }
};
</code>```

So you pick the right pen this way:

```<code>painter.setPen(QPen(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV).penColor()));
</code>```

No if's and no std::map needed.

However, if you think the penColor property doesn't exactly belong to a Vehicle, you can use a separate class to hold drawing information:

```<code>struct DrawingInfo
{
    DrawingInfo() : penColor(Qt::red), penWidth(5){}
    DrawingInfo(QColor c) : penColor(c), penWidth(5){}
    DrawingInfo(QColor c, int w) : penColor(c), penWidth(w){}

    QColor penColor;
    int penWidth;
};
</code>```

and give a Vehicle, and its derived classes, an instance of it:

```<code>class Vehicle
{
public:
    DrawingInfo drawingInfo() const { return _drawingInfo; }
protected:
    DrawingInfo _drawingInfo;
};
class Car : public Vehicle
{
public:
    Car()
    {
        _drawingInfo.penColor = Qt::blue;
    }
};
</code>```

This time, you can select the right pen this way:

```<code>Vehicle v = fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV);
QPen pen(v.drawingInfo().penColor);
pen.setWidth(v.drawingInfo().penWidth);
painter.setPen(pen);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a vector of pointers to vehicles which contains vehicles like cars, lorries, motorcycles. These vehicles have positions associated with them and these positions are tracked and drawn using drawPoint() in QT. I would like to know how to implement an alternative way of checking the object type of each element, i.e, without using typeid.

for (unsigned int jV = 0; jV < fRoadDisp->getCurrentLane(iLane)->getNVehiclesinLane(); jV++)
   {
       //QPainter painter(this); //already done outside loop
       QPen pointpenv(Qt::red);
       pointpenv.setWidth(5);
       QPen pointpenC(Qt::blue); // For a Car
       pointpenC.setWidth(5);
       QPen pointpenL(Qt::green); // For a Lorry
       pointpenL.setWidth(5);
       QPen pointpenM(Qt::yellow); // For a Motorcycle
       pointpenM.setWidth(5);

       double position = fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)->getPosition();

       if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Car*)){painter.setPen(pointpenC);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Lorry*)){painter.setPen(pointpenL);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Motorcycle*)){painter.setPen(pointpenM);}

       painter.drawPoint(((iLane * (width()/fRoadDisp->getNLanes())) + width()/(2 *   fRoadDisp->getNLanes())), position * height()/300);
   }

The above loops over all the vehicles in a vector of pointers to vehicles and just makes available different coloured pens for different vehicles, and, depending on which type of vehicle is being drawn, I would like the appropriate pen to be activated.

Currently, any points just appear white. A possible solution (I have been told) is to use static public variables, but I am not sure how to implement this in place of typeid.

Any help would be appreciated.

Body:
I like the approach suggested by vahancho, but, given the necessary refactoring, I wouldn't add an enum to the scene and directly give a penColor property to  abstract Vehicle's, to avoid inspecting their type:

class Vehicle
{
public:
    virtual QColor penColor() const { return Qt::red; }
};
class Car : public Vehicle
{
  public:
  QColor penColor() const { return Qt::blue; }
};

So you pick the right pen this way:

painter.setPen(QPen(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV).penColor()));

No if's and no std::map needed.

However, if you think the penColor property doesn't exactly belong to a Vehicle, you can use a separate class to hold drawing information:

struct DrawingInfo
{
    DrawingInfo() : penColor(Qt::red), penWidth(5){}
    DrawingInfo(QColor c) : penColor(c), penWidth(5){}
    DrawingInfo(QColor c, int w) : penColor(c), penWidth(w){}

    QColor penColor;
    int penWidth;
};

and give a Vehicle, and its derived classes, an instance of it:

class Vehicle
{
public:
    DrawingInfo drawingInfo() const { return _drawingInfo; }
protected:
    DrawingInfo _drawingInfo;
};
class Car : public Vehicle
{
public:
    Car()
    {
        _drawingInfo.penColor = Qt::blue;
    }
};

This time, you can select the right pen this way:

Vehicle v = fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV);
QPen pen(v.drawingInfo().penColor);
pen.setWidth(v.drawingInfo().penWidth);
painter.setPen(pen);


问:
Execute Same Jenkins job "N" number of times based on the value received for parameter "N "
Execute Same Jenkins job N number of times based on the value received for parameter N </p>

答:
Running same job in parallel means they all use same workspace, in most loop kind of execution.

SOLUTION: Use MultiJob, with all jobs in same phases.

Clone same job, in needed number of instances (i.e N=3) that need to be executed in parallel.

Create MultiJob with just one phase

Set all 3 jobs in same phase in MultiJob, and all of them will run in parallel.


问:
Indentation for files that don't have a registered formatter
It seems that I am getting this problem since version 1.18, honestly I don't remember.
With VSCodeVim installed I used to press the = key to get my code (Elixir, embedded elixir, ...) indented properly.

Am I missing something, like a configuration, that would allow me to re-indent my files without having a nagging "Formatter for file x not installed".

This is honestly the only things that nags me with VSCode so far, love the speed, the capabilities and the UI...

答: Select the contents of file.Bottom right corner shows spaces/tabs: 2/4. You can click on that and indent the whole file.


问:
React Starter Kit sass-loader performance
While working on dev using npm run start everything seems to be fine in terms of webpack build speeds, but on production, when running npm run build it takes more than 5min to build the the app. I compared the build speed to the older versions of the app as well as a clean RSK build, and I thought the slowdown might be caused by sass-loader so profiled the build and looked at what http://webpack.github.io/analyse would tell me.

Seems like the sass-loader is indeed at fault here. I tried using fast-sass-loader but that increased the build time instead of reducing it. Prefetching the loaders like the analyse tool suggests didn't help either.

Here are the package.json and webpack.config.js files it's using.

package.json

```<code>{
  "name": "web",
  "version": "2.14.7",
  "private": true,
  "engines": {
    "node": ">='6.5'",
    "npm": ">=3.10"
  },
  "browserslist": [
    ">1%",
    "last 4 versions",
    "Firefox ESR",
    "not ie < 9"
  ],
  "dependencies": {
    "apollo-client": "^1.7.0",
    "axios": "^0.15.3",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-polyfill": "^6.22.0",
    "bcrypt": "^1.0.2",
    "bcryptjs": "^2.4.3",
    "bluebird": "^3.5.1",
    "body-parser": "^1.16.0",
    "bootstrap": "4.0.0-beta",
    "bugsnag": "^2.0.0",
    "classnames": "^2.2.5",
    "compression": "^1.7.1",
    "connect-ensure-login": "^0.1.1",
    "cookie-parser": "^1.4.3",
    "core-js": "^2.4.1",
    "express": "^4.16.2",
    "express-graphql": "^0.6.3",
    "express-jwt": "^5.1.0",
    "express-request-language": "^1.1.9",
    "express-session": "^1.15.6",
    "fastclick": "^1.0.6",
    "fb": "^2.0.0",
    "fbjs": "^0.8.9",
    "flatpickr": "^3.0.7",
    "graphql": "^0.10.3",
    "graphql-date": "^1.0.3",
    "graphql-relay": "^0.5.1",
    "graphql-sequelize": "^5.4.2",
    "graphql-tag": "^1.2.4",
    "he": "^1.1.1",
    "history": "^4.5.1",
    "intl": "^1.2.5",
    "intl-locales-supported": "^1.0.0",
    "isomorphic-style-loader": "^4.0.0",
    "jsonwebtoken": "^7.2.1",
    "lodash": "^4.17.4",
    "mailchimp-api-v3": "^1.7.1",
    "moment": "^2.18.1",
    "node-fetch": "^1.6.3",
    "node-sass": "^4.5.3",
    "normalize.css": "^5.0.0",
    "nouislider": "^10.1.0",
    "passport": "^0.4.0",
    "passport-facebook": "^2.1.1",
    "passport-local": "^1.0.0",
    "pg": "^6.1.2",
    "pretty-error": "^2.0.2",
    "prop-types": "^15.6.0",
    "query-string": "^4.3.1",
    "react": "^16.0.0",
    "react-addons-css-transition-group": "^15.6.0",
    "react-addons-shallow-compare": "^15.6.0",
    "react-addons-transition-group": "^15.6.0",
    "react-apollo": "^1.4.3",
    "react-bootstrap": "^0.31.0",
    "react-calendar": "^1.1.0",
    "react-dates": "^12.5.1",
    "react-day-picker": "^6.1.0",
    "react-dom": "^16.0.0",
    "react-google-maps": "^8.5.0",
    "react-images": "^0.5.11",
    "react-intl": "^2.2.3",
    "react-redux": "^5.0.5",
    "react-router": "^3.0.2",
    "react-select": "^1.0.0-rc.5",
    "react-table": "^6.5.3",
    "react-toastify": "^2.0.0",
    "reactstrap": "^5.0.0-alpha.3",
    "recompose": "^0.25.0",
    "redux": "^3.7.1",
    "redux-form": "^7.0.3",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.2.0",
    "sanitize-html": "^1.15.0",
    "sass-loader": "^6.0.6",
    "sequelize": "^4.13.2",
    "sequelize-cli": "^2.5.1",
    "sequelize-slugify": "^0.5.0",
    "serialize-javascript": "^1.3.0",
    "source-map-support": "^0.4.11",
    "umzug": "^2.0.1",
    "universal-router": "^5.0.0",
    "whatwg-fetch": "^2.0.2"
  },
  "devDependencies": {
    "assets-webpack-plugin": "^3.5.1",
    "autoprefixer": "^6.7.2",
    "babel-cli": "^6.22.2",
    "babel-core": "^6.22.1",
    "babel-eslint": "^7.1.1",
    "babel-loader": "^6.2.10",
    "babel-plugin-react-intl": "^2.3.1",
    "babel-plugin-rewire": "^1.0.0",
    "babel-preset-env": "^1.1.8",
    "babel-preset-react": "^6.22.0",
    "babel-preset-react-optimize": "^1.0.1",
    "babel-preset-stage-2": "^6.22.0",
    "babel-register": "^6.22.0",
    "babel-template": "^6.22.0",
    "babel-types": "^6.22.0",
    "browser-sync": "^2.18.7",
    "chai": "^3.5.0",
    "chokidar": "^1.6.1",
    "css-loader": "^0.26.1",
    "editorconfig-tools": "^0.1.1",
    "enzyme": "^2.7.1",
    "eslint": "^3.15.0",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-loader": "^1.6.1",
    "eslint-plugin-css-modules": "^2.2.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.9.0",
    "file-loader": "^0.10.0",
    "front-matter": "^2.1.2",
    "glob": "^7.1.1",
    "json-loader": "^0.5.4",
    "lint-staged": "^3.3.0",
    "markdown-it": "^8.2.2",
    "mkdirp": "^0.5.1",
    "mocha": "^3.2.0",
    "pixrem": "^3.0.2",
    "pleeease-filters": "^3.0.0",
    "postcss": "^5.2.12",
    "postcss-calc": "^5.3.1",
    "postcss-color-function": "^3.0.0",
    "postcss-custom-media": "^5.0.1",
    "postcss-custom-properties": "^5.0.2",
    "postcss-custom-selectors": "^3.0.0",
    "postcss-flexbugs-fixes": "^2.1.0",
    "postcss-loader": "^1.2.2",
    "postcss-media-minmax": "^2.1.2",
    "postcss-nested": "^1.0.0",
    "postcss-nesting": "^2.3.1",
    "postcss-partial-import": "^3.1.0",
    "postcss-pseudoelements": "^3.0.0",
    "postcss-selector-matches": "^2.0.5",
    "postcss-selector-not": "^2.0.0",
    "postcss-url": "^5.1.2",
    "pre-commit": "^1.2.2",
    "raw-loader": "^0.5.1",
    "react-addons-test-utils": "^15.4.2",
    "react-deep-force-update": "^2.0.1",
    "react-hot-loader": "^3.0.0-beta.6",
    "redbox-react": "^1.3.3",
    "redux-mock-store": "^1.2.1",
    "rimraf": "^2.5.4",
    "sinon": "^2.0.0-pre.5",
    "stylefmt": "^5.1.1",
    "stylelint": "^7.8.0",
    "stylelint-config-standard": "^16.0.0",
    "url-loader": "^0.5.7",
    "webpack": "^2.2.1",
    "webpack-bundle-analyzer": "^2.3.0",
    "webpack-dev-middleware": "^1.10.0",
    "webpack-hot-middleware": "^2.16.1",
    "write-file-webpack-plugin": "^3.4.2"
  },
  "babel": {
    "presets": [
      [
        "env",
        {
          "targets": {
            "node": "current"
          }
        }
      ],
      "stage-2",
      "react"
    ],
    "env": {
      "test": {
        "plugins": [
          "rewire"
        ]
      }
    }
  },
  "eslintConfig": {
    "parser": "babel-eslint",
    "extends": [
      "airbnb",
      "plugin:css-modules/recommended"
    ],
    "plugins": [
      "css-modules"
    ],
    "globals": {
      "__DEV__": true
    },
    "env": {
      "browser": true
    },
    "rules": {
      "import/extensions": "off",
      "import/no-extraneous-dependencies": "off",
      "no-plusplus": [
        "error",
        {
          "allowForLoopAfterthoughts": true
        }
      ],
      "react/jsx-filename-extension": "off",
      "react/prefer-stateless-function": "off",
      "react/prop-types": "off"
    }
  },
  "stylelint": {
    "extends": "stylelint-config-standard",
    "rules": {
      "string-quotes": "single",
      "property-no-unknown": [
        true,
        {
          "ignoreProperties": [
            "composes"
          ]
        }
      ],
      "selector-pseudo-class-no-unknown": [
        true,
        {
          "ignorePseudoClasses": [
            "global"
          ]
        }
      ]
    }
  },
  "pre-commit": "lint:staged",
  "lint-staged": {
    "*.{cmd,html,json,md,sh,txt,xml,yml}": [
      "editorconfig-tools fix",
      "git add"
    ],
    "*.{js,jsx}": [
      "eslint --fix",
      "git add"
    ],
    "*.{css,less,sss}": [
      "stylefmt",
      "stylelint",
      "git add"
    ]
  },
  "scripts": {
    "lint:js": "eslint src tools",
    "lint:css": "stylelint \"src/**/*.{css,less,sss}\"",
    "lint:staged": "lint-staged || true",
    "lint": "yarn run lint:js && yarn run lint:css",
    "test": "mocha \"src/**/*.test.js\" --require babel-register --require test/setup.js",
    "test:watch": "yarn run test -- --reporter min --watch",
    "clean": "babel-node tools/run clean",
    "copy": "babel-node tools/run copy",
    "extractMessages": "babel-node tools/run extractMessages",
    "bundle": "babel-node tools/run bundle",
    "build": "babel-node tools/run build",
    "build:stats": "yarn run build -- --release --analyse",
    "deploy": "babel-node tools/run deploy",
    "render": "babel-node tools/run render",
    "serve": "babel-node tools/run runServer",
    "start": "yarn run migrate && babel-node tools/run start",
    "migrate": "sequelize db:migrate",
    "seed": "sequelize db:seed:all",
    "seed:undo": "sequelize db:seed:undo:all",
  }
}
</code>```

webpack.config.js

```<code>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import path from 'path';
import webpack from 'webpack';
import AssetsPlugin from 'assets-webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import pkg from '../package.json';

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const isAnalyse = process.argv.includes('--analyse') || process.argv.includes('--analyze');
const port = parseInt(process.env.PORT || '3000', 10);
const analyzerPort = port + 3;

// Can be `server`, `static` or `disabled`.
// In `server` mode analyzer will start HTTP server to show bundle report.
// In `static` mode single HTML file with bundle report will be generated.
// In `disabled` mode you can use this plugin to just generate Webpack Stats JSON
// file by setting `generateStatsFile` to `true`.
let analyzerMode = 'disabled';
if (isAnalyse) {
  analyzerMode = 'server';
} else if (!isDebug) {
  analyzerMode = 'static';
}

//
// Common configuration chunk to be used for both
// client-side (client.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------

const config = {
  context: path.resolve(__dirname, '../src'),

  output: {
    path: path.resolve(__dirname, '../build/public/assets'),
    publicPath: '/assets/',
    pathinfo: isVerbose,
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: [
          path.resolve(__dirname, '../src'),
        ],
        query: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
            ['env', {
              targets: {
                browsers: pkg.browserslist,
              },
              modules: false,
              useBuiltIns: false,
              debug: false,
            }],
            // Experimental ECMAScript proposals
            // https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-
            'stage-2',
            // JSX, Flow
            // https://github.com/babel/babel/tree/master/packages/babel-preset-react
            'react',
            // Optimize React code for the production build
            // https://github.com/thejameskyle/babel-react-optimize
            ...isDebug ? [] : ['react-optimize'],
          ],
          plugins: [
            // Adds component stack to warning messages
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx-source
            ...isDebug ? ['transform-react-jsx-source'] : [],
            // Adds __self attribute to JSX which React will use for some warnings
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx-self
            ...isDebug ? ['transform-react-jsx-self'] : [],
            'react-intl',
          ],
        },
      },
      {
        test: /^((?!\.local).)*\.scss$/,
        use: [
          {
            loader: 'isomorphic-style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: isDebug ? '[name]-[local]-[hash:base64:5]' : '[hash:base64:5]',
              // CSS Nano http://cssnano.co/options/
              minimize: !isDebug,
              discardComments: { removeAll: true },
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              config: './tools/postcss.config.js',
            },
          },
          {
            loader: 'sass-loader',
          },
        ],
      },
      {
        test: /\.local.scss$/,
        use: [
          {
            loader: 'isomorphic-style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: '[local]',
              // CSS Nano http://cssnano.co/options/
              minimize: !isDebug,
              discardComments: { removeAll: true },
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              config: './tools/postcss.config.js',
            },
          },
          {
            loader: 'sass-loader',
          },
        ],
      },
      {
        test: /\.css/,
        use: [
          {
            loader: 'isomorphic-style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: isDebug ? '[name]-[local]-[hash:base64:5]' : '[hash:base64:5]',
              // CSS Nano http://cssnano.co/options/
              minimize: !isDebug,
              discardComments: { removeAll: true },
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              config: './tools/postcss.config.js',
            },
          },
        ],
      },
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './lib/markdown-loader.js'),
      },
      {
        test: /\.txt$/,
        loader: 'raw-loader',
      },
      {
        test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
        loader: 'file-loader',
        query: {
          name: isDebug ? '[path][name].[ext]?[hash:8]' : '[hash:8].[ext]',
        },
      },
      {
        test: /\.(mp4|webm|wav|mp3|m4a|aac|oga)(\?.*)?$/,
        loader: 'url-loader',
        query: {
          name: isDebug ? '[path][name].[ext]?[hash:8]' : '[hash:8].[ext]',
          limit: 10000,
        },
      },
      {
        test: /\.(graphql|gql)$/,
        exclude: /node_modules/,
        loader: 'graphql-tag/loader',
      },
    ],
  },

  resolve: {
    modules: [path.resolve(__dirname, '../src'), 'node_modules'],
  },

  // Don't attempt to continue if there are any errors.
  bail: !isDebug,

  cache: isDebug,

  stats: {
    colors: true,
    reasons: isDebug,
    hash: isVerbose,
    version: isVerbose,
    timings: true,
    chunks: isVerbose,
    chunkModules: isVerbose,
    cached: isVerbose,
    cachedAssets: isVerbose,
  },
};

//
// Configuration for the client-side bundle (client.js)
// -----------------------------------------------------------------------------

const clientConfig = {
  ...config,

  name: 'client',
  target: 'web',

  entry: {
    client: ['babel-polyfill', './clientLoader.js'],
  },

  output: {
    ...config.output,
    filename: isDebug ? '[name].js' : '[name].[chunkhash:8].js',
    chunkFilename: isDebug ? '[name].chunk.js' : '[name].[chunkhash:8].chunk.js',
  },

  resolve: { ...config.resolve },

  plugins: [
    // Define free variables
    // https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': true,
      __DEV__: isDebug,
    }),

    // Emit a file with assets paths
    // https://github.com/sporto/assets-webpack-plugin#options
    new AssetsPlugin({
      path: path.resolve(__dirname, '../build'),
      filename: 'assets.json',
      prettyPrint: true,
    }),

    // Move modules that occur in multiple entry chunks to a new entry chunk (the commons chunk).
    // http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: module => /node_modules/.test(module.resource),
    }),

    ...isDebug ? [] : [
      // Minimize all JavaScript output of chunks
      // https://github.com/mishoo/UglifyJS2#compressor-options
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          screw_ie8: true, // React doesn't support IE8
          warnings: isVerbose,
          unused: true,
          dead_code: true,
        },
        mangle: {
          screw_ie8: true,
        },
        output: {
          comments: false,
          screw_ie8: true,
        },
      }),
    ],

    new BundleAnalyzerPlugin({
      // See above
      analyzerMode,
      // Host that will be used in `server` mode to start HTTP server.
      analyzerHost: '127.0.0.1',
      // Port that will be used in `server` mode to start HTTP server.
      analyzerPort,
      // Path to bundle report file that will be generated in `static` mode.
      // Relative to bundles output directory.
      reportFilename: path.resolve(__dirname, '../report.html'),
      // Automatically open report in default browser
      openAnalyzer: true,
      // If `true`, Webpack Stats JSON file will be generated in bundles output directory
      generateStatsFile: !isDebug,
      // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
      // Relative to bundles output directory.
      statsFilename: path.resolve(__dirname, '../stats.json'),
      // Options for `stats.toJson()` method.
      // You can exclude sources of your modules from stats file with `source: false` option.
      // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
      statsOptions: null,
      // Log level. Can be 'info', 'warn', 'error' or 'silent'.
      logLevel: 'info',
    }),
  ],

  // Choose a developer tool to enhance debugging
  // http://webpack.github.io/docs/configuration.html#devtool
  devtool: isDebug ? 'cheap-module-source-map' : false,

  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  // https://webpack.github.io/docs/configuration.html#node
  // https://github.com/webpack/node-libs-browser/tree/master/mock
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};

//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------

const serverConfig = {
  ...config,

  name: 'server',
  target: 'node',

  entry: {
    server: ['babel-polyfill', './server.js'],
  },

  output: {
    ...config.output,
    filename: '../../server.js',
    libraryTarget: 'commonjs2',
  },

  module: {
    ...config.module,

    // Override babel-preset-env configuration for Node.js
    rules: config.module.rules.map(rule => (rule.loader !== 'babel-loader' ? rule : {
      ...rule,
      query: {
        ...rule.query,
        presets: rule.query.presets.map(preset => (preset[0] !== 'env' ? preset : ['env', {
          targets: {
            node: parseFloat(pkg.engines.node.replace(/^\D+/g, '')),
          },
          modules: false,
          useBuiltIns: false,
          debug: false,
        }])),
      },
    })),
  },

  resolve: { ...config.resolve },

  externals: [
    /^\.\/assets\.json$/,
    (context, request, callback) => {
      const isExternal =
        request.match(/^[@a-z][a-z/.\-0-9]*$/i) &&
        !request.match(/\.(css|less|scss|sss)$/i);
      callback(null, Boolean(isExternal));
    },
  ],

  plugins: [
    // Define free variables
    // https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': false,
      __DEV__: isDebug,
    }),

    // Do not create separate chunks of the server bundle
    // https://webpack.github.io/docs/list-of-plugins.html#limitchunkcountplugin
    new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),

    // Adds a banner to the top of each generated chunk
    // https://webpack.github.io/docs/list-of-plugins.html#bannerplugin
    new webpack.BannerPlugin({
      banner: 'require("source-map-support").install();',
      raw: true,
      entryOnly: false,
    }),
  ],

  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },

  devtool: isDebug ? 'cheap-module-source-map' : 'source-map',
};

export default [clientConfig, serverConfig];
</code>```

答:
Since project works fine and quickly in development mode, so it's reasonable to find major differences between dev and prod builds.

First valuable difference is minimize option in css-loader (minimize: !isDebug) and included react-optimize plugin. Since they can potentially perform aggressive optimizations, it can slow down production build.

Secondly resolving for css-like files performs in dedicated manner - by webpack resolver function: !request.match(/\.(css|less|scss|sss)$/i). If target file are present in root bundle three, there is no reason to perform such resolution. If not - maybe redundant files from node_modules or somethere are present.

Also you can try ready isomorphic solution with frontend+backend bundling and includes css support, like resolve-app.

Body:
While working on dev using npm run start everything seems to be fine in terms of webpack build speeds, but on production, when running npm run build it takes more than 5min to build the the app. I compared the build speed to the older versions of the app as well as a clean RSK build, and I thought the slowdown might be caused by sass-loader so profiled the build and looked at what http://webpack.github.io/analyse would tell me.

Seems like the sass-loader is indeed at fault here. I tried using fast-sass-loader but that increased the build time instead of reducing it. Prefetching the loaders like the analyse tool suggests didn't help either.

Here are the package.json and webpack.config.js files it's using.

package.json

{
  "name": "web",
  "version": "2.14.7",
  "private": true,
  "engines": {
    "node": ">='6.5'",
    "npm": ">=3.10"
  },
  "browserslist": [
    ">1%",
    "last 4 versions",
    "Firefox ESR",
    "not ie < 9"
  ],
  "dependencies": {
    "apollo-client": "^1.7.0",
    "axios": "^0.15.3",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-polyfill": "^6.22.0",
    "bcrypt": "^1.0.2",
    "bcryptjs": "^2.4.3",
    "bluebird": "^3.5.1",
    "body-parser": "^1.16.0",
    "bootstrap": "4.0.0-beta",
    "bugsnag": "^2.0.0",
    "classnames": "^2.2.5",
    "compression": "^1.7.1",
    "connect-ensure-login": "^0.1.1",
    "cookie-parser": "^1.4.3",
    "core-js": "^2.4.1",
    "express": "^4.16.2",
    "express-graphql": "^0.6.3",
    "express-jwt": "^5.1.0",
    "express-request-language": "^1.1.9",
    "express-session": "^1.15.6",
    "fastclick": "^1.0.6",
    "fb": "^2.0.0",
    "fbjs": "^0.8.9",
    "flatpickr": "^3.0.7",
    "graphql": "^0.10.3",
    "graphql-date": "^1.0.3",
    "graphql-relay": "^0.5.1",
    "graphql-sequelize": "^5.4.2",
    "graphql-tag": "^1.2.4",
    "he": "^1.1.1",
    "history": "^4.5.1",
    "intl": "^1.2.5",
    "intl-locales-supported": "^1.0.0",
    "isomorphic-style-loader": "^4.0.0",
    "jsonwebtoken": "^7.2.1",
    "lodash": "^4.17.4",
    "mailchimp-api-v3": "^1.7.1",
    "moment": "^2.18.1",
    "node-fetch": "^1.6.3",
    "node-sass": "^4.5.3",
    "normalize.css": "^5.0.0",
    "nouislider": "^10.1.0",
    "passport": "^0.4.0",
    "passport-facebook": "^2.1.1",
    "passport-local": "^1.0.0",
    "pg": "^6.1.2",
    "pretty-error": "^2.0.2",
    "prop-types": "^15.6.0",
    "query-string": "^4.3.1",
    "react": "^16.0.0",
    "react-addons-css-transition-group": "^15.6.0",
    "react-addons-shallow-compare": "^15.6.0",
    "react-addons-transition-group": "^15.6.0",
    "react-apollo": "^1.4.3",
    "react-bootstrap": "^0.31.0",
    "react-calendar": "^1.1.0",
    "react-dates": "^12.5.1",
    "react-day-picker": "^6.1.0",
    "react-dom": "^16.0.0",
    "react-google-maps": "^8.5.0",
    "react-images": "^0.5.11",
    "react-intl": "^2.2.3",
    "react-redux": "^5.0.5",
    "react-router": "^3.0.2",
    "react-select": "^1.0.0-rc.5",
    "react-table": "^6.5.3",
    "react-toastify": "^2.0.0",
    "reactstrap": "^5.0.0-alpha.3",
    "recompose": "^0.25.0",
    "redux": "^3.7.1",
    "redux-form": "^7.0.3",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.2.0",
    "sanitize-html": "^1.15.0",
    "sass-loader": "^6.0.6",
    "sequelize": "^4.13.2",
    "sequelize-cli": "^2.5.1",
    "sequelize-slugify": "^0.5.0",
    "serialize-javascript": "^1.3.0",
    "source-map-support": "^0.4.11",
    "umzug": "^2.0.1",
    "universal-router": "^5.0.0",
    "whatwg-fetch": "^2.0.2"
  },
  "devDependencies": {
    "assets-webpack-plugin": "^3.5.1",
    "autoprefixer": "^6.7.2",
    "babel-cli": "^6.22.2",
    "babel-core": "^6.22.1",
    "babel-eslint": "^7.1.1",
    "babel-loader": "^6.2.10",
    "babel-plugin-react-intl": "^2.3.1",
    "babel-plugin-rewire": "^1.0.0",
    "babel-preset-env": "^1.1.8",
    "babel-preset-react": "^6.22.0",
    "babel-preset-react-optimize": "^1.0.1",
    "babel-preset-stage-2": "^6.22.0",
    "babel-register": "^6.22.0",
    "babel-template": "^6.22.0",
    "babel-types": "^6.22.0",
    "browser-sync": "^2.18.7",
    "chai": "^3.5.0",
    "chokidar": "^1.6.1",
    "css-loader": "^0.26.1",
    "editorconfig-tools": "^0.1.1",
    "enzyme": "^2.7.1",
    "eslint": "^3.15.0",
    "eslint-config-airbnb": "^14.1.0",
    "eslint-loader": "^1.6.1",
    "eslint-plugin-css-modules": "^2.2.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^4.0.0",
    "eslint-plugin-react": "^6.9.0",
    "file-loader": "^0.10.0",
    "front-matter": "^2.1.2",
    "glob": "^7.1.1",
    "json-loader": "^0.5.4",
    "lint-staged": "^3.3.0",
    "markdown-it": "^8.2.2",
    "mkdirp": "^0.5.1",
    "mocha": "^3.2.0",
    "pixrem": "^3.0.2",
    "pleeease-filters": "^3.0.0",
    "postcss": "^5.2.12",
    "postcss-calc": "^5.3.1",
    "postcss-color-function": "^3.0.0",
    "postcss-custom-media": "^5.0.1",
    "postcss-custom-properties": "^5.0.2",
    "postcss-custom-selectors": "^3.0.0",
    "postcss-flexbugs-fixes": "^2.1.0",
    "postcss-loader": "^1.2.2",
    "postcss-media-minmax": "^2.1.2",
    "postcss-nested": "^1.0.0",
    "postcss-nesting": "^2.3.1",
    "postcss-partial-import": "^3.1.0",
    "postcss-pseudoelements": "^3.0.0",
    "postcss-selector-matches": "^2.0.5",
    "postcss-selector-not": "^2.0.0",
    "postcss-url": "^5.1.2",
    "pre-commit": "^1.2.2",
    "raw-loader": "^0.5.1",
    "react-addons-test-utils": "^15.4.2",
    "react-deep-force-update": "^2.0.1",
    "react-hot-loader": "^3.0.0-beta.6",
    "redbox-react": "^1.3.3",
    "redux-mock-store": "^1.2.1",
    "rimraf": "^2.5.4",
    "sinon": "^2.0.0-pre.5",
    "stylefmt": "^5.1.1",
    "stylelint": "^7.8.0",
    "stylelint-config-standard": "^16.0.0",
    "url-loader": "^0.5.7",
    "webpack": "^2.2.1",
    "webpack-bundle-analyzer": "^2.3.0",
    "webpack-dev-middleware": "^1.10.0",
    "webpack-hot-middleware": "^2.16.1",
    "write-file-webpack-plugin": "^3.4.2"
  },
  "babel": {
    "presets": [
      [
        "env",
        {
          "targets": {
            "node": "current"
          }
        }
      ],
      "stage-2",
      "react"
    ],
    "env": {
      "test": {
        "plugins": [
          "rewire"
        ]
      }
    }
  },
  "eslintConfig": {
    "parser": "babel-eslint",
    "extends": [
      "airbnb",
      "plugin:css-modules/recommended"
    ],
    "plugins": [
      "css-modules"
    ],
    "globals": {
      "__DEV__": true
    },
    "env": {
      "browser": true
    },
    "rules": {
      "import/extensions": "off",
      "import/no-extraneous-dependencies": "off",
      "no-plusplus": [
        "error",
        {
          "allowForLoopAfterthoughts": true
        }
      ],
      "react/jsx-filename-extension": "off",
      "react/prefer-stateless-function": "off",
      "react/prop-types": "off"
    }
  },
  "stylelint": {
    "extends": "stylelint-config-standard",
    "rules": {
      "string-quotes": "single",
      "property-no-unknown": [
        true,
        {
          "ignoreProperties": [
            "composes"
          ]
        }
      ],
      "selector-pseudo-class-no-unknown": [
        true,
        {
          "ignorePseudoClasses": [
            "global"
          ]
        }
      ]
    }
  },
  "pre-commit": "lint:staged",
  "lint-staged": {
    "*.{cmd,html,json,md,sh,txt,xml,yml}": [
      "editorconfig-tools fix",
      "git add"
    ],
    "*.{js,jsx}": [
      "eslint --fix",
      "git add"
    ],
    "*.{css,less,sss}": [
      "stylefmt",
      "stylelint",
      "git add"
    ]
  },
  "scripts": {
    "lint:js": "eslint src tools",
    "lint:css": "stylelint \"src/**/*.{css,less,sss}\"",
    "lint:staged": "lint-staged || true",
    "lint": "yarn run lint:js && yarn run lint:css",
    "test": "mocha \"src/**/*.test.js\" --require babel-register --require test/setup.js",
    "test:watch": "yarn run test -- --reporter min --watch",
    "clean": "babel-node tools/run clean",
    "copy": "babel-node tools/run copy",
    "extractMessages": "babel-node tools/run extractMessages",
    "bundle": "babel-node tools/run bundle",
    "build": "babel-node tools/run build",
    "build:stats": "yarn run build -- --release --analyse",
    "deploy": "babel-node tools/run deploy",
    "render": "babel-node tools/run render",
    "serve": "babel-node tools/run runServer",
    "start": "yarn run migrate && babel-node tools/run start",
    "migrate": "sequelize db:migrate",
    "seed": "sequelize db:seed:all",
    "seed:undo": "sequelize db:seed:undo:all",
  }
}

webpack.config.js

/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import path from 'path';
import webpack from 'webpack';
import AssetsPlugin from 'assets-webpack-plugin';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import pkg from '../package.json';

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const isAnalyse = process.argv.includes('--analyse') || process.argv.includes('--analyze');
const port = parseInt(process.env.PORT || '3000', 10);
const analyzerPort = port + 3;

// Can be `server`, `static` or `disabled`.
// In `server` mode analyzer will start HTTP server to show bundle report.
// In `static` mode single HTML file with bundle report will be generated.
// In `disabled` mode you can use this plugin to just generate Webpack Stats JSON
// file by setting `generateStatsFile` to `true`.
let analyzerMode = 'disabled';
if (isAnalyse) {
  analyzerMode = 'server';
} else if (!isDebug) {
  analyzerMode = 'static';
}

//
// Common configuration chunk to be used for both
// client-side (client.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------

const config = {
  context: path.resolve(__dirname, '../src'),

  output: {
    path: path.resolve(__dirname, '../build/public/assets'),
    publicPath: '/assets/',
    pathinfo: isVerbose,
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: [
          path.resolve(__dirname, '../src'),
        ],
        query: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
            ['env', {
              targets: {
                browsers: pkg.browserslist,
              },
              modules: false,
              useBuiltIns: false,
              debug: false,
            }],
            // Experimental ECMAScript proposals
            // https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-
            'stage-2',
            // JSX, Flow
            // https://github.com/babel/babel/tree/master/packages/babel-preset-react
            'react',
            // Optimize React code for the production build
            // https://github.com/thejameskyle/babel-react-optimize
            ...isDebug ? [] : ['react-optimize'],
          ],
          plugins: [
            // Adds component stack to warning messages
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx-source
            ...isDebug ? ['transform-react-jsx-source'] : [],
            // Adds __self attribute to JSX which React will use for some warnings
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx-self
            ...isDebug ? ['transform-react-jsx-self'] : [],
            'react-intl',
          ],
        },
      },
      {
        test: /^((?!\.local).)*\.scss$/,
        use: [
          {
            loader: 'isomorphic-style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: isDebug ? '[name]-[local]-[hash:base64:5]' : '[hash:base64:5]',
              // CSS Nano http://cssnano.co/options/
              minimize: !isDebug,
              discardComments: { removeAll: true },
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              config: './tools/postcss.config.js',
            },
          },
          {
            loader: 'sass-loader',
          },
        ],
      },
      {
        test: /\.local.scss$/,
        use: [
          {
            loader: 'isomorphic-style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: '[local]',
              // CSS Nano http://cssnano.co/options/
              minimize: !isDebug,
              discardComments: { removeAll: true },
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              config: './tools/postcss.config.js',
            },
          },
          {
            loader: 'sass-loader',
          },
        ],
      },
      {
        test: /\.css/,
        use: [
          {
            loader: 'isomorphic-style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: isDebug ? '[name]-[local]-[hash:base64:5]' : '[hash:base64:5]',
              // CSS Nano http://cssnano.co/options/
              minimize: !isDebug,
              discardComments: { removeAll: true },
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              config: './tools/postcss.config.js',
            },
          },
        ],
      },
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './lib/markdown-loader.js'),
      },
      {
        test: /\.txt$/,
        loader: 'raw-loader',
      },
      {
        test: /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2)(\?.*)?$/,
        loader: 'file-loader',
        query: {
          name: isDebug ? '[path][name].[ext]?[hash:8]' : '[hash:8].[ext]',
        },
      },
      {
        test: /\.(mp4|webm|wav|mp3|m4a|aac|oga)(\?.*)?$/,
        loader: 'url-loader',
        query: {
          name: isDebug ? '[path][name].[ext]?[hash:8]' : '[hash:8].[ext]',
          limit: 10000,
        },
      },
      {
        test: /\.(graphql|gql)$/,
        exclude: /node_modules/,
        loader: 'graphql-tag/loader',
      },
    ],
  },

  resolve: {
    modules: [path.resolve(__dirname, '../src'), 'node_modules'],
  },

  // Don't attempt to continue if there are any errors.
  bail: !isDebug,

  cache: isDebug,

  stats: {
    colors: true,
    reasons: isDebug,
    hash: isVerbose,
    version: isVerbose,
    timings: true,
    chunks: isVerbose,
    chunkModules: isVerbose,
    cached: isVerbose,
    cachedAssets: isVerbose,
  },
};

//
// Configuration for the client-side bundle (client.js)
// -----------------------------------------------------------------------------

const clientConfig = {
  ...config,

  name: 'client',
  target: 'web',

  entry: {
    client: ['babel-polyfill', './clientLoader.js'],
  },

  output: {
    ...config.output,
    filename: isDebug ? '[name].js' : '[name].[chunkhash:8].js',
    chunkFilename: isDebug ? '[name].chunk.js' : '[name].[chunkhash:8].chunk.js',
  },

  resolve: { ...config.resolve },

  plugins: [
    // Define free variables
    // https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': true,
      __DEV__: isDebug,
    }),

    // Emit a file with assets paths
    // https://github.com/sporto/assets-webpack-plugin#options
    new AssetsPlugin({
      path: path.resolve(__dirname, '../build'),
      filename: 'assets.json',
      prettyPrint: true,
    }),

    // Move modules that occur in multiple entry chunks to a new entry chunk (the commons chunk).
    // http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: module => /node_modules/.test(module.resource),
    }),

    ...isDebug ? [] : [
      // Minimize all JavaScript output of chunks
      // https://github.com/mishoo/UglifyJS2#compressor-options
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          screw_ie8: true, // React doesn't support IE8
          warnings: isVerbose,
          unused: true,
          dead_code: true,
        },
        mangle: {
          screw_ie8: true,
        },
        output: {
          comments: false,
          screw_ie8: true,
        },
      }),
    ],

    new BundleAnalyzerPlugin({
      // See above
      analyzerMode,
      // Host that will be used in `server` mode to start HTTP server.
      analyzerHost: '127.0.0.1',
      // Port that will be used in `server` mode to start HTTP server.
      analyzerPort,
      // Path to bundle report file that will be generated in `static` mode.
      // Relative to bundles output directory.
      reportFilename: path.resolve(__dirname, '../report.html'),
      // Automatically open report in default browser
      openAnalyzer: true,
      // If `true`, Webpack Stats JSON file will be generated in bundles output directory
      generateStatsFile: !isDebug,
      // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
      // Relative to bundles output directory.
      statsFilename: path.resolve(__dirname, '../stats.json'),
      // Options for `stats.toJson()` method.
      // You can exclude sources of your modules from stats file with `source: false` option.
      // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
      statsOptions: null,
      // Log level. Can be 'info', 'warn', 'error' or 'silent'.
      logLevel: 'info',
    }),
  ],

  // Choose a developer tool to enhance debugging
  // http://webpack.github.io/docs/configuration.html#devtool
  devtool: isDebug ? 'cheap-module-source-map' : false,

  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  // https://webpack.github.io/docs/configuration.html#node
  // https://github.com/webpack/node-libs-browser/tree/master/mock
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};

//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------

const serverConfig = {
  ...config,

  name: 'server',
  target: 'node',

  entry: {
    server: ['babel-polyfill', './server.js'],
  },

  output: {
    ...config.output,
    filename: '../../server.js',
    libraryTarget: 'commonjs2',
  },

  module: {
    ...config.module,

    // Override babel-preset-env configuration for Node.js
    rules: config.module.rules.map(rule => (rule.loader !== 'babel-loader' ? rule : {
      ...rule,
      query: {
        ...rule.query,
        presets: rule.query.presets.map(preset => (preset[0] !== 'env' ? preset : ['env', {
          targets: {
            node: parseFloat(pkg.engines.node.replace(/^\D+/g, '')),
          },
          modules: false,
          useBuiltIns: false,
          debug: false,
        }])),
      },
    })),
  },

  resolve: { ...config.resolve },

  externals: [
    /^\.\/assets\.json$/,
    (context, request, callback) => {
      const isExternal =
        request.match(/^[@a-z][a-z/.\-0-9]*$/i) &&
        !request.match(/\.(css|less|scss|sss)$/i);
      callback(null, Boolean(isExternal));
    },
  ],

  plugins: [
    // Define free variables
    // https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': false,
      __DEV__: isDebug,
    }),

    // Do not create separate chunks of the server bundle
    // https://webpack.github.io/docs/list-of-plugins.html#limitchunkcountplugin
    new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),

    // Adds a banner to the top of each generated chunk
    // https://webpack.github.io/docs/list-of-plugins.html#bannerplugin
    new webpack.BannerPlugin({
      banner: 'require("source-map-support").install();',
      raw: true,
      entryOnly: false,
    }),
  ],

  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },

  devtool: isDebug ? 'cheap-module-source-map' : 'source-map',
};

export default [clientConfig, serverConfig];


问:
Are ES6 classes just syntactic sugar for the prototypal pattern in Javascript?
After playing with ES6, I've really started to like the new syntax and features available, but I do have a question about classes.

Are the new ES6 classes just syntactic sugar for the old prototypal pattern? Or is there more going on here behind the scenes? For example:

```<code>class Thing {
   //... classy stuff
  doStuff(){}
}
</code>```

vs:

```<code>var Thing = function() {
  // ... setup stuff
};

Thing.prototype.doStuff = function() {}; // etc
</code>```

答:
Yes, perhaps, but some of the syntactic sugar has teeth.

Declaring a class creates a function object that is the constructor for the class, using the code provided for constructor within the class body, and for named classes, with the same name as the class.

The class constructor function has a normal prototype object from which class instances inherit properties in normal JavaScript fashion. Instance methods defined within the class body are added to this prototype.

ES6 does not provide a means to declare class instance default property values (i.e. values which are not methods) within the class body to be stored on the prototype and inherited. To initialize instance value you can either set them as local, non inherited properties within the constructor, or manually add them to the class constructor's prototype object outside the class definition in the same fashion as for ordinary constructor functions. (I  am not arguing the merits or otherwise of setting up inherited properties for JavaScript classes).

Static methods declared within the class body are added as properties of the class constructor function. Avoid using static class method names that compete with standard function properties and methods inherited from Function.prototype such as call, apply or length.

Less sugary is that class declarations and methods are always executed in strict mode, and a feature that gets little attention: the .prototype property of class constructor functions is read only: you can't set it to some other object you've created for some special purpose.

Some interesting stuff happens when you extend a class:

the prototype object property of the extended class constructor is automatically prototyped on the prototype object of the class being extended. This is not particularly new and the  effect can be duplicated using Object.create.

the extended class constructor function (object) is automatically prototyped on the constructor function of the class being extended, not Function. While it may be possible to replicate the effect on an ordinary constructor function using Object.setPrototypeOf or even childClass.__proto__ = parentClass, this would be an extremely unusual coding practice and is often advised against in JavaScript documentation.

There are other differences such as class objects not being hoisted in the manner of named functions declared using the function keyword.

I believe it could be naive to think that Class declarations and expressions will remain unaltered in all future versions of ECMA Script and it will be interesting to see if and when developments occur. Arguably it has become a fad to associate "syntactical sugar" with classes introduced in ES6 (ECMA-262 standard version 6) but personally I try to avoid repeating it.

ContentLicense: CC BY-SA 4.0

Body:
After playing with ES6, I've really started to like the new syntax and features available, but I do have a question about classes.

Are the new ES6 classes just syntactic sugar for the old prototypal pattern? Or is there more going on here behind the scenes? For example:

class Thing {
   //... classy stuff
  doStuff(){}
}

vs:

var Thing = function() {
  // ... setup stuff
};

Thing.prototype.doStuff = function() {}; // etc


问:
How to send push notification on button click
I've create push notification for my android app, it's work when I try to send it from firebase console. Now what I want is make a push notification when user click on register then show the notification for other users.

I've search in google but didn't find one of the example. The goals is to notif other user that there are new user register in my app.

Thanks for help

```<code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMessagingService";
    public static final int ID_SMALL_NOTIFICATION = 235;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        // TODO(developer): Handle FCM messages here.

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification("Hi ini isinya");
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG,"Message Notification Title" + remoteMessage.getNotification().getTitle());
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, ID_SMALL_NOTIFICATION, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = "fcm_default_channel";
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.icon)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(ID_SMALL_NOTIFICATION, notificationBuilder.build());
    }

}
</code>```

答:
I didn't get what you mean but you can use Volly Json object request

First you need to copy your server key from Firebase Console, open up Firebase Console and choose your project

Second add Volley dependency in your project

compile 'com.mcxiaoke.volley:library:1.0.19'

then you can add this code to push

```<code>private void sendFCMPush() {

            String SERVER_KEY = YOUR_SERVER_KEY;
            String msg = "this is test message";
            String title = "my title";
            String token = FCM_TOKEN;

            JSONObject obj = null;
        JSONObject objData = null;
        JSONObject dataobjData = null;

        try {
            obj = new JSONObject();
            objData = new JSONObject();

            objData.put("body", msg);
            objData.put("title", title);
            objData.put("sound", "default");
            objData.put("icon", "icon_name"); //   icon_name
            objData.put("tag", token);
            objData.put("priority", "high");

            dataobjData = new JSONObject();
            dataobjData.put("text", msg);
            dataobjData.put("title", title);

            obj.put("to", token);
            //obj.put("priority", "high");

            obj.put("notification", objData);
            obj.put("data", dataobjData);
            Log.e("return here>>", obj.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

            JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, Constants.FCM_PUSH_URL, obj,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.e("True", response + "");
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e("False", error + "");
                        }
                    }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("Authorization", "key=" + SERVER_KEY);
                    params.put("Content-Type", "application/json");
                    return params;
                }
            };
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            int socketTimeout = 1000 * 60;// 60 seconds
            RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            jsObjRequest.setRetryPolicy(policy);
            requestQueue.add(jsObjRequest);
}
</code>```

Hope this help

Body:
I've create push notification for my android app, it's work when I try to send it from firebase console. Now what I want is make a push notification when user click on register then show the notification for other users.

I've search in google but didn't find one of the example. The goals is to notif other user that there are new user register in my app.

Thanks for help

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMessagingService";
    public static final int ID_SMALL_NOTIFICATION = 235;
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        // TODO(developer): Handle FCM messages here.

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification("Hi ini isinya");
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG,"Message Notification Title" + remoteMessage.getNotification().getTitle());
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, ID_SMALL_NOTIFICATION, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = "fcm_default_channel";
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.icon)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(ID_SMALL_NOTIFICATION, notificationBuilder.build());
    }

}

Body:
I didn't get what you mean but you can use Volly Json object request

First you need to copy your server key from Firebase Console, open up Firebase Console and choose your project

Second add Volley dependency in your project

compile 'com.mcxiaoke.volley:library:1.0.19'

then you can add this code to push

private void sendFCMPush() {

            String SERVER_KEY = YOUR_SERVER_KEY;
            String msg = "this is test message";
            String title = "my title";
            String token = FCM_TOKEN;

            JSONObject obj = null;
        JSONObject objData = null;
        JSONObject dataobjData = null;

        try {
            obj = new JSONObject();
            objData = new JSONObject();

            objData.put("body", msg);
            objData.put("title", title);
            objData.put("sound", "default");
            objData.put("icon", "icon_name"); //   icon_name
            objData.put("tag", token);
            objData.put("priority", "high");

            dataobjData = new JSONObject();
            dataobjData.put("text", msg);
            dataobjData.put("title", title);

            obj.put("to", token);
            //obj.put("priority", "high");

            obj.put("notification", objData);
            obj.put("data", dataobjData);
            Log.e("return here>>", obj.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

            JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, Constants.FCM_PUSH_URL, obj,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.e("True", response + "");
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e("False", error + "");
                        }
                    }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("Authorization", "key=" + SERVER_KEY);
                    params.put("Content-Type", "application/json");
                    return params;
                }
            };
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            int socketTimeout = 1000 * 60;// 60 seconds
            RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            jsObjRequest.setRetryPolicy(policy);
            requestQueue.add(jsObjRequest);
}

Hope this help


问:
Wrapper around Polly library so that implementation can stay at a single place
I have gone through the documentation and examples of Polly library, and it's really awesome and simple to use !!

In my case, I want to classify all the exceptions into 3 types: temporary, permanent and log. Now, I want to have a single piece of code which will be responsible to handle errors which are temporary in nature by doing wait and retry using Polly library.

```<code>  WaitAndRetryAsync(new[]{
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(2),
                    TimeSpan.FromSeconds(5)
                  })
</code>```

Same way, if something is permanent in nature (should be able to know it's type based on the exception we are trying to handle example: timeout can be interim but if database cred are not correct then it's permanent) then we can send email to the support staff.

Now, the problem starts here that, how I can wrap it using an interface or Abstract class so that my all the derived class can pass on an exception along with method name, which can be passed on to my new framework and it will do the needful.

Any pointers will be of great help !

答:
You could create a class that accepts a Func or Action to the code you want Polly to call.

Something like this helper method:

```<code>public class RetryWrapper
    {
        public static TOutput Execute<TInput, TOutput>(Func<TInput, TOutput> func, TInput input)
        {
            RetryPolicy retryPolicy = Policy.Handle<TimeoutException>()
                .Or<OtherException>()
                .WaitAndRetry(3, x => new TimeSpan(0, 0, 2));

            return retryPolicy.Execute(() => func(input));
        }
    }
</code>```

Then you can call it

```<code>var result = RetryWrapper.Execute<string, bool>(x => MethodToCall(x), "input")
</code>```

Body:
I have gone through the documentation and examples of Polly library, and it's really awesome and simple to use !!

In my case, I want to classify all the exceptions into 3 types: temporary, permanent and log. Now, I want to have a single piece of code which will be responsible to handle errors which are temporary in nature by doing wait and retry using Polly library.

  WaitAndRetryAsync(new[]{
                    TimeSpan.FromSeconds(1),
                    TimeSpan.FromSeconds(2),
                    TimeSpan.FromSeconds(5)
                  })

Same way, if something is permanent in nature (should be able to know it's type based on the exception we are trying to handle example: timeout can be interim but if database cred are not correct then it's permanent) then we can send email to the support staff.

Now, the problem starts here that, how I can wrap it using an interface or Abstract class so that my all the derived class can pass on an exception along with method name, which can be passed on to my new framework and it will do the needful.

Any pointers will be of great help !

Body:
You could create a class that accepts a Func or Action to the code you want Polly to call.

Something like this helper method:

public class RetryWrapper
    {
        public static TOutput Execute<TInput, TOutput>(Func<TInput, TOutput> func, TInput input)
        {
            RetryPolicy retryPolicy = Policy.Handle<TimeoutException>()
                .Or<OtherException>()
                .WaitAndRetry(3, x => new TimeSpan(0, 0, 2));

            return retryPolicy.Execute(() => func(input));
        }
    }

Then you can call it

var result = RetryWrapper.Execute<string, bool>(x => MethodToCall(x), "input")


问:
How to show disable HTML select option in by default?
I am new to HTML and PHP and want to achieve a drop-down menu from the mysql table and hard-coded too. I have multiple select in my page, One of them is

```<code><select name="tagging">
    <option value="">Choose Tagging</option>
    <option value="Option A">Option A</option>
    <option value="Option B">Option B</option>
    <option value="Option C">Option C</option>
</select>
</code>```

Problem is now that user can also select "Choose Tagging" as his tagging but i only want to provide him to chose from available three. I used disable as

```<code><select name="tagging">
    <option value="" disabled="disabled">Choose Tagging</option>
    <option value="Option A">Option A</option>
    <option value="Option B">Option B</option>
    <option value="Option C">Option C</option>
</select>
</code>```

But now "Option A" became the default one. So i want to set "Choose Tagging" as by default and also want to disable it from selection. Is it a way to do this. Same thing need to be done with other select which will fetch data from Mysql. Any suggestion will be appreciable.

答:
```<code> selected disabled="true"
</code>```

Use this. It will work in new browsers

Body:
I am new to HTML and PHP and want to achieve a drop-down menu from the mysql table and hard-coded too. I have multiple select in my page, One of them is

<select name="tagging">
    <option value="">Choose Tagging</option>
    <option value="Option A">Option A</option>
    <option value="Option B">Option B</option>
    <option value="Option C">Option C</option>
</select>

Problem is now that user can also select "Choose Tagging" as his tagging but i only want to provide him to chose from available three. I used disable as

<select name="tagging">
    <option value="" disabled="disabled">Choose Tagging</option>
    <option value="Option A">Option A</option>
    <option value="Option B">Option B</option>
    <option value="Option C">Option C</option>
</select>

But now "Option A" became the default one. So i want to set "Choose Tagging" as by default and also want to disable it from selection. Is it a way to do this. Same thing need to be done with other select which will fetch data from Mysql. Any suggestion will be appreciable.

Body:
 selected disabled="true"

Use this. It will work in new browsers


问:
Gulp group media error "must start with number, buffer, array or string"
I use

```<code>var cmq = require('gulp-combine-media-queries')

gulp.task('cmq', function () {
gulp.src('css/style.css')
.pipe(cmq({
  log: true
}))
.pipe(gulp.dest('dist'));
});
</code>```

And this error is output after gulp command:

```<code>File css/style.css found.
buffer.js:169
throw new TypeError('must start with number, buffer, array or
string');
  ^

TypeError: must start with number, buffer, array or string
at fromObject (buffer.js:169:9)
at new Buffer (buffer.js:62:10)
at Transform.transform [as _transform] (/home/user/node_modules/gulp-
combine-media-queries/index.js:152:21)
at Transform._read (/home/user/node_modules/gulp-combine-media-
queries/node_modules/readable-stream/lib/_stream_transform.js:184:10)
at Transform._write (/home/user/node_modules/gulp-combine-media-
queries/node_modules/readable-stream/lib/_stream_transform.js:172:12)
at doWrite (/home/user/node_modules/gulp-combine-media-
queries/node_modules/readable-stream/lib/_stream_writable.js:237:10)
at writeOrBuffer (/home/user/node_modules/gulp-combine-media-
queries/node_modules/readable-stream/lib/_stream_writable.js:227:5)
at Transform.Writable.write (/home/user/node_modules/gulp-combine-
media-queries/node_modules/readable-
stream/lib/_stream_writable.js:194:11)
at write (/home/user/node_modules/vinyl-fs/node_modules/readable-
stream/lib/_stream_readable.js:623:24)
at flow (/home/user/node_modules/vinyl-fs/node_modules/readable-
stream/lib/_stream_readable.js:632:7)
at DestroyableTransform.pipeOnReadable (/home/user/node_modules/vinyl-
fs/node_modules/readable-stream/lib/_stream_readable.js:664:5)
at emitNone (events.js:67:13)
at DestroyableTransform.emit (events.js:166:7)
at emitReadable_ (/home/user/node_modules/vinyl-
fs/node_modules/readable-stream/lib/_stream_readable.js:448:10)
at emitReadable (/home/user/node_modules/vinyl-
fs/node_modules/readable-stream/lib/_stream_readable.js:444:5)
at readableAddChunk (/home/user/node_modules/vinyl-
fs/node_modules/readable-stream/lib/_stream_readable.js:187:9)
</code>```

Node - 4.2.6, Gulp 3.9.1, npm - 3.5.2
I also used another npms for grouping media and have the same errors. I read many articles with the same problems, but none has helped

答:
looking at media-query code (https://github.com/konitter/gulp-combine-media-queries/blob/master/index.js)

I could see that your file "css/style.css" is not accessible by gulp hence the error.

Please recheck the path and try again

Body:
I use

var cmq = require('gulp-combine-media-queries')

gulp.task('cmq', function () {
gulp.src('css/style.css')
.pipe(cmq({
  log: true
}))
.pipe(gulp.dest('dist'));
});

And this error is output after gulp command:

File css/style.css found.
buffer.js:169
throw new TypeError('must start with number, buffer, array or
string');
  ^

TypeError: must start with number, buffer, array or string
at fromObject (buffer.js:169:9)
at new Buffer (buffer.js:62:10)
at Transform.transform [as _transform] (/home/user/node_modules/gulp-
combine-media-queries/index.js:152:21)
at Transform._read (/home/user/node_modules/gulp-combine-media-
queries/node_modules/readable-stream/lib/_stream_transform.js:184:10)
at Transform._write (/home/user/node_modules/gulp-combine-media-
queries/node_modules/readable-stream/lib/_stream_transform.js:172:12)
at doWrite (/home/user/node_modules/gulp-combine-media-
queries/node_modules/readable-stream/lib/_stream_writable.js:237:10)
at writeOrBuffer (/home/user/node_modules/gulp-combine-media-
queries/node_modules/readable-stream/lib/_stream_writable.js:227:5)
at Transform.Writable.write (/home/user/node_modules/gulp-combine-
media-queries/node_modules/readable-
stream/lib/_stream_writable.js:194:11)
at write (/home/user/node_modules/vinyl-fs/node_modules/readable-
stream/lib/_stream_readable.js:623:24)
at flow (/home/user/node_modules/vinyl-fs/node_modules/readable-
stream/lib/_stream_readable.js:632:7)
at DestroyableTransform.pipeOnReadable (/home/user/node_modules/vinyl-
fs/node_modules/readable-stream/lib/_stream_readable.js:664:5)
at emitNone (events.js:67:13)
at DestroyableTransform.emit (events.js:166:7)
at emitReadable_ (/home/user/node_modules/vinyl-
fs/node_modules/readable-stream/lib/_stream_readable.js:448:10)
at emitReadable (/home/user/node_modules/vinyl-
fs/node_modules/readable-stream/lib/_stream_readable.js:444:5)
at readableAddChunk (/home/user/node_modules/vinyl-
fs/node_modules/readable-stream/lib/_stream_readable.js:187:9)

Node - 4.2.6, Gulp 3.9.1, npm - 3.5.2
I also used another npms for grouping media and have the same errors. I read many articles with the same problems, but none has helped


问:
Multiple usb cameras on Raspberry Pi using OpenCV
I would like to connect 2 usb webcams to a RaspberryPI and be able to get at least 1920 x 1080 frames at 10 fps using OpenCV.  Has anyone done this and knows if this is possible?  I am worried that the PI has only 1 usb bus?? (usb2) and might get a usb bandwidth problem.

Currently I am using an Odroid and it has a usb2 and usb3 bus so I can connect 1 camera to each without any problemo..

答:
What i have found in the past with this is no matter what you select using OpenCV for bandwidth options the cameras try to take up as much bandwidth as they want.

This has led to multiple cameras on a single USB port being a no-no.

That being said, this will depend on your camera and is very likely worth testing. I regularly use HD-3000 Microsoft cameras and they do not like working on the same port, even on my beefy i7 laptop. This is because the limitation is in the USB Host Bandwidth and not processing power etc.

I have had a similar development process to you inthe past though, and selected an Odroid XU4 because it had the multiple USB hosts for the cameras. It also means you have a metric tonne more processing power available and more importantly can buy and use the on-board chip if you want to create a custom electronics design.


问:
Execution failed with app:processDebugGoogleServices'

I have been trying to add retrieve some of my images from Firebase firestore. After I added the dependencies I have the following error

"Error:Execution failed for task ':app:processDebugGoogleServices'. >
  Please fix the version conflict either by updating the version of the
  google-services plugin (information about the latest version is
  available at
  https://bintray.com/android/android-tools/com.google.gms.google-services/)
  or updating the version of com.google.android.gms to 10.0.1."

This is my module app gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"
    defaultConfig {
        applicationId "com.example.rimapps.charpapers"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions{
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'

    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:27.+'
    compile 'com.android.support:recyclerview-v7:27.+'
    compile 'com.android.support:cardview-v7:27.+'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.google.firebase:firebase-firestore:11.4.2'
    compile 'com.google.firebase:firebase-appindexing:10.0.1'

}
apply plugin: 'com.google.gms.google-services'```
</div>
</div>

This is my project gradle </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        //classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}</code>```

Please help to solve this problem I have tried all I could.

答:
In order to solve this, you need to use the same version for dependencies like this:

```<code>compile 'com.google.firebase:firebase-messaging:11.4.2'
compile 'com.google.firebase:firebase-firestore:11.4.2'
compile 'com.google.firebase:firebase-appindexing:11.4.2'
</code>```

As you probably see, now all dependencies have 11.4.2 version.

Body:
I have been trying to add retrieve some of my images from Firebase firestore. After I added the dependencies I have the following error

"Error:Execution failed for task ':app:processDebugGoogleServices'. >
  Please fix the version conflict either by updating the version of the
  google-services plugin (information about the latest version is
  available at
  https://bintray.com/android/android-tools/com.google.gms.google-services/)
  or updating the version of com.google.android.gms to 10.0.1."

This is my module app gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.1"
    defaultConfig {
        applicationId "com.example.rimapps.charpapers"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions{
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'

    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:27.+'
    compile 'com.android.support:recyclerview-v7:27.+'
    compile 'com.android.support:cardview-v7:27.+'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    testCompile 'junit:junit:4.12'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.google.firebase:firebase-firestore:11.4.2'
    compile 'com.google.firebase:firebase-appindexing:10.0.1'

}
apply plugin: 'com.google.gms.google-services'

This is my project gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        //classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.1'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://maven.google.com" }

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Please help to solve this problem I have tried all I could.

Body:
In order to solve this, you need to use the same version for dependencies like this:

compile 'com.google.firebase:firebase-messaging:11.4.2'
compile 'com.google.firebase:firebase-firestore:11.4.2'
compile 'com.google.firebase:firebase-appindexing:11.4.2'

As you probably see, now all dependencies have 11.4.2 version.


问:
wpf application with embedded database
I am a .net developer and I am looking forward to learn wpf. I don't want to use services to connect with a database. I want to use an embedded database.

Could anyone help me by providing me a tutorial or just to inform me of how could I start with my application as it concerned the database?

Thanks

答: Look into Sql Server Compact.</p>

ContentLicense: CC BY-SA 2.5

Title: wpf application with embedded database

Body: Look into Sql Server Compact.


问:
Getting a list of results by using CRUD Repository
I am new to using CRUD Repository.

I have a database table with three columns:

course_id, name, course

I want to get a list of course_id give name, example,

```<code>SELECT id FROM table WHERE name='charmaine';
</code>```

However, I do not want to do it with query but using crud repository.

There is an error shown in my controller.
May I know there is this error?

My controller

```<code>@GetMapping(value = "getting/{name}")
    //@ResponseBody
     public String getting(@PathVariable("name") String name) {
        List<CourseMaster> getIds =  CourseService.findIdByName(Name);   —> error icon here
        return getIds;  —> error icon here
     }
</code>```

Service

```<code>public List<CourseMaster> findIdByName(String Name) {
    return CourseMasterRepo.findByName(Name);
}
</code>```

Repository

```<code>public interface CourseMasterRepo extends CrudRepository<CourseMaster, Long> {
    List<CourseMaster> findByName(String Name);
}
</code>```

答:
if your code is done in java spring you must use hql language in hibernate, that is a interface of sql query.

hql query that use lambda expression is very simple and useful.

For example,

```<code>String hql = "FROM Employee E WHERE E.id = 10";
Query query = session.createQuery(hql);
List results = query.list();
</code>```

Body:
I am new to using CRUD Repository.

I have a database table with three columns:

course_id, name, course

I want to get a list of course_id give name, example,

SELECT id FROM table WHERE name='charmaine';

However, I do not want to do it with query but using crud repository.

There is an error shown in my controller.
May I know there is this error?

My controller

@GetMapping(value = "getting/{name}")
    //@ResponseBody
     public String getting(@PathVariable("name") String name) {
        List<CourseMaster> getIds =  CourseService.findIdByName(Name);   —> error icon here
        return getIds;  —> error icon here
     }

Service

public List<CourseMaster> findIdByName(String Name) {
    return CourseMasterRepo.findByName(Name);
}

Repository

public interface CourseMasterRepo extends CrudRepository<CourseMaster, Long> {
    List<CourseMaster> findByName(String Name);
}

Body:
if your code is done in java spring you must use hql language in hibernate, that is a interface of sql query.

hql query that use lambda expression is very simple and useful.

For example,

String hql = "FROM Employee E WHERE E.id = 10";
Query query = session.createQuery(hql);
List results = query.list();


问:
Best practice for adding to a pull request on your repository?

I have a repository that someone has submitted pull request to, where forked my repo quite a few commits ago. I've cloned his pull request and was playing around with it and fixed some errors in his commit. What is the best way to add my own commits on top of his? I don't want to merge his pull request without applying the fixes first.

My immediate thoughts are:

clone his fork, commit locally and submit a PR to his fork. He would then merge my changes into his pull request which I would then merge.

create a new branch in my repo, make it point to the commit he forked from, merge his PR in this new branch, add my commits until I'm satisfied and merge new branch back to master.

So far I have tried the second one, but when I git pull my network graph (viewed on github) goes from

```<code>owner        --.--.--.--.--.--.| master
               |
PR submitter   .--.| PR commit
</code>```

to

```<code>owner        --.--.--.--.--.--.|master
               |
               .--.| new-branch
</code>```

and it seems like he loses authorship. I don't his contribution to be erased if I later merge new-branch into master. What is the best option? are there others I haven't thought about?

答:
Your second approach is perfectly fine. Add your commits, then merge to master.

Authorship is not shown in the github network graph like this. When you hover over commits, you see owner.

Body:
I have a repository that someone has submitted pull request to, where forked my repo quite a few commits ago. I've cloned his pull request and was playing around with it and fixed some errors in his commit. What is the best way to add my own commits on top of his? I don't want to merge his pull request without applying the fixes first.

My immediate thoughts are:

clone his fork, commit locally and submit a PR to his fork. He would then merge my changes into his pull request which I would then merge.

create a new branch in my repo, make it point to the commit he forked from, merge his PR in this new branch, add my commits until I'm satisfied and merge new branch back to master.

So far I have tried the second one, but when I git pull my network graph (viewed on github) goes from

owner        --.--.--.--.--.--.| master
               |
PR submitter   .--.| PR commit

to

owner        --.--.--.--.--.--.|master
               |
               .--.| new-branch

and it seems like he loses authorship. I don't his contribution to be erased if I later merge new-branch into master. What is the best option? are there others I haven't thought about?


问:
checking MongoDB document with unknown key (which is not there in document)

I would like to get find a key which is not there in MongoDB document.
Please find the following document.

```<code>    {
"_id" : ObjectId("523b6e61fb408eea0eec2648"),
"userid" : "abby",
"score" : 82
}
</code>```

I have  a requirement that I need to query Mongo DB with a key which is not there in any document . say  key =name.
my db collection size is 10 GB.
Now, I want to check the collection that the key = name is there or not ?

```<code>db.getCollection('score').find({"name":{$exists:true}})
</code>```

the above query is taking more than 10 sec to find that weather the key name is there in the document or not.
my question is that is there any way to get the response immediately if the specified key is not here in that document.

my question is different because when I check the link provided , I
  came to know that they are checking the existing key in a document.
  but in my case checking a key which is not there in any document.

答:
I would simply create an index on that key:

```<code>db.score.createIndex({"name": 1})
</code>```

This should speed up queries in general.

Edit 1:

My initial assumption is wrong: exists query are not speeded up by indices. More about this topic on: Improve querying fields exist in MongoDB

Body:
I would like to get find a key which is not there in MongoDB document.
Please find the following document.

    {
"_id" : ObjectId("523b6e61fb408eea0eec2648"),
"userid" : "abby",
"score" : 82
}

I have  a requirement that I need to query Mongo DB with a key which is not there in any document . say  key =name.
my db collection size is 10 GB.
Now, I want to check the collection that the key = name is there or not ?

db.getCollection('score').find({"name":{$exists:true}})

the above query is taking more than 10 sec to find that weather the key name is there in the document or not.
my question is that is there any way to get the response immediately if the specified key is not here in that document.

my question is different because when I check the link provided , I
  came to know that they are checking the existing key in a document.
  but in my case checking a key which is not there in any document.

Body:
I would simply create an index on that key:

db.score.createIndex({"name": 1})

This should speed up queries in general.

Edit 1:

My initial assumption is wrong: exists query are not speeded up by indices. More about this topic on: Improve querying fields exist in MongoDB