问:
React with Redux: Module build failed: SyntaxError: Unexpected token <
I'm trying to follow a simple tutorial found on Udemy. For some reason the example code is working (probably because the tutorial is slightly out of date). I've done some googling about

Here is the output when trying to start the server.

```<code>ERROR in ./index.js
Module build failed: SyntaxError: Unexpected token (9:4)

   7 | function render(){
   8 |   ReactDOM.render(
>  9 |     <Examples/>,
     |     ^
  10 |     document.getElementById('root')
  11 |   )
  12 | }

 @ multi main
</code>```

My package.json:

```<code>{
  "name": "redux",
  "version": "3.6.0",
  "description": "Predictable state container for JavaScript apps",
  "browser": "dist/redux.js",
  "main": "lib/index.js",
  "module": "es/index.js",
  "jsnext:main": "es/index.js",
  "typings": "./index.d.ts",
  "files": [
    "dist",
    "lib",
    "es",
    "src",
    "index.d.ts"
  ],
  "scripts": {
    "clean": "rimraf lib dist es coverage",
    "lint": "eslint src test build",
    "test": "cross-env BABEL_ENV=commonjs jest",
    "test:watch": "yarn test -- --watch",
    "test:cov": "yarn test -- --coverage",
    "build:commonjs": "cross-env BABEL_ENV=commonjs babel src --out-dir lib",
    "build:es": "cross-env BABEL_ENV=es babel src --out-dir es",
    "build:umd": "cross-env BABEL_ENV=es NODE_ENV=development rollup -c -i src/index.js -o dist/redux.js",
    "build:umd:min": "cross-env BABEL_ENV=es NODE_ENV=production rollup -c -i src/index.js -o dist/redux.min.js",
    "build": "yarn run build:commonjs && yarn run build:es && yarn run build:umd && yarn run build:umd:min",
    "prepublish": "yarn run clean && yarn run lint && yarn test && yarn run build && check-es3-syntax lib/ dist/ --kill --print",
    "examples:build": "babel-node examples/buildAll.js",
    "examples:lint": "eslint examples",
    "examples:test": "CI=true babel-node examples/testAll.js",
    "docs:clean": "rimraf _book",
    "docs:prepare": "gitbook install",
    "docs:build": "yarn run docs:prepare && gitbook build -g reactjs/redux && cp logo/apple-touch-icon.png _book/gitbook/images/apple-touch-icon-precomposed-152.png && cp logo/favicon.ico _book/gitbook/images",
    "docs:watch": "yarn run docs:prepare && gitbook serve",
    "docs:publish": "yarn run docs:clean && yarn run docs:build && cp CNAME _book && cd _book && git init && git commit --allow-empty -m 'update book' && git checkout -b gh-pages && touch .nojekyll && git add . && git commit -am 'update book' && git push git@github.com:reactjs/redux gh-pages --force"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/reactjs/redux.git"
  },
  "keywords": [
    "redux",
    "reducer",
    "state",
    "predictable",
    "functional",
    "immutable",
    "hot",
    "live",
    "replay",
    "flux",
    "elm"
  ],
  "authors": [
    "Dan Abramov <dan.abramov@me.com> (https://github.com/gaearon)",
    "Andrew Clark <acdlite@me.com> (https://github.com/acdlite)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/reactjs/redux/issues"
  },
  "homepage": "http://redux.js.org",
  "dependencies": {
    "lodash": "^4.2.1",
    "lodash-es": "^4.2.1",
    "loose-envify": "^1.1.0",
    "symbol-observable": "^1.0.3"
  },
  "devDependencies": {
    "babel-cli": "^6.3.15",
    "babel-core": "^6.3.15",
    "babel-eslint": "^7.0.0",
    "babel-jest": "^18.0.0",
    "babel-plugin-check-es2015-constants": "^6.3.13",
    "babel-plugin-transform-es2015-arrow-functions": "^6.3.13",
    "babel-plugin-transform-es2015-block-scoped-functions": "^6.3.13",
    "babel-plugin-transform-es2015-block-scoping": "^6.3.13",
    "babel-plugin-transform-es2015-classes": "^6.3.13",
    "babel-plugin-transform-es2015-computed-properties": "^6.3.13",
    "babel-plugin-transform-es2015-destructuring": "^6.3.13",
    "babel-plugin-transform-es2015-for-of": "^6.3.13",
    "babel-plugin-transform-es2015-function-name": "^6.3.13",
    "babel-plugin-transform-es2015-literals": "^6.3.13",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.3.13",
    "babel-plugin-transform-es2015-object-super": "^6.3.13",
    "babel-plugin-transform-es2015-parameters": "^6.3.13",
    "babel-plugin-transform-es2015-shorthand-properties": "^6.3.13",
    "babel-plugin-transform-es2015-spread": "^6.3.13",
    "babel-plugin-transform-es2015-sticky-regex": "^6.3.13",
    "babel-plugin-transform-es2015-template-literals": "^6.3.13",
    "babel-plugin-transform-es2015-unicode-regex": "^6.3.13",
    "babel-plugin-transform-es3-member-expression-literals": "^6.5.0",
    "babel-plugin-transform-es3-property-literals": "^6.5.0",
    "babel-plugin-transform-object-rest-spread": "^6.3.13",
    "babel-register": "^6.3.13",
    "check-es3-syntax-cli": "^0.1.1",
    "cross-env": "^3.1.4",
    "eslint": "^3.8.1",
    "eslint-config-react-app": "^0.5.0",
    "eslint-plugin-flowtype": "^2.29.2",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "2.2.3",
    "eslint-plugin-react": "^6.8.0",
    "gitbook-cli": "^2.3.0",
    "glob": "^7.1.1",
    "jest": "^18.0.0",
    "rimraf": "^2.3.4",
    "rollup": "^0.41.4",
    "rollup-plugin-babel": "^2.7.1",
    "rollup-plugin-node-resolve": "^2.0.0",
    "rollup-plugin-replace": "^1.1.1",
    "rollup-plugin-uglify": "^1.0.1",
    "rxjs": "^5.0.0-beta.6",
    "typescript": "^1.8.0",
    "typescript-definition-tester": "0.0.4"
  },
  "npmName": "redux",
  "npmFileMap": [
    {
      "basePath": "/dist/",
      "files": [
        "*.js"
      ]
    }
  ],
  "browserify": {
    "transform": [
      "loose-envify"
    ]
  },
  "jest": {
    "testRegex": "(/test/.*\\.spec.js)$"
  }
}
</code>```

Here is my webpack.config.js file:

```<code>var path = require('path')
var webpack = require('webpack')

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: [ 'babel' ],
        exclude: /node_modules/,
        include: __dirname
      }
    ]
  }
}
</code>```

I did follow this answer in attempt to fix it: babel-loader jsx SyntaxError: Unexpected token

I did npm install babel-preset-react and added the query to my webpack.config file to look like:

```<code>module: {
  loaders: [
    {
      test: /\.js$/,
      loaders: [ 'babel' ],
      exclude: /node_modules/,
      include: __dirname,
      query:
          {
              presets:['react']
          }
    }
  ]
}
</code>```

}

However, this was the error I got after doing that:

```<code>$ npm start                                                                                ‹ruby-2.3.0›

> redux-counter-example@0.0.0 start /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux
> node server.js

==>   Listening on port 3000. Open up http://localhost:3000/ in your browser.
/Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/webpack-core/lib/LoadersList.js:54
    if(!element.loader || element.loader.indexOf("!") >= 0) throw new Error("Cannot define 'query' and multiple loaders in loaders list");
                                                            ^

Error: Cannot define 'query' and multiple loaders in loaders list
    at getLoadersFromObject (/Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/webpack-core/lib/LoadersList.js:54:65)
    at LoadersList.<anonymous> (/Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/webpack-core/lib/LoadersList.js:78:12)
    at Array.map (native)
    at LoadersList.match (/Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/webpack-core/lib/LoadersList.js:70:19)
    at /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/webpack/lib/NormalModuleFactory.js:111:68
    at /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/async/lib/async.js:726:13
    at /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/async/lib/async.js:52:16
    at done (/Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/async/lib/async.js:246:17)
    at /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/async/lib/async.js:44:16
    at /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/async/lib/async.js:723:17

npm ERR! Darwin 16.4.0
npm ERR! argv "/usr/local/Cellar/node5/5.12.0/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v5.12.0
npm ERR! npm  v4.1.2
npm ERR! code ELIFECYCLE
npm ERR! redux-counter-example@0.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the redux-counter-example@0.0.0 start script 'node server.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the redux-counter-example package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs redux-counter-example
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls redux-counter-example
npm ERR! There is likely additional logging output above.
</code>```

Any help would be greatly appreciated

答:
Its evident from the error that you cannot define multiple loaders inside loaders, since you have declared loaders  inside loaders whereas it should be loader and assigned a single value. Also install and use babel-presets for react, es2015 , stage-0 if you use ES6 like

```<code>module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
             presets: ['react', 'es2015', 'stage-0']
        },
        include: __dirname
      }
    ]
  }
</code>```

Install the presets with

```<code>npm install -S babel-preset-react babel-preset-es2015 babel-preset-stage-0
</code>```

Body:
I'm trying to follow a simple tutorial found on Udemy. For some reason the example code is working (probably because the tutorial is slightly out of date). I've done some googling about

Here is the output when trying to start the server.

ERROR in ./index.js
Module build failed: SyntaxError: Unexpected token (9:4)

   7 | function render(){
   8 |   ReactDOM.render(
>  9 |     <Examples/>,
     |     ^
  10 |     document.getElementById('root')
  11 |   )
  12 | }

 @ multi main

My package.json:

{
  "name": "redux",
  "version": "3.6.0",
  "description": "Predictable state container for JavaScript apps",
  "browser": "dist/redux.js",
  "main": "lib/index.js",
  "module": "es/index.js",
  "jsnext:main": "es/index.js",
  "typings": "./index.d.ts",
  "files": [
    "dist",
    "lib",
    "es",
    "src",
    "index.d.ts"
  ],
  "scripts": {
    "clean": "rimraf lib dist es coverage",
    "lint": "eslint src test build",
    "test": "cross-env BABEL_ENV=commonjs jest",
    "test:watch": "yarn test -- --watch",
    "test:cov": "yarn test -- --coverage",
    "build:commonjs": "cross-env BABEL_ENV=commonjs babel src --out-dir lib",
    "build:es": "cross-env BABEL_ENV=es babel src --out-dir es",
    "build:umd": "cross-env BABEL_ENV=es NODE_ENV=development rollup -c -i src/index.js -o dist/redux.js",
    "build:umd:min": "cross-env BABEL_ENV=es NODE_ENV=production rollup -c -i src/index.js -o dist/redux.min.js",
    "build": "yarn run build:commonjs && yarn run build:es && yarn run build:umd && yarn run build:umd:min",
    "prepublish": "yarn run clean && yarn run lint && yarn test && yarn run build && check-es3-syntax lib/ dist/ --kill --print",
    "examples:build": "babel-node examples/buildAll.js",
    "examples:lint": "eslint examples",
    "examples:test": "CI=true babel-node examples/testAll.js",
    "docs:clean": "rimraf _book",
    "docs:prepare": "gitbook install",
    "docs:build": "yarn run docs:prepare && gitbook build -g reactjs/redux && cp logo/apple-touch-icon.png _book/gitbook/images/apple-touch-icon-precomposed-152.png && cp logo/favicon.ico _book/gitbook/images",
    "docs:watch": "yarn run docs:prepare && gitbook serve",
    "docs:publish": "yarn run docs:clean && yarn run docs:build && cp CNAME _book && cd _book && git init && git commit --allow-empty -m 'update book' && git checkout -b gh-pages && touch .nojekyll && git add . && git commit -am 'update book' && git push git@github.com:reactjs/redux gh-pages --force"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/reactjs/redux.git"
  },
  "keywords": [
    "redux",
    "reducer",
    "state",
    "predictable",
    "functional",
    "immutable",
    "hot",
    "live",
    "replay",
    "flux",
    "elm"
  ],
  "authors": [
    "Dan Abramov <dan.abramov@me.com> (https://github.com/gaearon)",
    "Andrew Clark <acdlite@me.com> (https://github.com/acdlite)"
  ],
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/reactjs/redux/issues"
  },
  "homepage": "http://redux.js.org",
  "dependencies": {
    "lodash": "^4.2.1",
    "lodash-es": "^4.2.1",
    "loose-envify": "^1.1.0",
    "symbol-observable": "^1.0.3"
  },
  "devDependencies": {
    "babel-cli": "^6.3.15",
    "babel-core": "^6.3.15",
    "babel-eslint": "^7.0.0",
    "babel-jest": "^18.0.0",
    "babel-plugin-check-es2015-constants": "^6.3.13",
    "babel-plugin-transform-es2015-arrow-functions": "^6.3.13",
    "babel-plugin-transform-es2015-block-scoped-functions": "^6.3.13",
    "babel-plugin-transform-es2015-block-scoping": "^6.3.13",
    "babel-plugin-transform-es2015-classes": "^6.3.13",
    "babel-plugin-transform-es2015-computed-properties": "^6.3.13",
    "babel-plugin-transform-es2015-destructuring": "^6.3.13",
    "babel-plugin-transform-es2015-for-of": "^6.3.13",
    "babel-plugin-transform-es2015-function-name": "^6.3.13",
    "babel-plugin-transform-es2015-literals": "^6.3.13",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.3.13",
    "babel-plugin-transform-es2015-object-super": "^6.3.13",
    "babel-plugin-transform-es2015-parameters": "^6.3.13",
    "babel-plugin-transform-es2015-shorthand-properties": "^6.3.13",
    "babel-plugin-transform-es2015-spread": "^6.3.13",
    "babel-plugin-transform-es2015-sticky-regex": "^6.3.13",
    "babel-plugin-transform-es2015-template-literals": "^6.3.13",
    "babel-plugin-transform-es2015-unicode-regex": "^6.3.13",
    "babel-plugin-transform-es3-member-expression-literals": "^6.5.0",
    "babel-plugin-transform-es3-property-literals": "^6.5.0",
    "babel-plugin-transform-object-rest-spread": "^6.3.13",
    "babel-register": "^6.3.13",
    "check-es3-syntax-cli": "^0.1.1",
    "cross-env": "^3.1.4",
    "eslint": "^3.8.1",
    "eslint-config-react-app": "^0.5.0",
    "eslint-plugin-flowtype": "^2.29.2",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "2.2.3",
    "eslint-plugin-react": "^6.8.0",
    "gitbook-cli": "^2.3.0",
    "glob": "^7.1.1",
    "jest": "^18.0.0",
    "rimraf": "^2.3.4",
    "rollup": "^0.41.4",
    "rollup-plugin-babel": "^2.7.1",
    "rollup-plugin-node-resolve": "^2.0.0",
    "rollup-plugin-replace": "^1.1.1",
    "rollup-plugin-uglify": "^1.0.1",
    "rxjs": "^5.0.0-beta.6",
    "typescript": "^1.8.0",
    "typescript-definition-tester": "0.0.4"
  },
  "npmName": "redux",
  "npmFileMap": [
    {
      "basePath": "/dist/",
      "files": [
        "*.js"
      ]
    }
  ],
  "browserify": {
    "transform": [
      "loose-envify"
    ]
  },
  "jest": {
    "testRegex": "(/test/.*\\.spec.js)$"
  }
}

Here is my webpack.config.js file:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    './index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        loaders: [ 'babel' ],
        exclude: /node_modules/,
        include: __dirname
      }
    ]
  }
}

I did follow this answer in attempt to fix it: babel-loader jsx SyntaxError: Unexpected token

I did npm install babel-preset-react and added the query to my webpack.config file to look like:

module: {
  loaders: [
    {
      test: /\.js$/,
      loaders: [ 'babel' ],
      exclude: /node_modules/,
      include: __dirname,
      query:
          {
              presets:['react']
          }
    }
  ]
}

}

However, this was the error I got after doing that:

$ npm start                                                                                ‹ruby-2.3.0›

> redux-counter-example@0.0.0 start /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux
> node server.js

==>   Listening on port 3000. Open up http://localhost:3000/ in your browser.
/Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/webpack-core/lib/LoadersList.js:54
    if(!element.loader || element.loader.indexOf("!") >= 0) throw new Error("Cannot define 'query' and multiple loaders in loaders list");
                                                            ^

Error: Cannot define 'query' and multiple loaders in loaders list
    at getLoadersFromObject (/Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/webpack-core/lib/LoadersList.js:54:65)
    at LoadersList.<anonymous> (/Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/webpack-core/lib/LoadersList.js:78:12)
    at Array.map (native)
    at LoadersList.match (/Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/webpack-core/lib/LoadersList.js:70:19)
    at /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/webpack/lib/NormalModuleFactory.js:111:68
    at /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/async/lib/async.js:726:13
    at /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/async/lib/async.js:52:16
    at done (/Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/async/lib/async.js:246:17)
    at /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/async/lib/async.js:44:16
    at /Users/NAME/Documents/personal/redux-demo/Redux and React/React & Redux/v01-insert-redux/node_modules/async/lib/async.js:723:17

npm ERR! Darwin 16.4.0
npm ERR! argv "/usr/local/Cellar/node5/5.12.0/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v5.12.0
npm ERR! npm  v4.1.2
npm ERR! code ELIFECYCLE
npm ERR! redux-counter-example@0.0.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the redux-counter-example@0.0.0 start script 'node server.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the redux-counter-example package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs redux-counter-example
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls redux-counter-example
npm ERR! There is likely additional logging output above.

Any help would be greatly appreciated

Body:
Its evident from the error that you cannot define multiple loaders inside loaders, since you have declared loaders  inside loaders whereas it should be loader and assigned a single value. Also install and use babel-presets for react, es2015 , stage-0 if you use ES6 like

module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
             presets: ['react', 'es2015', 'stage-0']
        },
        include: __dirname
      }
    ]
  }

Install the presets with

npm install -S babel-preset-react babel-preset-es2015 babel-preset-stage-0


来源: stackexchange

问:
Get coordinates of a particular section of the image
I want to add a text and link to both the sign boards here in this image (separately for both). I am trying to use the <map> <area> rule and I need to place the coordinates of the two rectangle boxes there so that once a user clicks on that board or text he will be redirected to some another page. Now the problem is that I am not sure from where to find the exact coordinates of the image here and how? If anyone can help then please help.

Here is the code I am using

```<code><img src="image link here" usemap="#mapname">
    <map name="mapname">
      <area shape="rect" coords="" href="http://www.google.com" alt="TEST">
    </map>
</code>```

答:
I'm working on something similar, but I wanted to make it responsive - not if you zoom in, image will be bigger and areas too. I didn't use <map>, because the coords are absolute. I used this:

```<code><div id="mapdiv">
  <img src="link" id="imgmap" alt="" />
    <a href="target"><div id="box1">Here is the text</div></a>
    <div id="box2" onclick="alert('You can use js too')"></div>
</div>
</code>```

And CSS:

```<code>#imgmap {
    width: 100%;
    }
div#mapdiv {
    position: relative; /* thanks to this... */
    }
div#menu div {
    position: absolute; /* ...and this are boxes positioned relatively inside the imgdiv */
    border: 1px dashed blue; /* for finding coords, remove after you are done */
}
div#box1 {
    left: 21%; /* my coords, make your own by trying and trying... */
    top: 26.5%;
    height: 5%;
    width: 6.5%
    }
div#box2 {
    left: 7.5%;
    top: 66.2%;
    height: 24.5%;
    width: 31.5%;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to add a text and link to both the sign boards here in this image (separately for both). I am trying to use the <map> <area> rule and I need to place the coordinates of the two rectangle boxes there so that once a user clicks on that board or text he will be redirected to some another page. Now the problem is that I am not sure from where to find the exact coordinates of the image here and how? If anyone can help then please help.

Here is the code I am using

    <map name="mapname">
      <area shape="rect" coords="" href="http://www.google.com" alt="TEST">
    </map>

Body:
I'm working on something similar, but I wanted to make it responsive - not if you zoom in, image will be bigger and areas too. I didn't use <map>, because the coords are absolute. I used this:

<div id="mapdiv">
  <img src="link" id="imgmap" alt="" />
    <a href="target"><div id="box1">Here is the text</div></a>
    <div id="box2" onclick="alert('You can use js too')"></div>
</div>

And CSS:

#imgmap {
    width: 100%;
    }
div#mapdiv {
    position: relative; /* thanks to this... */
    }
div#menu div {
    position: absolute; /* ...and this are boxes positioned relatively inside the imgdiv */
    border: 1px dashed blue; /* for finding coords, remove after you are done */
}
div#box1 {
    left: 21%; /* my coords, make your own by trying and trying... */
    top: 26.5%;
    height: 5%;
    width: 6.5%
    }
div#box2 {
    left: 7.5%;
    top: 66.2%;
    height: 24.5%;
    width: 31.5%;
    }


问:
System design: whether to normalize the departments or not
I'm working with two consultants in one project. The thing is we reached a point where both of them cannot get into an agreement and each offer a different approach.

The thing is we have a store with four departments and we want to find the best approach for working with all of them in the same database.

Each department sell different products: Cars, Boats, Jetskies and Motorbikes.

When the data is inserted or updated in each department there are some triggers to be fires so different workflows will begin, when adding a new car there are certain requirements that needs to be checked as well as the details of the car that are completely different than a boat. Also, regarding the data there are not many fields there are in common, I would say so far only the brand, color, model and year, everything else is specific for each deparment due to the different products and how they work with them..

Consultant one says:

Create one table for all the departments and use a column to identify what department the row belongs to, this way you will have only one trigger and inside the trigger you will then call the function/mehod you need for each record type.

Reason: you only have one table (with over 200 fields) and one trigger, is easier to maintain. Also if you need to report you just need to query one table and filter based on the record type. If you need to report for all the items you don't need to have multiple joins.

Consultant two says:

Create one table for each deparment and a trigger for each table.

Reason: you will have smaller tables (aprox 50 fields each) and is more flexible and you have it all separated. If you want to report you need to join the tables as you want to include data from different places.

I see the advantages of having everything in one place but if I want to expand or change anything I have the feeling I will bre creating a beast table as the data grows.

On the other side keep it separated look more appealing but will need to setup everything for each different table.

What would you say is the best approach?

答:
I would say option 2.

Why?

(1) I would find one table with 200+ columns harder to maintain. You're also then going to have to expose fields for an object that doesn't need said fields.

(2) You are also going to have to "hide" logic inside the trigger which then decides to do different actions based on the type of department etc...

(3) Option 2 involves more "scaffolding" and separate objects but those are objects are inherently smaller and easier to maintain and don't specifically hide logic or cause any sort of ambiguity.

(4) Option 2 abides by the single responsibility principle. Not everyone follows this I understand but I find it a good guiding principle, as the responsibility for the data lies with the individual table and the responsibility for triggered the action lies with the individual trigger as opposed to just being one mammoth entity/trigger.

** I would state that I am simply looking at this from a software development perspective, I am not sure whether or not SalesForce would handle this setup, but it is the way I would personally prefer to design it. :)


问:
Django Admin list_display product list
I new in django and I trying modifying a project to learn.

I've two classes in a model ('Order' and 'OrderItem'), the class OrderItem stores all items selected in a client order.

models.py

```<code>class Order(models.Model):

    STATUS_CHOICES = (
        (0, 'Waiting Payment'),
        (1, 'Completed'),
        (2, 'Canceled'),
    )

    PAYMENT_OPTION_CHOICES = (
        ('deposit', 'deposit'),
        ('paypal', 'Paypal'),
    )

    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='User')
    status = models.IntegerField(
        'Situation', choices=STATUS_CHOICES, default=0, blank=True
    )
    payment_option = models.CharField(
        'Payment Options', choices=PAYMENT_OPTION_CHOICES, max_length=20,
         default='deposit'
    )

    created = models.DateTimeField('Created in', auto_now_add=True)
    modified = models.DateTimeField('Modified in', auto_now=True)

    objects = OrderManager()

    class Meta:
        verbose_name = 'Order'
        ordering = ('-created',)

    def __str__(self):
        return 'Order #{}'.format(self.pk)

    def products(self):
        products_ids = self.items.values_list('product')
        return Product.objects.filter(pk__in=products_ids)

    def total(self):
        aggregate_queryset = self.items.aggregate(
            total = models.Sum(
                models.F('price') * models.F('quantity'),
                output_field = models.DecimalField()
            )
        )
        return aggregate_queryset['total']

class OrderItem(models.Model):

    order = models.ForeignKey(Order, verbose_name='Order',     related_name='items')
    product = models.ForeignKey('event.Product', verbose_name='Product')
    quantity = models.PositiveIntegerField('Quantity', default=1)
    price = models.DecimalField('Price', decimal_places=2, max_digits=8)

    class Meta:
        verbose_name = 'Order Item'

    def __str__(self):
        return '{}'.format(self.product)
</code>```

In the django admin I can show all Orders and when I click to see more I see all products on this order, but my problem is, I can't list this products of class OrderItem in my list_display, how  can I do that?

admin.py

```<code>class OrderItemInline(admin.StackedInline):
    model = OrderItem
    fields = ['product']
    readonly_fields = ['product',]
    extra = 0
    max_num = 0

class OrderAdmin(admin.ModelAdmin):

    model = Order
    inlines = [ OrderItemInline, ]

    readonly_fieldsets = (
        (None, {
            'fields': ('user','status','order','created')
        }),
    )
    readonly_fields = ['user','status','payment_option']

    search_fields = ['user__name', 'user__email']
    list_filter = ['status', ]

    list_display = ['pk','user','status','created','product']
    ordering = ('-created',)

   admin.site.register(Order, OrderAdmin)
</code>```

答:
I got it, I don't know if it's the rigth one.

I'm create a list first.

```<code>def list_products(self, obj):
    products = []
    for prod_name in obj.items.values_list('product__name', flat=True):
        products.append(''.join(prod_name))
        to_return = '<br/>'.join(products)
    return mark_safe(to_return)
</code>```

Title: Django Admin list_display product list

Body:
I new in django and I trying modifying a project to learn.

I've two classes in a model ('Order' and 'OrderItem'), the class OrderItem stores all items selected in a client order.

models.py

class Order(models.Model):

    STATUS_CHOICES = (
        (0, 'Waiting Payment'),
        (1, 'Completed'),
        (2, 'Canceled'),
    )

    PAYMENT_OPTION_CHOICES = (
        ('deposit', 'deposit'),
        ('paypal', 'Paypal'),
    )

    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='User')
    status = models.IntegerField(
        'Situation', choices=STATUS_CHOICES, default=0, blank=True
    )
    payment_option = models.CharField(
        'Payment Options', choices=PAYMENT_OPTION_CHOICES, max_length=20,
         default='deposit'
    )

    created = models.DateTimeField('Created in', auto_now_add=True)
    modified = models.DateTimeField('Modified in', auto_now=True)

    objects = OrderManager()

    class Meta:
        verbose_name = 'Order'
        ordering = ('-created',)

    def __str__(self):
        return 'Order #{}'.format(self.pk)

    def products(self):
        products_ids = self.items.values_list('product')
        return Product.objects.filter(pk__in=products_ids)

    def total(self):
        aggregate_queryset = self.items.aggregate(
            total = models.Sum(
                models.F('price') * models.F('quantity'),
                output_field = models.DecimalField()
            )
        )
        return aggregate_queryset['total']

class OrderItem(models.Model):

    order = models.ForeignKey(Order, verbose_name='Order',     related_name='items')
    product = models.ForeignKey('event.Product', verbose_name='Product')
    quantity = models.PositiveIntegerField('Quantity', default=1)
    price = models.DecimalField('Price', decimal_places=2, max_digits=8)

    class Meta:
        verbose_name = 'Order Item'

    def __str__(self):
        return '{}'.format(self.product)

In the django admin I can show all Orders and when I click to see more I see all products on this order, but my problem is, I can't list this products of class OrderItem in my list_display, how  can I do that?

admin.py

class OrderItemInline(admin.StackedInline):
    model = OrderItem
    fields = ['product']
    readonly_fields = ['product',]
    extra = 0
    max_num = 0

class OrderAdmin(admin.ModelAdmin):

    model = Order
    inlines = [ OrderItemInline, ]

    readonly_fieldsets = (
        (None, {
            'fields': ('user','status','order','created')
        }),
    )
    readonly_fields = ['user','status','payment_option']

    search_fields = ['user__name', 'user__email']
    list_filter = ['status', ]

    list_display = ['pk','user','status','created','product']
    ordering = ('-created',)

   admin.site.register(Order, OrderAdmin)

Body:
I got it, I don't know if it's the rigth one.

I'm create a list first.

def list_products(self, obj):
    products = []
    for prod_name in obj.items.values_list('product__name', flat=True):
        products.append(''.join(prod_name))
        to_return = '<br/>'.join(products)
    return mark_safe(to_return)


问:
library integration limit in IOS / Apple
I haeard from some android developer that there is a library limit in android provided by google so:

Is there such scenarios exist in apple or how any library integration limit in a single app ios/apple. ??

How many libraries can we integrate in single project?

答:
I think the think you heard about is MultiDex on Android which is related with total count of functions inside app including 3rd party libraries.

As the Android platform has continued to grow, so has the size of Android apps. When your app and the libraries it references reach a certain size, you encounter build errors that indicate your app has reached a limit of the Android app build architecture.

But as far as I know there is nothing like MultiDex on iOS.


问:
Render a table in the rows of another table in react
I want to create something like this in react:

I create a renderTable and a renderInside function. Inside renderTable I call renderInside like this:

```<code>const renderInside = (slipsList) => {
  if (slipsList) {
    return (
      <table className="table table-bordered">
        <thead>
          <tr>
            <th className="table__header">
              <div className="table__header__text">
                <span className="table__header--selected">
                  Symbol
                </span>
              </div>
            </th>
          </tr>
        </thead>
        <tbody>
          {slipsList.map((slip, i) =>
            <tr key={i}>
              <td>{slip.amount}</td>
            </tr>
          )}
        </tbody>
      </table>
    );
  }
  return (
    <div>Loading...</div>
  );
};
</code>```

and the renderTable is like this:

```<code>const renderTable = (slipsList) => {
  if (slipsList) {
    return (
      <div className="table-scrollable-container">
        <div className="table-scrollable">
          <table className="table table-bordered">
            <thead>
              <tr>
                <th className="table__header">
                  <div className="table__header__text">
                    <span className="table__header--selected">
                      Date Valeur
                    </span>
                  </div>
                  <div className="table__header__arrow" />
                </th>
              </tr>
            </thead>
            <tbody>
              {slipsList.map((slip, i) =>
                <tr key={i}>
                  <td className="table-sticky--first-col">
                    {slip.confirmationDate}
                  </td>
                  <td>
                    {slip.netAmountEuro}
                  </td>
                  <tr className="collapsed">
                    <td colSpan="10">
                    {renderInside(slipsList)}
                  </td>
                </tr>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    );
  }
  return (
    <div>Loading...</div>
  );
};
</code>```

But it doesn't work. I use another two ways of doing this but I want. For every row or the main table I must put the secondary table. Any ideas of how to do this?

答:
Try to Use this:

In renderInside method:

```<code>{slipsList.map((slip, i) => (  //added this bracket
      <tr key={i}>
         <td>{slip.amount}</td>
      </tr>
    )
 )}
</code>```

In renderTable method:

```<code>{slipsList.map((slip, i) => (   //added this bracket
    <tr key={i}>
      <td className="table-sticky--first-col">
        {slip.confirmationDate}
      </td>
      <td>
        {slip.netAmountEuro}
      </td>
      <tr className="collapsed">
        <td colSpan="10">
          {renderInside(slipsList)}
        </td>
      </tr>
    </tr>
  )
)}
</code>```

One more thing, i think you need to pass slip inside {renderInside(slipsList)} method instead of slipsList.

Body:
I want to create something like this in react:

I create a renderTable and a renderInside function. Inside renderTable I call renderInside like this:

const renderInside = (slipsList) => {
  if (slipsList) {
    return (

                  Symbol

          {slipsList.map((slip, i) =>

              {slip.amount}

          )}

    );
  }
  return (

Loading...

  );
};

and the renderTable is like this:

const renderTable = (slipsList) => {
  if (slipsList) {
    return (

                      Date Valeur

              {slipsList.map((slip, i) =>

                    {slip.confirmationDate}

                    {slip.netAmountEuro}

                    {renderInside(slipsList)}

              )}

    );
  }
  return (

Loading...

  );
};

But it doesn't work. I use another two ways of doing this but I want. For every row or the main table I must put the secondary table. Any ideas of how to do this?

Body:
Try to Use this:

In renderInside method:

{slipsList.map((slip, i) => (  //added this bracket
      <tr key={i}>
         <td>{slip.amount}</td>
      </tr>
    )
 )}

In renderTable method:

{slipsList.map((slip, i) => (   //added this bracket
    <tr key={i}>
      <td className="table-sticky--first-col">
        {slip.confirmationDate}
      </td>
      <td>
        {slip.netAmountEuro}
      </td>
      <tr className="collapsed">
        <td colSpan="10">
          {renderInside(slipsList)}
        </td>
      </tr>
    </tr>
  )
)}

One more thing, i think you need to pass slip inside {renderInside(slipsList)} method instead of slipsList.


问:
Change gravity of PopupWindow
I have a button that must show a popup window. And the popup window must be aligned with the right side of the button. That's how I do it.

```<code>button.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick( final View view ) {
        if(popup == null) {
            final View view = getLayoutInflater().inflate(R.layout.popup, null);
            popup = new PopupWindow(view);
        }

        if(popup.isShowing()) {
            popup.dismiss();
        } else {
            popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            popup.setFocusable(true);
            popup.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
            popup.showAsDropDown(button, 0, 0);
        }
    }
} );
</code>```

This code works fine but the popup window is aligned with the left side of the button. Is there an easy way to change gravity of PopupWindow?

答:
The easiest way I've found is to specify the x-offset parameter:</p>

```<code>final View view = popup.getContentView();
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
popup.showAsDropDown(button, button.getWidth() - view.getMeasuredWidth(), 0);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Change gravity of PopupWindow

Body:
I have a button that must show a popup window. And the popup window must be aligned with the right side of the button. That's how I do it.

button.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick( final View view ) {
        if(popup == null) {
            final View view = getLayoutInflater().inflate(R.layout.popup, null);
            popup = new PopupWindow(view);
        }

        if(popup.isShowing()) {
            popup.dismiss();
        } else {
            popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            popup.setFocusable(true);
            popup.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
            popup.showAsDropDown(button, 0, 0);
        }
    }
} );

This code works fine but the popup window is aligned with the left side of the button. Is there an easy way to change gravity of PopupWindow?

Body:
The easiest way I've found is to specify the x-offset parameter:

final View view = popup.getContentView();
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
popup.showAsDropDown(button, button.getWidth() - view.getMeasuredWidth(), 0);


问:
Using T-SQL EXCEPT with DELETE / Optimizing a query
The following code removes records of tasks related to inactive projects from the table.

```<code>delete from [Deliverables] where
[Deliverables].[ProjectID] not in
(
select
[ProjectID] from [ActiveProjects]
)
</code>```

I've read somewhere that using NOT IN with subquery that returns a lot of values is not really the most efficient thing to do and it's better to use EXCEPT clause.

However, when I try to use the following code, I get an error (Incorrect syntax near the keyword 'except'.)

```<code>delete from [Deliverables]
except
select * from [Deliverables], [ActiveProjects]
where [Deliverables].[ProjectID] = [ActiveProjects].[ProjectID]
</code>```

How can I use EXCEPT with DELETE? If I can't, is there any way to optimize my query to execute faster?

答:
Try it like this (modify to your needs by adding where-clauses and your column names etc)</p>

```<code>delete from table1
  from table1 a
 inner join
      ( select your_column
          from table1
        except
        select your_column
          from table2
      ) b
    on a.your_column = b.your_column;
</code>```

Body:
The following code removes records of tasks related to inactive projects from the table.

delete from [Deliverables] where
[Deliverables].[ProjectID] not in
(
select
[ProjectID] from [ActiveProjects]
)

I've read somewhere that using NOT IN with subquery that returns a lot of values is not really the most efficient thing to do and it's better to use EXCEPT clause.

However, when I try to use the following code, I get an error (Incorrect syntax near the keyword 'except'.)

delete from [Deliverables]
except
select * from [Deliverables], [ActiveProjects]
where [Deliverables].[ProjectID] = [ActiveProjects].[ProjectID]

How can I use EXCEPT with DELETE? If I can't, is there any way to optimize my query to execute faster?

Body:
Try it like this (modify to your needs by adding where-clauses and your column names etc)

delete from table1
  from table1 a
 inner join
      ( select your_column
          from table1
        except
        select your_column
          from table2
      ) b
    on a.your_column = b.your_column;


问:
how to disable defalut URl showing when overing on button
Please refer below image

when ever am handovering it shows some URl in  window Bottom of IE browser. but no url supplied for this button.

This is the button  code

```<code><button id="btnCancel"  >Cancel</button>
</code>```

How can i remove the invalid URL ? why it showing in IE browser ?

Thanks,

Siva

答:
Always specify the type attribute for a "button" element. Different browsers use different default types for the "button" element.
If you do not specify the "type" in button element, browser assumes it a "submit" type and use enclosing "form" element action of the button element.
Please refer below link for reference-
https://www.w3schools.com/tags/tag_button.asp</p>

Body:
Please refer below image

when ever am handovering it shows some URl in  window Bottom of IE browser. but no url supplied for this button.

This is the button  code

<button id="btnCancel"  >Cancel</button>

How can i remove the invalid URL ? why it showing in IE browser ?

Thanks,

Siva


问:
Filter and Order the firebase data in android
The following is my firebase database structure.

The following is the method that I get the data from firebase database to the recycler view. However, there is an unique id(red oval) in the child part. How can I go after the unique id and filter the data using the key "category"? Also, I want to order them in acensding order but firebase does not provide a method for that. Where can I get the list of data and reverse them? Please give me some helps. Thank you very much.

```<code>    mFilterDatabse = mDatabase.orderByChild("category").equalTo(categoryResult);

    FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mFilterDatabse
    ) {
        @Override
        protected void populateViewHolder(ProductViewHolder viewHolder, final Product model, int position) {

            Log.d(TAG, "loading view " + position);
            final String product_id = getRef(position).getKey();
            viewHolder.setProductName(model.getProductName());
            viewHolder.setDescription(model.getDescription());
            viewHolder.setImage(getApplicationContext(), model.getProductImage());
            viewHolder.setUid(model.getUid());

            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent productDetailIntent = new Intent();
                    productDetailIntent.setClass(MainActivity.this, ProductDetailActivity.class);
                    productDetailIntent.putExtra("product_id", product_id);
                    Log.d(TAG + " product_id", product_id);
                    productDetailIntent.putExtra("colorNo", model.getColorNo());
                    Log.d(TAG + " colorNo", model.getColorNo() + "");
                    startActivity(productDetailIntent);
                }
            });

            Log.d(TAG, "finish loading view");
        }
    };

    mProductList.setAdapter(firebaseRecyclerAdapter);
    firebaseRecyclerAdapter.notifyDataSetChanged();

public static class ProductViewHolder extends RecyclerView.ViewHolder {

    View mView;
    private Typeface customTypeface = Typeface.createFromAsset(itemView.getContext().getAssets(), FontManager.APP_FONT);

    public ProductViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setProductName(String productName) {
        TextView product_title = (TextView) mView.findViewById(R.id.p_title);
        product_title.setText(productName);
        product_title.setTypeface(customTypeface);
    }

    public void setDescription(String description) {
        TextView product_desc = (TextView) mView.findViewById(R.id.p_desc);
        product_desc.setText(description);
        product_desc.setTypeface(customTypeface);
    }

    public void setUid(String uid) {
        TextView product_username = (TextView) mView.findViewById(R.id.p_username);
        product_username.setText(uid);
        product_username.setTypeface(customTypeface);
    }

    public void setImage(final Context ctx, final String image) {
        final ImageView post_image = (ImageView) mView.findViewById(R.id.product_image);
        Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(post_image, new Callback() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "image loading success !");
            }

            @Override
            public void onError() {
                Log.d(TAG, "image loading error !");
                Picasso.with(ctx)
                        .load(image)
                        .resize(100, 100)
                        .centerCrop()
                        .into(post_image);
            }
        });
    }
}
</code>```

答:
When you use the push() method to generate the unique keys, is the moment in which you can get the keys. Please use this code:

```<code>DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(Product).push();
String pushedKey = ref.getKey(); // We can do whatever you want with them
</code>```

Because of the unique ids, the items are already ordered by date (ascending order). If you want to order descending you need to use a TIMESTAMP like this: -1 * ServerValue.TIMESTAMP. Here is also the official documentation which will help you do more than that. You will be able to orderByChild(), orderByKey() or orderByValue() and also limitToFirst(), limitToLast(), equalTo() or to use intervals like: startAt() and endAt().
Hope it helps! :)

Body:
The following is my firebase database structure.

The following is the method that I get the data from firebase database to the recycler view. However, there is an unique id(red oval) in the child part. How can I go after the unique id and filter the data using the key "category"? Also, I want to order them in acensding order but firebase does not provide a method for that. Where can I get the list of data and reverse them? Please give me some helps. Thank you very much.

    mFilterDatabse = mDatabase.orderByChild("category").equalTo(categoryResult);

    FirebaseRecyclerAdapter<Product, ProductViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Product, ProductViewHolder>(

            Product.class,
            R.layout.product_row,
            ProductViewHolder.class,
            mFilterDatabse
    ) {
        @Override
        protected void populateViewHolder(ProductViewHolder viewHolder, final Product model, int position) {

            Log.d(TAG, "loading view " + position);
            final String product_id = getRef(position).getKey();
            viewHolder.setProductName(model.getProductName());
            viewHolder.setDescription(model.getDescription());
            viewHolder.setImage(getApplicationContext(), model.getProductImage());
            viewHolder.setUid(model.getUid());

            viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent productDetailIntent = new Intent();
                    productDetailIntent.setClass(MainActivity.this, ProductDetailActivity.class);
                    productDetailIntent.putExtra("product_id", product_id);
                    Log.d(TAG + " product_id", product_id);
                    productDetailIntent.putExtra("colorNo", model.getColorNo());
                    Log.d(TAG + " colorNo", model.getColorNo() + "");
                    startActivity(productDetailIntent);
                }
            });

            Log.d(TAG, "finish loading view");
        }
    };

    mProductList.setAdapter(firebaseRecyclerAdapter);
    firebaseRecyclerAdapter.notifyDataSetChanged();

public static class ProductViewHolder extends RecyclerView.ViewHolder {

    View mView;
    private Typeface customTypeface = Typeface.createFromAsset(itemView.getContext().getAssets(), FontManager.APP_FONT);

    public ProductViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setProductName(String productName) {
        TextView product_title = (TextView) mView.findViewById(R.id.p_title);
        product_title.setText(productName);
        product_title.setTypeface(customTypeface);
    }

    public void setDescription(String description) {
        TextView product_desc = (TextView) mView.findViewById(R.id.p_desc);
        product_desc.setText(description);
        product_desc.setTypeface(customTypeface);
    }

    public void setUid(String uid) {
        TextView product_username = (TextView) mView.findViewById(R.id.p_username);
        product_username.setText(uid);
        product_username.setTypeface(customTypeface);
    }

    public void setImage(final Context ctx, final String image) {
        final ImageView post_image = (ImageView) mView.findViewById(R.id.product_image);
        Picasso.with(ctx).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(post_image, new Callback() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "image loading success !");
            }

            @Override
            public void onError() {
                Log.d(TAG, "image loading error !");
                Picasso.with(ctx)
                        .load(image)
                        .resize(100, 100)
                        .centerCrop()
                        .into(post_image);
            }
        });
    }
}

Body:
When you use the push() method to generate the unique keys, is the moment in which you can get the keys. Please use this code:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(Product).push();
String pushedKey = ref.getKey(); // We can do whatever you want with them

Because of the unique ids, the items are already ordered by date (ascending order). If you want to order descending you need to use a TIMESTAMP like this: -1 * ServerValue.TIMESTAMP. Here is also the official documentation which will help you do more than that. You will be able to orderByChild(), orderByKey() or orderByValue() and also limitToFirst(), limitToLast(), equalTo() or to use intervals like: startAt() and endAt().
Hope it helps! :)


问:
Warning: Failed propType: Required prop `data` was not specified in `Photo`. Check the render method of `withApollo(Photo)`
So, the above mentioned warning is generated on component page load (See attached image).

propTypes for the component are clearly specified after the component declaration.

Can anyone shed any light on this issue?

My code is as follows:

Photo.js

import React from 'react';
import Comments from './Comments';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { Link } from 'react-router';
import {
  gql,
  graphql,
  withApollo
} from 'react-apollo';
import ApolloClient from 'apollo-client';

class Photo extends React.Component {

incrementQuery (currentID) {

    console.log("like of id= " + currentID + " has been incremented by 1");

    this.props.client.query({
      query: queryB,
      variables: {
        id: currentID,
      },
    });
  }

  render() {
    const { post, i } = this.props;

    return (

          <Link to={`/view/${post.id}`}>

          </Link>
          <CSSTransitionGroup transitionName="like" transitionEnterTimeout={500} transitionLeaveTimeout={500}>
            {post.likes}
          </CSSTransitionGroup>

{post.caption}

            <button onClick={this.incrementQuery.bind(null,i)} className="likes">♥ {post.likes}</button>
            <Link to={`/view/${post.id}`} className="button">

                 {(post.comments ? Object.keys(post.comments).length : 0)}

            </Link>

    )
  }
};

Photo.propTypes = {
  client: React.PropTypes.instanceOf(ApolloClient).isRequired,
  query: React.PropTypes.object,
  variables: React.PropTypes.object,
  data: React.PropTypes.shape({
    loading: React.PropTypes.bool.isRequired,
    error: React.PropTypes.bool.isRequired,
    updatePosts: React.PropTypes.object,
  }).isRequired,
}

const queryB = gql`
  mutation updatePosts($id: ID!) {
    updatePosts (id: $id, likes: 1) {
      id
      likes
    }
  }
  `;

const PhotoWithApollo = withApollo(Photo);

export default PhotoWithApollo;```
</div>
</div>
</p>

<p>PhotoGrid.js</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>import _ from 'lodash';
import React from 'react';
import Photo from './Photo';
import {
  gql,
  graphql,
} from 'react-apollo';

const PhotoGrid = (props) => ({

  handleSubmit(e) {
    e.preventDefault();
    this.props.addItem(this.refs.item.value);
  },

  render() {
    const { data } = this.props;

    if (data.loading) {
      return <p>Loading ...</p>;
    }
    if (data.error) {
      return <p>{data.error.message}</p>;
    }
    return (
      <div className="photo-grid">
        { data.allPostses.map( posts => <Photo data={{loading: true, error: false}} key={posts.id} i={posts.id} post={posts} /> ) }
      </div>
    )
  }
});

const allPostsCommentsQuery = gql`
  query allPostsCommentsQuery {
    allPostses {
      id
      displaysrc
      caption
      likes
      comments {
        id
        posts {
          id
        }
        text
        user
      }
    }
  }
`;

const PhotoGridWithData = graphql(allPostsCommentsQuery)(PhotoGrid);

export default PhotoGridWithData;</code>```

答:
This error is because the component Photo requires a property name data that isRequired. This comes from code:

```<code>Photo.propTypes = {
  data: React.PropTypes.shape({
    loading: React.PropTypes.bool.isRequired,
    error: React.PropTypes.bool.isRequired,
    updatePosts: React.PropTypes.object,
  }).isRequired
}
</code>```

You must send to Photo aproperty data with the specified shape.

Verify what does withApollo: does it insert data in Photo? If not, verify how is called the exported component PhotoWithApollo. There should be something like:

```<code><PhotoWithApollo data={{loading: true, error:'my error', updatePosts:{}}}/>
</code>```

Body:
So, the above mentioned warning is generated on component page load (See attached image).

propTypes for the component are clearly specified after the component declaration.

Can anyone shed any light on this issue?

My code is as follows:

Photo.js

import React from 'react';
import Comments from './Comments';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { Link } from 'react-router';
import {
  gql,
  graphql,
  withApollo
} from 'react-apollo';
import ApolloClient from 'apollo-client';

class Photo extends React.Component {

incrementQuery (currentID) {

    console.log("like of id= " + currentID + " has been incremented by 1");

    this.props.client.query({
      query: queryB,
      variables: {
        id: currentID,
      },
    });
  }

  render() {
    const { post, i } = this.props;

    return (

          <Link to={`/view/${post.id}`}>

          </Link>
          <CSSTransitionGroup transitionName="like" transitionEnterTimeout={500} transitionLeaveTimeout={500}>
            {post.likes}
          </CSSTransitionGroup>

{post.caption}

            <button onClick={this.incrementQuery.bind(null,i)} className="likes">♥ {post.likes}</button>
            <Link to={`/view/${post.id}`} className="button">

                 {(post.comments ? Object.keys(post.comments).length : 0)}

            </Link>

    )
  }
};

Photo.propTypes = {
  client: React.PropTypes.instanceOf(ApolloClient).isRequired,
  query: React.PropTypes.object,
  variables: React.PropTypes.object,
  data: React.PropTypes.shape({
    loading: React.PropTypes.bool.isRequired,
    error: React.PropTypes.bool.isRequired,
    updatePosts: React.PropTypes.object,
  }).isRequired,
}

const queryB = gql`
  mutation updatePosts($id: ID!) {
    updatePosts (id: $id, likes: 1) {
      id
      likes
    }
  }
  `;

const PhotoWithApollo = withApollo(Photo);

export default PhotoWithApollo;

PhotoGrid.js

import _ from 'lodash';
import React from 'react';
import Photo from './Photo';
import {
  gql,
  graphql,
} from 'react-apollo';

const PhotoGrid = (props) => ({

  handleSubmit(e) {
    e.preventDefault();
    this.props.addItem(this.refs.item.value);
  },

  render() {
    const { data } = this.props;

    if (data.loading) {
      return
Loading ...
;
    }
    if (data.error) {
      return
{data.error.message}
;
    }
    return (

        { data.allPostses.map( posts => <Photo data={{loading: true, error: false}} key={posts.id} i={posts.id} post={posts} /> ) }

    )
  }
});

const allPostsCommentsQuery = gql`
  query allPostsCommentsQuery {
    allPostses {
      id
      displaysrc
      caption
      likes
      comments {
        id
        posts {
          id
        }
        text
        user
      }
    }
  }
`;

const PhotoGridWithData = graphql(allPostsCommentsQuery)(PhotoGrid);

export default PhotoGridWithData;

Body:
This error is because the component Photo requires a property name data that isRequired. This comes from code:

Photo.propTypes = {
  data: React.PropTypes.shape({
    loading: React.PropTypes.bool.isRequired,
    error: React.PropTypes.bool.isRequired,
    updatePosts: React.PropTypes.object,
  }).isRequired
}

You must send to Photo aproperty data with the specified shape.

Verify what does withApollo: does it insert data in Photo? If not, verify how is called the exported component PhotoWithApollo. There should be something like:

<PhotoWithApollo data={{loading: true, error:'my error', updatePosts:{}}}/>


问:
Array to store location of matching poistions of 2 different arrays in vba
I have created two arrays both of equal dimensions in VBA (part of code below, used twice to create 2 arrays), I want to use a match function/some other function/ loop to store the matching values location in a new array in vba, and in case of error(non existing value) any appropriate flag(0).

For eg: Array1(USA, UK, Singapore, China)
        Array2(India, USA, UK, New Zealand)
        Array3(0,2,3,0)

I am looking how to get to array3{}

thanks in advance!!

```<code>Dim wcountryarray() as variant

ReDim wcountryArrayname(1 To maxima5 * Site_countmax * wacountmax) As Variant

counter = 100

lsitetype = 1

For Country_count = 1 To wacountmax

For within_site = 1 To Site_countmax

counter = counter + 2

For Site_types = lsitetype To maxima5 + lsitetype - 1

    wcountryArrayname(Site_types) = WB2.Sheets("Data Input").Cells(Site_types + counter, 2).Value & "|" & _
    WB2.Sheets("Data Input").Cells(Site_types + counter, 3).Value & "|" & _
    WB2.Sheets("Data Input").Cells(Site_types + counter, 4).Value

 Next Site_types

 counter = counter + 30 - maxima5 - (maxima5 - 1)

 columns_Data = columns_Data - 1

 Site_types = Site_types - 1

 lsitetype = Site_types + 1

 Next within_site

 counter = (100 * (Country_count + 1)) - Site_types

 Next Country_count
</code>```

答:
For example, in VBA this results in Variant(1 To 4) array:

```<code>a = [IfError(Match({"India","USA","UK","New Zealand"},{"USA","UK","Singapore","China"},0),)]

Debug.Print Join(a) ' "0 1 2 0"
</code>```

or with arrays:

```<code>array1 = Array("USA", "UK", "Singapore", "China")
array2 = Array("India", "USA", "UK", "New Zealand")
array3 = Evaluate("IFERROR(MATCH({""" & Join(array2, """,""") & """},{""" & Join(array1, """,""") & """},0),)")

Debug.Print Join(array3) ' "0 1 2 0"
</code>```

Body:
I have created two arrays both of equal dimensions in VBA (part of code below, used twice to create 2 arrays), I want to use a match function/some other function/ loop to store the matching values location in a new array in vba, and in case of error(non existing value) any appropriate flag(0).

For eg: Array1(USA, UK, Singapore, China)
        Array2(India, USA, UK, New Zealand)
        Array3(0,2,3,0)

I am looking how to get to array3{}

thanks in advance!!

Dim wcountryarray() as variant

ReDim wcountryArrayname(1 To maxima5 * Site_countmax * wacountmax) As Variant

counter = 100

lsitetype = 1

For Country_count = 1 To wacountmax

For within_site = 1 To Site_countmax

counter = counter + 2

For Site_types = lsitetype To maxima5 + lsitetype - 1

    wcountryArrayname(Site_types) = WB2.Sheets("Data Input").Cells(Site_types + counter, 2).Value & "|" & _
    WB2.Sheets("Data Input").Cells(Site_types + counter, 3).Value & "|" & _
    WB2.Sheets("Data Input").Cells(Site_types + counter, 4).Value

 Next Site_types

 counter = counter + 30 - maxima5 - (maxima5 - 1)

 columns_Data = columns_Data - 1

 Site_types = Site_types - 1

 lsitetype = Site_types + 1

 Next within_site

 counter = (100 * (Country_count + 1)) - Site_types

 Next Country_count

Body:
For example, in VBA this results in Variant(1 To 4) array:

a = [IfError(Match({"India","USA","UK","New Zealand"},{"USA","UK","Singapore","China"},0),)]

Debug.Print Join(a) ' "0 1 2 0"

or with arrays:

array1 = Array("USA", "UK", "Singapore", "China")
array2 = Array("India", "USA", "UK", "New Zealand")
array3 = Evaluate("IFERROR(MATCH({""" & Join(array2, """,""") & """},{""" & Join(array1, """,""") & """},0),)")

Debug.Print Join(array3) ' "0 1 2 0"


问:
Autofac decorator + delegate factory
I am trying to use a decorator in Autofac with a delegate factory but I can't seem to get it to resolve the parameters.

```<code>public interface IFoo
{ }

public class Foo : IFoo
{
    public Foo(string bar)
    { ... }
}

public class DecoratedFoo : IFoo
{
    public DecoratedFoo(IFoo decorated)
    { ... }
}
</code>```

I would like to inject into a service like so:

```<code>public SomeService(Func<string, IFoo> factory)
{
    // I would expect IFoo to be a DecoratedFoo here
    IFoo foo = factory("hello");
}
</code>```

I have registered components like so:

```<code>builder.RegisterType<Foo>()
    .Named<IFoo>("foo")
    .UsingConstructor(typeof(string));

builder.RegisterDecorator<IFoo>(
    (ctx, inner) => new DecoratedFoo(inner),
    fromKey: "foo");
</code>```

I get an error saying it cannot resolve my parameter bar. This is a simplified example but I won't know what the value of bar is (hence using the factory).

Is there any way to accomplish what I'm doing?

答:
When you use RegisterDecorator - it will not propagate string parameter you pass to your factory deeper to your Foo constructor. Here is an open issue about that. So on this line

```<code>IFoo foo = factory("hello");
</code>```

It will throw exception (as you observe) because it will try to find parameterless constructor of Foo and there is none.

To fix, you can remove your RegisterDecorator and instead do that manually:

```<code>builder.RegisterType<Foo>()
    .Named<IFoo>("foo");
builder.Register((cnt, parameters) =>
    new DecoratedFoo(cnt.ResolveNamed<IFoo>("foo", parameters))).As<IFoo>();
</code>```

Almost the same amount of code, but works as expected, because you manually propagate parameters.

Title: Autofac decorator + delegate factory

Body:
I am trying to use a decorator in Autofac with a delegate factory but I can't seem to get it to resolve the parameters.

public interface IFoo
{ }

public class Foo : IFoo
{
    public Foo(string bar)
    { ... }
}

public class DecoratedFoo : IFoo
{
    public DecoratedFoo(IFoo decorated)
    { ... }
}

I would like to inject into a service like so:

public SomeService(Func<string, IFoo> factory)
{
    // I would expect IFoo to be a DecoratedFoo here
    IFoo foo = factory("hello");
}

I have registered components like so:

builder.RegisterType<Foo>()
    .Named<IFoo>("foo")
    .UsingConstructor(typeof(string));

builder.RegisterDecorator<IFoo>(
    (ctx, inner) => new DecoratedFoo(inner),
    fromKey: "foo");

I get an error saying it cannot resolve my parameter bar. This is a simplified example but I won't know what the value of bar is (hence using the factory).

Is there any way to accomplish what I'm doing?

Body:
When you use RegisterDecorator - it will not propagate string parameter you pass to your factory deeper to your Foo constructor. Here is an open issue about that. So on this line

IFoo foo = factory("hello");

It will throw exception (as you observe) because it will try to find parameterless constructor of Foo and there is none.

To fix, you can remove your RegisterDecorator and instead do that manually:

builder.RegisterType<Foo>()
    .Named<IFoo>("foo");
builder.Register((cnt, parameters) =>
    new DecoratedFoo(cnt.ResolveNamed<IFoo>("foo", parameters))).As<IFoo>();

Almost the same amount of code, but works as expected, because you manually propagate parameters.


问:
parsing JSON object to a list of a model from couchbase view
I am trying to make a mapreduce view in couchbase like so. Right now my view code in couchbase server looks like this,

```<code>function(doc, meta)
{
  emit(doc.content,null);
}
</code>```

where I am emitting the content of a document.

so when I iterate in (var rows in result.Rows), I want to assign each value in the content(in JSON) to a list of a model(abc) which has the get/set for serialNumber,uldNumber, and assignedDate in a class

row.key value has

```<code>{{
  "serialNumber": "1",
  "uldNumber": "33",
  "assignedDate": "2033-02-17T09:10:38"
}}
</code>```

my class looks like

```<code> public class abc
    {
        //[JsonProperty("serialNumber")]
        public string SerialNumber { get; set; }

        //[JsonProperty("uldNumber")]
        public string UldNumber { get; set; }

        //[JsonProperty("assignedDate")]
        public DateTime AssignedDate { get; set; }
    }
</code>```

If I try to deserialize it like so,

```<code> JsonSerializer js = new JsonSerializer();
 _abcList.Add(js.Deserialize<dynamic[]>(row));
</code>```

I get "cannot convert from 'Couchbase.Views.ViewRow<dynamic>' to 'Newtonsoft.Json.JsonReader"

If i were to do this, row.Key.toString(); , I get exception error of 'Newtonsoft.Json.Linq.JObject'

"cannot convert couchbase.views.viewrow to string "

I have looked at this and this but both of these have not worked.

答:
When you do an emit statement like this:

```<code>emit(doc.content, null);
</code>```

You're just making the view key doc.content, and leaving the row data null.  You might try this:

```<code>emit(doc.content, doc);
</code>```

This will make the row content the full data in the document.  Alternatively, you can use row.Id to get the document ID and use Read(row.Id) to read the document.  This is slower, but uses less storage space for the view.

Also, you typically don't put JSON object maps in the key.  Normally it's either a single value like a number or string, or an array of values.  Arrays are easier to use for view lookups.

Body:
I am trying to make a mapreduce view in couchbase like so. Right now my view code in couchbase server looks like this,

function(doc, meta)
{
  emit(doc.content,null);
}

where I am emitting the content of a document.

so when I iterate in (var rows in result.Rows), I want to assign each value in the content(in JSON) to a list of a model(abc) which has the get/set for serialNumber,uldNumber, and assignedDate in a class

row.key value has

{{
  "serialNumber": "1",
  "uldNumber": "33",
  "assignedDate": "2033-02-17T09:10:38"
}}

my class looks like

 public class abc
    {
        //[JsonProperty("serialNumber")]
        public string SerialNumber { get; set; }

        //[JsonProperty("uldNumber")]
        public string UldNumber { get; set; }

        //[JsonProperty("assignedDate")]
        public DateTime AssignedDate { get; set; }
    }

If I try to deserialize it like so,

 JsonSerializer js = new JsonSerializer();
 _abcList.Add(js.Deserialize<dynamic[]>(row));

I get "cannot convert from 'Couchbase.Views.ViewRow<dynamic>' to 'Newtonsoft.Json.JsonReader"

If i were to do this, row.Key.toString(); , I get exception error of 'Newtonsoft.Json.Linq.JObject'

"cannot convert couchbase.views.viewrow to string "

I have looked at this and this but both of these have not worked.

Body:
When you do an emit statement like this:

emit(doc.content, null);

You're just making the view key doc.content, and leaving the row data null.  You might try this:

emit(doc.content, doc);

This will make the row content the full data in the document.  Alternatively, you can use row.Id to get the document ID and use Read(row.Id) to read the document.  This is slower, but uses less storage space for the view.

Also, you typically don't put JSON object maps in the key.  Normally it's either a single value like a number or string, or an array of values.  Arrays are easier to use for view lookups.


问:
How to convert Mouse Coordinates to local to SubScene in JavaFx 8
I have a main Stage in that I have a scene and that scene contains four SubScene. I want to get the mouse click coordinates local to the scene which is clicked. I know on which scene the mouse has been clicked on because all the scenes are having their individual event listeners but the coordinates i am getting is of the main Scene (of the stage). How do I convert that coordinate to local to scene.

Thanks in advance.

答:
Adding the listeners to the individual subscenes works fine for me:</p>

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.SubScene;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class SubSceneClickTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        GridPane root = new GridPane();
        for (int i = 0 ; i < 4 ; i++) {
            SubScene subScene = new SubScene(new StackPane(), 300, 300);
            subScene.setFill((i + i / 2) % 2 == 0 ? Color.CORNFLOWERBLUE : Color.AQUA);
            String message = "Click on subscene "+i;
            subScene.setOnMouseClicked(e -> System.out.printf("%s [%.1f, %.1f]%n", message, e.getX(), e.getY()));
            root.add(subScene, i / 2, i % 2);
        }
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Body:
Adding the listeners to the individual subscenes works fine for me:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.SubScene;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class SubSceneClickTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        GridPane root = new GridPane();
        for (int i = 0 ; i < 4 ; i++) {
            SubScene subScene = new SubScene(new StackPane(), 300, 300);
            subScene.setFill((i + i / 2) % 2 == 0 ? Color.CORNFLOWERBLUE : Color.AQUA);
            String message = "Click on subscene "+i;
            subScene.setOnMouseClicked(e -> System.out.printf("%s [%.1f, %.1f]%n", message, e.getX(), e.getY()));
            root.add(subScene, i / 2, i % 2);
        }
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


问:
SQL Encryption - Why does the Master Key automatically refer to the Certificate?
I just recently came in touch with MS SQL Encryption, where I used a Master Key, a Certificate and a Symmetric Key.
When I tried to DEcrypt it, I've had quite the hard time getting through the key opening in the right order.
Essentially I wrote something like this:

OPEN MASTER KEY BY PASSWORD ('Password')

OPEN CERTIFICATE BY MASTER KEY

OPEN SYMMETRIC KEY SSN_01 BY CERTIFICATE

which obviously didn't work, and no it's not exactly what I wrote it's just to give you an idea of what I did. Now I eventually figured out that I only needed to open the Master Key and then open the Symmetric Key by the Certificate. My question is why?
Why have the Master Key and the Certificate been automatically linked?

答: Think of it this way: once you have the master key open, when you go to open the symmetric key, SQL Server will say "Hmm… the certificate that protects that is locked. Do I have the means to unlock it?". And, sure enough, it does! Assuming that the certificate's private key is encrypted with the database master key, of course You can check sys.key_encryptions to see what encrypts/protects what and sys.openkeys to see what keys you have open in this session.


问:
Search text file and return values after equal sign
I am reading in a file and want to return certain values after the equal sign

The text file looks like this

```<code>slicenum=1
imageWidth=100
ID=1
</code>```

etc. and then repeats for each slice of the image

For now, I am focusing on ID, but eventually I want to have an array I guess of all the values I want to extract.

When I do this, it just prints the whole file. How do I print just the value after the equals sign of the ID?

```<code>string ID;
string line;
while (getline(inFile, line)) {
        if (line.find(ID) != string::npos)
            cout << line << std::endl;
}
</code>```

答:
Use std::string::substr and std::string::find

```<code>const size_t pos = line.find('=');
if (pos != std::string::npos) {
    std::cout << line.substr(pos + 1);
}
</code>```

Body:
I am reading in a file and want to return certain values after the equal sign

The text file looks like this

slicenum=1
imageWidth=100
ID=1

etc. and then repeats for each slice of the image

For now, I am focusing on ID, but eventually I want to have an array I guess of all the values I want to extract.

When I do this, it just prints the whole file. How do I print just the value after the equals sign of the ID?

string ID;
string line;
while (getline(inFile, line)) {
        if (line.find(ID) != string::npos)
            cout << line << std::endl;
}

Body:
Use std::string::substr and std::string::find

const size_t pos = line.find('=');
if (pos != std::string::npos) {
    std::cout << line.substr(pos + 1);
}


问:
Redux: Notify parent React component when the child component dispatches a Redux action
My parent component is a React class that has a method in it which does a setInterval (amongst other things). This interval is cleared when some conditions are met.

However I want this method on the parent React class to be called once again when one of it's children dispatches a specific action (thereby re-setting the setInterval).

How do I notify the parent that the child had dispatched a certain (Redux) action? I'm using connect to pass the state down. So the parent and the children share the same dispatch method.

答: Not sure if that would be the optimal solution for your problem, but how about passing down a callback to the child component and dispatching the redux action from the parent? You would be able to clear the interval there too.</p>


问:
Class vs Struct for data only?
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)

```<code>class Foo {
private:
   struct Pos { int x, y, z };
public:
   Pos Position;
};
</code>```

Versus:

```<code>struct Foo {
   struct Pos { int x, y, z } Pos;
};
</code>```

Similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++?

When should I use a struct instead of a class?

答:
"(note: it will only hold variables, there will never be functions)"

Never is a big word.  Usually "never" means "eventually".  Since that's the case, I'd suggest you use a class.  That way, when things change, you don't have so much to change.

The Java (and Python) folks have gotten along fine with everything being a class.   It hasn't hurt them any to not have these specialized method-less classes that C++ calls a "struct".

OwnerDisplayName: Daniel

Title: Class vs Struct for data only?

Body:
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)

class Foo {
private:
   struct Pos { int x, y, z };
public:
   Pos Position;
};

Versus:

struct Foo {
   struct Pos { int x, y, z } Pos;
};

Similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++?

When should I use a struct instead of a class?

LastEditorDisplayName: dmckee


问:
Application works when started locally or from mapped network drive but not from UNC path

Short story

I have a weird problem and couldn't find any solution for it across internet.

This is probably not important for a problem but I prefer to mention that I had two separate projects and decided to combine them into one solution. Both projects were/are simple winform application. They worked separately after compiling: directly in Visual Studio during debugging (no matter in debug or release mode), locally outside debugger and after copying them into some folder on local network.

However after merging them, one of the application stopped working when it is started from the network.

Stop working means?

I attached debugger to the already running process and found out that:

Code in frmMain.Designer.vb in Partial Class frmMain in Private Sub InitializeComponent() works properly. This is checked by making a breakpoint at the begin of Sub and going step-by-step through the code until End Sub.

Code in frmMain.vb in Public Class frmMain in Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load is not triggered. After going out from InitializeComponent() (point 1) code does not enter frmMain_Load. Main form is shown on the screen with all controls but not initialized/cleaned, without icon etc.

Clicking some buttons on main form allows me to open child forms but they are also not initialized/cleaned.

Closing child form by clicking on "X" doesn't close the form (normally does). Clicking on cmdClose button on the same child form closes the form. Button has DialogResult property set to Cancel. Form itself has CancelButton property set to cmdClose. Pressing ESC also closes the form.

```<code>Private Sub cmdClose_Click(sender As Object, e As EventArgs) Handles cmdClose.Click
    Me.Dispose()
End Sub
</code>```

Closing the main form (no matter if by "X", cmdClose button or ESC) hangs up the application.

```<code>Private Sub cmdClose_Click(sender As Object, e As EventArgs) Handles cmdClose.Click
    Me.Close()
End Sub
</code>```

If I open Windows Explorer and go to the final location of application on shared network drive starting from the mapped drive Y:\folder and start application from there - it works.

However if choose the same final destination through \\server\share-name\folder and start application from there - it doesn't work.

Point 6 and 7 acts the same if application is started by a shortcut on desktop and in this shortcut target path to application is defined in one of the two methods.

Windows 7, .Net Framework 4.5.

Do you have any clue how to solve it and where the bug is?

答:
Explanation of error

I decided to extract the icon from application executable instead of resource like it was before to avoid adding two times the same icon file to the executable: first as an application icon which is added in Project/Properties/Application/Icon and second as an form icon added in Project/Properties/Resources.

The problem is if in any place in code (in my example in Private Sub form_Load(sender As Object, e As EventArgs) Handles MyBase.Load) you add

```<code>Me.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location)
</code>```

it will not work with UNC paths returning

```<code>System.ArgumentException
The filePath does not indicate a valid file or the filePath indicates a Universal Naming Convention (UNC) path.
</code>```

Error occurs in runtime after form closing. Method

```<code>Assembly.GetExecutingAssembly().Location
</code>```

returns correct path (as string for example \\server\share-name\folder) but method

```<code>Public Shared Function ExtractAssociatedIcon(filePath As String) As Icon
</code>```

does not accept UNC path.

Solution

To solve this issue 2 clumsy solutions are proposed here and here.

Body:
Short story

I have a weird problem and couldn't find any solution for it across internet.

This is probably not important for a problem but I prefer to mention that I had two separate projects and decided to combine them into one solution. Both projects were/are simple winform application. They worked separately after compiling: directly in Visual Studio during debugging (no matter in debug or release mode), locally outside debugger and after copying them into some folder on local network.

However after merging them, one of the application stopped working when it is started from the network.

Stop working means?

I attached debugger to the already running process and found out that:

Code in frmMain.Designer.vb in Partial Class frmMain in Private Sub InitializeComponent() works properly. This is checked by making a breakpoint at the begin of Sub and going step-by-step through the code until End Sub.

Code in frmMain.vb in Public Class frmMain in Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load is not triggered. After going out from InitializeComponent() (point 1) code does not enter frmMain_Load. Main form is shown on the screen with all controls but not initialized/cleaned, without icon etc.

Clicking some buttons on main form allows me to open child forms but they are also not initialized/cleaned.

Closing child form by clicking on "X" doesn't close the form (normally does). Clicking on cmdClose button on the same child form closes the form. Button has DialogResult property set to Cancel. Form itself has CancelButton property set to cmdClose. Pressing ESC also closes the form.

Private Sub cmdClose_Click(sender As Object, e As EventArgs) Handles cmdClose.Click
    Me.Dispose()
End Sub

Closing the main form (no matter if by "X", cmdClose button or ESC) hangs up the application.

Private Sub cmdClose_Click(sender As Object, e As EventArgs) Handles cmdClose.Click
    Me.Close()
End Sub

If I open Windows Explorer and go to the final location of application on shared network drive starting from the mapped drive Y:\folder and start application from there - it works.

However if choose the same final destination through \\server\share-name\folder and start application from there - it doesn't work.

Point 6 and 7 acts the same if application is started by a shortcut on desktop and in this shortcut target path to application is defined in one of the two methods.

Windows 7, .Net Framework 4.5.

Do you have any clue how to solve it and where the bug is?

Body:
Explanation of error

I decided to extract the icon from application executable instead of resource like it was before to avoid adding two times the same icon file to the executable: first as an application icon which is added in Project/Properties/Application/Icon and second as an form icon added in Project/Properties/Resources.

The problem is if in any place in code (in my example in Private Sub form_Load(sender As Object, e As EventArgs) Handles MyBase.Load) you add

Me.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location)

it will not work with UNC paths returning

System.ArgumentException
The filePath does not indicate a valid file or the filePath indicates a Universal Naming Convention (UNC) path.

Error occurs in runtime after form closing. Method

Assembly.GetExecutingAssembly().Location

returns correct path (as string for example \\server\share-name\folder) but method

Public Shared Function ExtractAssociatedIcon(filePath As String) As Icon

does not accept UNC path.

Solution

To solve this issue 2 clumsy solutions are proposed here and here.


问:
Resize/scale entire canvas with all objects in fabricjs without loss of quality
Is there way how to scale/resize entire canvas made in fabric.js ? I have <canvas className="canvas" ref="canvas" width="895" height="560"></canvas> then const canvas = new fabric.Canvas(this.refs.canvas),can i change width and height of canvas element and all objects inside ??

答:
This question has been answered many times.
The best answer on my opinion provided by one of fabricjs contributors Andrea Bogazzi here: https://stackoverflow.com/a/35019311/3710047

Basically, you can use fabricjs canvas methods:

```<code>canvas.setZoom(val);
canvas.setWidth(originalWidth * canvas.getZoom());
canvas.setHeight(originalHeight * canvas.getZoom());
</code>```

Body:
This question has been answered many times.
The best answer on my opinion provided by one of fabricjs contributors Andrea Bogazzi here: https://stackoverflow.com/a/35019311/3710047

Basically, you can use fabricjs canvas methods:

canvas.setZoom(val);
canvas.setWidth(originalWidth * canvas.getZoom());
canvas.setHeight(originalHeight * canvas.getZoom());


问:
Finding out where analytics should be defined
I am working with Google Analytics api in python and keep getting the error

```<code>NameError: name 'analytics' is not defined.
</code>```

I have been searching for several days on the analytics api site and on StackOverflow for the answer. If someone could please point me in the direction of the right documentation or help me out here that would be greatly appreciated. Attached is the code that I have so far.

```<code>from apiclient.http import MediaFileUpload
from apiclient.errors import HttpError

try:
  media = MediaFileUpload('Bing_Ad_Test.csv',
                          mimetype='application/octet-stream',
                          resumable=False)
  daily_upload = analytics.management().uploads().uploadData(
      accountId='',
      webPropertyId='',
      customDataSourceId='',
      media_body=media).execute()

except TypeError, error:
  # Handle errors in constructing a query.
  print 'There was an error in constructing your query : %s' % error

except HttpError, error:
  # Handle API errors.
  print ('There was an API error : %s : %s' %
         (error.resp.status, error.resp.reason))
</code>```

答:
The script that you are using assumes that you have already authenticated and created a service.  Before you can run this script, you need to build the service object.  See this example:</p>

```<code>import argparse

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from apiclient.http import MediaFileUpload

# SET VARS
SERVICE_ACCOUNT_EMAIL='XXX'
CUSTOM_DATA_SOURCE_ID='XXX'
WEB_PROPERTY_ID='XXX'
ACCOUNT_ID='XXX'
CSV_IMPORT_FILE_LOCATION='XXX'
CREDENTIALS_KEY_FILE_LOCATION='XXX'

def get_service(api_name, api_version, scope, key_file_location,
                service_account_email):

  credentials = ServiceAccountCredentials.from_p12_keyfile(
    service_account_email, key_file_location, scopes=scope)

  http = credentials.authorize(httplib2.Http())

  # Build the service object.
  service = build(api_name, api_version, http=http)

  return service

def uploadCSV(service):
  try:
    media = MediaFileUpload(CSV_IMPORT_FILE_LOCATION,
                          mimetype='application/octet-stream',
                          resumable=False)
    daily_upload = service.management().uploads().uploadData(
        accountId=ACCOUNT_ID,
        webPropertyId=WEB_PROPERTY_ID,
        customDataSourceId=CUSTOM_DATA_SOURCE_ID,
        media_body=media).execute()

  except TypeError, error:
    # Handle errors in constructing a query.
    print 'There was an error in constructing your query : %s' % error

def main():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.edit','https://www.googleapis.com/auth/analytics']

  # Authenticate and construct service.
  service = get_service('analytics', 'v3', scope, CREDENTIALS_KEY_FILE_LOCATION,
    SERVICE_ACCOUNT_EMAIL)

  # Upload CSV Data
  uploadCSV(service)

if __name__ == '__main__':
  main()
</code>```

Body:
I am working with Google Analytics api in python and keep getting the error

NameError: name 'analytics' is not defined.

I have been searching for several days on the analytics api site and on StackOverflow for the answer. If someone could please point me in the direction of the right documentation or help me out here that would be greatly appreciated. Attached is the code that I have so far.

from apiclient.http import MediaFileUpload
from apiclient.errors import HttpError

try:
  media = MediaFileUpload('Bing_Ad_Test.csv',
                          mimetype='application/octet-stream',
                          resumable=False)
  daily_upload = analytics.management().uploads().uploadData(
      accountId='',
      webPropertyId='',
      customDataSourceId='',
      media_body=media).execute()

except TypeError, error:
  # Handle errors in constructing a query.
  print 'There was an error in constructing your query : %s' % error

except HttpError, error:
  # Handle API errors.
  print ('There was an API error : %s : %s' %
         (error.resp.status, error.resp.reason))

Body:
The script that you are using assumes that you have already authenticated and created a service.  Before you can run this script, you need to build the service object.  See this example:

import argparse

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

import httplib2
from oauth2client import client
from oauth2client import file
from oauth2client import tools
from apiclient.http import MediaFileUpload

# SET VARS
SERVICE_ACCOUNT_EMAIL='XXX'
CUSTOM_DATA_SOURCE_ID='XXX'
WEB_PROPERTY_ID='XXX'
ACCOUNT_ID='XXX'
CSV_IMPORT_FILE_LOCATION='XXX'
CREDENTIALS_KEY_FILE_LOCATION='XXX'

def get_service(api_name, api_version, scope, key_file_location,
                service_account_email):

  credentials = ServiceAccountCredentials.from_p12_keyfile(
    service_account_email, key_file_location, scopes=scope)

  http = credentials.authorize(httplib2.Http())

  # Build the service object.
  service = build(api_name, api_version, http=http)

  return service

def uploadCSV(service):
  try:
    media = MediaFileUpload(CSV_IMPORT_FILE_LOCATION,
                          mimetype='application/octet-stream',
                          resumable=False)
    daily_upload = service.management().uploads().uploadData(
        accountId=ACCOUNT_ID,
        webPropertyId=WEB_PROPERTY_ID,
        customDataSourceId=CUSTOM_DATA_SOURCE_ID,
        media_body=media).execute()

  except TypeError, error:
    # Handle errors in constructing a query.
    print 'There was an error in constructing your query : %s' % error

def main():
  # Define the auth scopes to request.
  scope = ['https://www.googleapis.com/auth/analytics.edit','https://www.googleapis.com/auth/analytics']

  # Authenticate and construct service.
  service = get_service('analytics', 'v3', scope, CREDENTIALS_KEY_FILE_LOCATION,
    SERVICE_ACCOUNT_EMAIL)

  # Upload CSV Data
  uploadCSV(service)

if __name__ == '__main__':
  main()


问:
No values in POST method's parameters
I have REST web services POST method:

```<code>public string Post([FromBody]string value1 )
{
    return "a";
}
</code>```

I have placed breakpoint inside of it. I have sent POST:

```<code>localhost/RESTServer/api/Person/?value1=1
</code>```

I get null in value1 inside of Post method. What I do wrong?

答:
I see you are just learning WebApi I recommend you this page: http://csharp-video-tutorials.blogspot.mx/2016/09/aspnet-web-api-tutorial-for-beginners.html by far the best tutorial out there.

Also about your problem :

Your post request should look something like this, if you intend to use Post

Title: No values in POST method's parameters

Body:
I have REST web services POST method:

public string Post([FromBody]string value1 )
{
    return "a";
}

I have placed breakpoint inside of it. I have sent POST:

localhost/RESTServer/api/Person/?value1=1

I get null in value1 inside of Post method. What I do wrong?