问:
error TS2300: Duplicate identifier 'PropertyKey' in node_modules/@types/core-js/index.d.ts
I have these errors in node_modules/@types/core-js/index.d.ts in Visual Studio Code IDE:

When I run npm start to serve the app, I get:

```<code>    node_modules/@types/core-js/index.d.ts(21,14): error TS2300: Duplicate identifier 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(85,5): error TS2687: All declarations of 'name' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(145,5): error TS2403: Subsequent variable declarations must have the same type.  Variable '[Symbol.unscopables]' must be of type '{ copyWithin: boolean; entries: boolean; fill: boolean; find: boolean; findIndex: boolean; keys: ...', but here has type 'any'.
node_modules/@types/core-js/index.d.ts(262,5): error TS2687: All declarations of 'flags' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(276,5): error TS2687: All declarations of 'EPSILON' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(311,5): error TS2687: All declarations of 'MAX_SAFE_INTEGER' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(318,5): error TS2687: All declarations of 'MIN_SAFE_INTEGER' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(457,5): error TS2403: Subsequent variable declarations must have the same type.  Variable '[Symbol.toStringTag]' must be of type '"Symbol"', but here has type 'string'.
node_modules/@types/core-js/index.d.ts(457,5): error TS2687: All declarations of '[Symbol.toStringTag]' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(464,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(492,5): error TS2687: All declarations of 'hasInstance' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(498,5): error TS2687: All declarations of 'isConcatSpreadable' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(504,5): error TS2687: All declarations of 'iterator' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(510,5): error TS2687: All declarations of 'match' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(516,5): error TS2687: All declarations of 'replace' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(522,5): error TS2687: All declarations of 'search' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(528,5): error TS2687: All declarations of 'species' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(534,5): error TS2687: All declarations of 'split' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(540,5): error TS2687: All declarations of 'toPrimitive' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(546,5): error TS2687: All declarations of 'toStringTag' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(552,5): error TS2687: All declarations of 'unscopables' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(609,5): error TS2403: Subsequent variable declarations must have the same type.  Variable '[Symbol.toStringTag]' must be of type '"Math"', but here has type 'string'.
node_modules/@types/core-js/index.d.ts(609,5): error TS2687: All declarations of '[Symbol.toStringTag]' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(613,5): error TS2403: Subsequent variable declarations must have the same type.  Variable '[Symbol.toStringTag]' must be of type '"JSON"', but here has type 'string'.
node_modules/@types/core-js/index.d.ts(613,5): error TS2687: All declarations of '[Symbol.toStringTag]' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(628,5): error TS2687: All declarations of 'size' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(634,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(645,5): error TS2687: All declarations of 'size' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(651,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(666,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(680,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(692,5): error TS2687: All declarations of 'value' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(804,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/typescript/lib/lib.es2015.core.d.ts(17,14): error TS2300: Duplicate identifier 'PropertyKey'.
</code>```

Here is my tsconfig.json:

```<code>    {
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "lib": ["es2015", "dom"],
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "outDir":"js/app/",
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
    "exclude": [
    "node_modules",
    "app/test"
  ]
}
</code>```

my package.json

```<code>    {
  "name": "vepo",
  "version": "1.0.0",
  "scripts": {
    "coverage": "istanbul cover ./test.js",
    "lite-server-test": "lite-server --config=liteserver-test-config.json",
    "test": "karma start karma.config.js",
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" \"sass --watch app\" \"sass --watch index.scss\" \"sass --watch global-constants.scss\" ",
    "lite": "lite-server",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "bin":{
    "e2e-test-start": "bin/e2e-test-start.js"
},
  "license": "ISC",
  "moduleResolution": "node",
  "dependencies": {
    "@angular/common": "~2.2.0",
    "@angular/compiler": "~2.2.0",
    "@angular/core": "~2.2.0",
    "@angular/forms": "~2.2.0",
    "@angular/http": "~2.2.0",
    "@angular/platform-browser": "~2.2.0",
    "@angular/platform-browser-dynamic": "~2.2.0",
    "@angular/router": "~3.2.0",
    "@angular/upgrade": "~2.2.0",
    "@types/bootstrap": "^3.3.32",
    "@types/core-js": "^0.9.34",
    "@types/google-maps": "^3.1.28",
    "@types/jasmine": "^2.5.38",
    "@types/jquery": "^2.0.34",
    "@types/node": "^6.0.51",
    "angular-in-memory-web-api": "~0.1.15",
    "angular2-google-maps": "^0.15.0",
    "angular2-modal": "^2.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "jquery": "v3.1.1",
    "jshint": "^2.9.4",
    "ng2-bs3-modal": "^0.10.4",
    "ng2-popover": "0.0.9",
    "protractor": "4.0.11",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.39",
    "tslint": "^4.0.2",
    "zone.js": "^0.6.25"
  },
  "devDependencies": {
    "@types/google-maps": "^3.1.28",
    "angular-mocks": "^1.5.8",
    "codelyzer": "1.0.0-beta.0",
    "concurrently": "^3.0.0",
    "core-js": "^2.4.1",
    "del": "latest",
    "gulp": "^3.9.1",
    "gulp-changed": "^1.3.2",
    "gulp-concat": "^2.6.1",
    "gulp-imagemin": "^3.1.1",
    "gulp-jshint": "^2.0.4",
    "gulp-minify-html": "^1.0.6",
    "gulp-sass": "latest",
    "gulp-sourcemaps": "latest",
    "gulp-strip-debug": "^1.1.0",
    "gulp-tslint": "latest",
    "gulp-typescript": "latest",
    "gulp-uglify": "^2.0.0",
    "istanbul": "^0.4.5",
    "jasmine": "~2.4.1",
    "karma": "latest",
    "karma-chrome-launcher": "latest",
    "karma-cli": "^1.0.1",
    "karma-coverage": "latest",
    "karma-htmlfile-reporter": "^0.3.4",
    "karma-jasmine": "latest",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-mocha-reporter": "latest",
    "karma-phantomjs2-launcher": "latest",
    "karma-story-reporter": "latest",
    "lite-server": "latest",
    "path": "latest",
    "phantomjs2": "latest",
    "protractor-jasmine2-html-reporter": "0.0.6",
    "require-dir": "latest",
    "systemjs-builder": "latest",
    "tslint": "latest",
    "typescript": "latest"
  }
}
</code>```

How do I resolve this?

**EDIT: I used to use typings for .d.ts files but i moved on to @types. I also updated my npm and node to try to fix the problem from this:

```<code>{ app: '1.0.0',
  npm: '3.10.8',
  ares: '1.10.1-DEV',
  http_parser: '2.7.0',
  icu: '57.1',
  modules: '48',
  node: '5.something',
  openssl: '1.0.2j',
  uv: '1.9.1',
  v8: '5.1.281.84',
  zlib: '1.2.8' }
</code>```

to this:

```<code>{ app: '1.0.0',
  npm: '4.0.2',
  ares: '1.10.1-DEV',
  http_parser: '2.7.0',
  icu: '57.1',
  modules: '48',
  node: '6.9.1',
  openssl: '1.0.2j',
  uv: '1.9.1',
  v8: '5.1.281.84',
  zlib: '1.2.8' }
</code>```

npm-debug.log:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'start' ]
2 info using npm@4.0.2
3 info using node@v6.9.1
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle vepo@1.0.0~prestart: vepo@1.0.0
6 silly lifecycle vepo@1.0.0~prestart: no script for prestart, continuing
7 info lifecycle vepo@1.0.0~start: vepo@1.0.0
8 verbose lifecycle vepo@1.0.0~start: unsafe-perm in lifecycle true
9 verbose lifecycle vepo@1.0.0~start: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/Ben/Development/vepo/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
10 verbose lifecycle vepo@1.0.0~start: CWD: /Users/Ben/Development/vepo
11 silly lifecycle vepo@1.0.0~start: Args: [ '-c',
11 silly lifecycle   'tsc && concurrently "npm run tsc:w" "npm run lite" "sass --watch app" "sass --watch index.scss" "sass --watch global-constants.scss" ' ]
12 silly lifecycle vepo@1.0.0~start: Returned: code: 2  signal: null
13 info lifecycle vepo@1.0.0~start: Failed to exec start script
14 verbose stack Error: vepo@1.0.0 start: `tsc && concurrently "npm run tsc:w" "npm run lite" "sass --watch app" "sass --watch index.scss" "sass --watch global-constants.scss" `
14 verbose stack Exit status 2
14 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:279:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:191:7)
14 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:191:7)
14 verbose stack     at maybeClose (internal/child_process.js:877:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid vepo@1.0.0
16 verbose cwd /Users/Ben/Development/vepo
17 error Darwin 16.1.0
18 error argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
19 error node v6.9.1
20 error npm  v4.0.2
21 error code ELIFECYCLE
22 error vepo@1.0.0 start: `tsc && concurrently "npm run tsc:w" "npm run lite" "sass --watch app" "sass --watch index.scss" "sass --watch global-constants.scss" `
22 error Exit status 2
23 error Failed at the vepo@1.0.0 start script 'tsc && concurrently "npm run tsc:w" "npm run lite" "sass --watch app" "sass --watch index.scss" "sass --watch global-constants.scss" '.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the vepo package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error     tsc && concurrently "npm run tsc:w" "npm run lite" "sass --watch app" "sass --watch index.scss" "sass --watch global-constants.scss"
23 error You can get information on how to open an issue for this project with:
23 error     npm bugs vepo
23 error Or if that isn't available, you can get their info via:
23 error     npm owner ls vepo
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]
</code>```

答: Upgrading "@types/core-js": "0.9.34" to version 0.9.39 worked for me.

Body:
I have these errors in node_modules/@types/core-js/index.d.ts in Visual Studio Code IDE:

When I run npm start to serve the app, I get:

    node_modules/@types/core-js/index.d.ts(21,14): error TS2300: Duplicate identifier 'PropertyKey'.
node_modules/@types/core-js/index.d.ts(85,5): error TS2687: All declarations of 'name' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(145,5): error TS2403: Subsequent variable declarations must have the same type.  Variable '[Symbol.unscopables]' must be of type '{ copyWithin: boolean; entries: boolean; fill: boolean; find: boolean; findIndex: boolean; keys: ...', but here has type 'any'.
node_modules/@types/core-js/index.d.ts(262,5): error TS2687: All declarations of 'flags' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(276,5): error TS2687: All declarations of 'EPSILON' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(311,5): error TS2687: All declarations of 'MAX_SAFE_INTEGER' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(318,5): error TS2687: All declarations of 'MIN_SAFE_INTEGER' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(457,5): error TS2403: Subsequent variable declarations must have the same type.  Variable '[Symbol.toStringTag]' must be of type '"Symbol"', but here has type 'string'.
node_modules/@types/core-js/index.d.ts(457,5): error TS2687: All declarations of '[Symbol.toStringTag]' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(464,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(492,5): error TS2687: All declarations of 'hasInstance' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(498,5): error TS2687: All declarations of 'isConcatSpreadable' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(504,5): error TS2687: All declarations of 'iterator' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(510,5): error TS2687: All declarations of 'match' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(516,5): error TS2687: All declarations of 'replace' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(522,5): error TS2687: All declarations of 'search' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(528,5): error TS2687: All declarations of 'species' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(534,5): error TS2687: All declarations of 'split' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(540,5): error TS2687: All declarations of 'toPrimitive' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(546,5): error TS2687: All declarations of 'toStringTag' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(552,5): error TS2687: All declarations of 'unscopables' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(609,5): error TS2403: Subsequent variable declarations must have the same type.  Variable '[Symbol.toStringTag]' must be of type '"Math"', but here has type 'string'.
node_modules/@types/core-js/index.d.ts(609,5): error TS2687: All declarations of '[Symbol.toStringTag]' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(613,5): error TS2403: Subsequent variable declarations must have the same type.  Variable '[Symbol.toStringTag]' must be of type '"JSON"', but here has type 'string'.
node_modules/@types/core-js/index.d.ts(613,5): error TS2687: All declarations of '[Symbol.toStringTag]' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(628,5): error TS2687: All declarations of 'size' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(634,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(645,5): error TS2687: All declarations of 'size' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(651,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(666,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(680,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(692,5): error TS2687: All declarations of 'value' must have identical modifiers.
node_modules/@types/core-js/index.d.ts(804,5): error TS2687: All declarations of 'prototype' must have identical modifiers.
node_modules/typescript/lib/lib.es2015.core.d.ts(17,14): error TS2300: Duplicate identifier 'PropertyKey'.

Here is my tsconfig.json:

    {
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "lib": ["es2015", "dom"],
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "outDir":"js/app/",
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
    "exclude": [
    "node_modules",
    "app/test"
  ]
}

my package.json

    {
  "name": "vepo",
  "version": "1.0.0",
  "scripts": {
    "coverage": "istanbul cover ./test.js",
    "lite-server-test": "lite-server --config=liteserver-test-config.json",
    "test": "karma start karma.config.js",
    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" \"sass --watch app\" \"sass --watch index.scss\" \"sass --watch global-constants.scss\" ",
    "lite": "lite-server",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "bin":{
    "e2e-test-start": "bin/e2e-test-start.js"
},
  "license": "ISC",
  "moduleResolution": "node",
  "dependencies": {
    "@angular/common": "~2.2.0",
    "@angular/compiler": "~2.2.0",
    "@angular/core": "~2.2.0",
    "@angular/forms": "~2.2.0",
    "@angular/http": "~2.2.0",
    "@angular/platform-browser": "~2.2.0",
    "@angular/platform-browser-dynamic": "~2.2.0",
    "@angular/router": "~3.2.0",
    "@angular/upgrade": "~2.2.0",
    "@types/bootstrap": "^3.3.32",
    "@types/core-js": "^0.9.34",
    "@types/google-maps": "^3.1.28",
    "@types/jasmine": "^2.5.38",
    "@types/jquery": "^2.0.34",
    "@types/node": "^6.0.51",
    "angular-in-memory-web-api": "~0.1.15",
    "angular2-google-maps": "^0.15.0",
    "angular2-modal": "^2.0.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "jquery": "v3.1.1",
    "jshint": "^2.9.4",
    "ng2-bs3-modal": "^0.10.4",
    "ng2-popover": "0.0.9",
    "protractor": "4.0.11",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.39",
    "tslint": "^4.0.2",
    "zone.js": "^0.6.25"
  },
  "devDependencies": {
    "@types/google-maps": "^3.1.28",
    "angular-mocks": "^1.5.8",
    "codelyzer": "1.0.0-beta.0",
    "concurrently": "^3.0.0",
    "core-js": "^2.4.1",
    "del": "latest",
    "gulp": "^3.9.1",
    "gulp-changed": "^1.3.2",
    "gulp-concat": "^2.6.1",
    "gulp-imagemin": "^3.1.1",
    "gulp-jshint": "^2.0.4",
    "gulp-minify-html": "^1.0.6",
    "gulp-sass": "latest",
    "gulp-sourcemaps": "latest",
    "gulp-strip-debug": "^1.1.0",
    "gulp-tslint": "latest",
    "gulp-typescript": "latest",
    "gulp-uglify": "^2.0.0",
    "istanbul": "^0.4.5",
    "jasmine": "~2.4.1",
    "karma": "latest",
    "karma-chrome-launcher": "latest",
    "karma-cli": "^1.0.1",
    "karma-coverage": "latest",
    "karma-htmlfile-reporter": "^0.3.4",
    "karma-jasmine": "latest",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-mocha-reporter": "latest",
    "karma-phantomjs2-launcher": "latest",
    "karma-story-reporter": "latest",
    "lite-server": "latest",
    "path": "latest",
    "phantomjs2": "latest",
    "protractor-jasmine2-html-reporter": "0.0.6",
    "require-dir": "latest",
    "systemjs-builder": "latest",
    "tslint": "latest",
    "typescript": "latest"
  }
}

How do I resolve this?

**EDIT: I used to use typings for .d.ts files but i moved on to @types. I also updated my npm and node to try to fix the problem from this:

{ app: '1.0.0',
  npm: '3.10.8',
  ares: '1.10.1-DEV',
  http_parser: '2.7.0',
  icu: '57.1',
  modules: '48',
  node: '5.something',
  openssl: '1.0.2j',
  uv: '1.9.1',
  v8: '5.1.281.84',
  zlib: '1.2.8' }

to this:

{ app: '1.0.0',
  npm: '4.0.2',
  ares: '1.10.1-DEV',
  http_parser: '2.7.0',
  icu: '57.1',
  modules: '48',
  node: '6.9.1',
  openssl: '1.0.2j',
  uv: '1.9.1',
  v8: '5.1.281.84',
  zlib: '1.2.8' }

npm-debug.log:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'start' ]
2 info using npm@4.0.2
3 info using node@v6.9.1
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle vepo@1.0.0~prestart: vepo@1.0.0
6 silly lifecycle vepo@1.0.0~prestart: no script for prestart, continuing
7 info lifecycle vepo@1.0.0~start: vepo@1.0.0
8 verbose lifecycle vepo@1.0.0~start: unsafe-perm in lifecycle true
9 verbose lifecycle vepo@1.0.0~start: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/Ben/Development/vepo/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
10 verbose lifecycle vepo@1.0.0~start: CWD: /Users/Ben/Development/vepo
11 silly lifecycle vepo@1.0.0~start: Args: [ '-c',
11 silly lifecycle   'tsc && concurrently "npm run tsc:w" "npm run lite" "sass --watch app" "sass --watch index.scss" "sass --watch global-constants.scss" ' ]
12 silly lifecycle vepo@1.0.0~start: Returned: code: 2  signal: null
13 info lifecycle vepo@1.0.0~start: Failed to exec start script
14 verbose stack Error: vepo@1.0.0 start: `tsc && concurrently "npm run tsc:w" "npm run lite" "sass --watch app" "sass --watch index.scss" "sass --watch global-constants.scss" `
14 verbose stack Exit status 2
14 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:279:16)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at EventEmitter.emit (events.js:191:7)
14 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
14 verbose stack     at emitTwo (events.js:106:13)
14 verbose stack     at ChildProcess.emit (events.js:191:7)
14 verbose stack     at maybeClose (internal/child_process.js:877:16)
14 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid vepo@1.0.0
16 verbose cwd /Users/Ben/Development/vepo
17 error Darwin 16.1.0
18 error argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
19 error node v6.9.1
20 error npm  v4.0.2
21 error code ELIFECYCLE
22 error vepo@1.0.0 start: `tsc && concurrently "npm run tsc:w" "npm run lite" "sass --watch app" "sass --watch index.scss" "sass --watch global-constants.scss" `
22 error Exit status 2
23 error Failed at the vepo@1.0.0 start script 'tsc && concurrently "npm run tsc:w" "npm run lite" "sass --watch app" "sass --watch index.scss" "sass --watch global-constants.scss" '.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the vepo package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error     tsc && concurrently "npm run tsc:w" "npm run lite" "sass --watch app" "sass --watch index.scss" "sass --watch global-constants.scss"
23 error You can get information on how to open an issue for this project with:
23 error     npm bugs vepo
23 error Or if that isn't available, you can get their info via:
23 error     npm owner ls vepo
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]


来源: stackexchange

问:
Gridview, Autogenerated Column, Checkbox Column Editable
I have a gridview binded to a datasource.

```<code> <asp:GridView ID="DocumentReviewGrid" runat="server" AllowPaging="True" AllowSorting="True"
                    EnableModelValidation="True" Width="100%" BorderStyle="None"
                    CssClass="docnav_data" BorderWidth="1px" GridLines="None" DataSourceID="DocumentReviewDataSource"
                    HorizontalAlign="Left" OnRowDataBound="DocumentReviewGrid_RowDataBound"
                    OnRowCreated="DocumentReviewGrid_RowCreated" CellSpacing="5"
                    PageSize="20" OnPageIndexChanged="DocumentReviewGrid_PageIndexChanged">
                    <AlternatingRowStyle BackColor="#EBF2F9" BorderStyle="None" />
                    <FooterStyle HorizontalAlign="Left" />
                    <HeaderStyle BackColor="#E7E7E7" HorizontalAlign="Left" />
                    <PagerSettings Mode="NumericFirstLast" Position="Top" PageButtonCount="4" />
                    <PagerStyle HorizontalAlign="Center" />
                </asp:GridView>
</code>```

As you can see Autogenerated Column is set to true, and it must be kept like that. One of the column is a SQL bit value, so it's represented as checkbox. I would like to be able to edit the checkbox column only, without using "AutoGenerateEditButton" property. I would just like to:

be able to check/uncheck the checkbox (I am stuck here)

performing a single update using an external button

the other columns must be readonly

答:
Autogenerated columns cannot be manipulated directly in pretty much anyway, so there is no simple way to do it. So what you could do is create a custom column, which will always come first before any auto generated columns (again, this behavior cannot be changed), and hide the auto generated bit column.

How to hide the column is described here. Essentially you cannot use Columns collection, so need to do this:

```<code>protected void DocumentReviewGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[X].Visible = false; // hides the first column
}
</code>```

Here X is the 0-based index of the column to hide.

And now to prepend the column just define it the way you want, leaving AutoGenerateColumns="true":

```<code><asp:GridView ID="DocumentReviewGrid"...>
    <Columns>
        <asp:CheckBoxField HeaderText="Esclusione" DataField="Esclusione" />
    </Columns>
</asp:GridView>
</code>```

Admittedly this is quite hackish, but that will get you almost where you want - bool column displayed and editable.

ContentLicense: CC BY-SA 3.0

Body:
I have a gridview binded to a datasource.

 <asp:GridView ID="DocumentReviewGrid" runat="server" AllowPaging="True" AllowSorting="True"
                    EnableModelValidation="True" Width="100%" BorderStyle="None"
                    CssClass="docnav_data" BorderWidth="1px" GridLines="None" DataSourceID="DocumentReviewDataSource"
                    HorizontalAlign="Left" OnRowDataBound="DocumentReviewGrid_RowDataBound"
                    OnRowCreated="DocumentReviewGrid_RowCreated" CellSpacing="5"
                    PageSize="20" OnPageIndexChanged="DocumentReviewGrid_PageIndexChanged">
                    <AlternatingRowStyle BackColor="#EBF2F9" BorderStyle="None" />
                    <FooterStyle HorizontalAlign="Left" />
                    <HeaderStyle BackColor="#E7E7E7" HorizontalAlign="Left" />
                    <PagerSettings Mode="NumericFirstLast" Position="Top" PageButtonCount="4" />
                    <PagerStyle HorizontalAlign="Center" />
                </asp:GridView>

As you can see Autogenerated Column is set to true, and it must be kept like that. One of the column is a SQL bit value, so it's represented as checkbox. I would like to be able to edit the checkbox column only, without using "AutoGenerateEditButton" property. I would just like to:

be able to check/uncheck the checkbox (I am stuck here)

performing a single update using an external button

the other columns must be readonly

Body:
Autogenerated columns cannot be manipulated directly in pretty much anyway, so there is no simple way to do it. So what you could do is create a custom column, which will always come first before any auto generated columns (again, this behavior cannot be changed), and hide the auto generated bit column.

How to hide the column is described here. Essentially you cannot use Columns collection, so need to do this:

protected void DocumentReviewGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[X].Visible = false; // hides the first column
}

Here X is the 0-based index of the column to hide.

And now to prepend the column just define it the way you want, leaving AutoGenerateColumns="true":

<asp:GridView ID="DocumentReviewGrid"...>
    <Columns>
        <asp:CheckBoxField HeaderText="Esclusione" DataField="Esclusione" />
    </Columns>
</asp:GridView>

Admittedly this is quite hackish, but that will get you almost where you want - bool column displayed and editable.


问:
rbind loop in R
I have data with 2 million rows and 7 columns. There are also thousands of different companies and indicators.

A sample of the data is:

```<code>company_id                                                             indicator_id     X2011
1    1000045                 AccountsPayableAndAccruedLiabilitiesCurrentAndNoncurrent   6612429
2    1000045 AccumulatedDepreciationDepletionAndAmortizationPropertyPlantAndEquipment        NA
3    1000045                                                AdjustmentForAmortization        NA
4    1000045                                                                   Assets 257236034
5    1000045                                         AssetsHeldForSaleAtCarryingValue   1373001
6    1000045                      AssetsOfDisposalGroupIncludingDiscontinuedOperation        NA
      X2012     X2013     X2014     X2015
1   7405579   8924919   7841070   5839000
2   2111343   2242703   2236449   2462000
3 -11482251 -13490892 -13852305 -13811000
4 263835468 283429579 302528591 325309000
5   1203664   1696330        NA        NA
6        NA        NA   1746887   2148000
</code>```

and some of the indicators I want are:

```<code>    asset_indicators
[1] "DeferredIncomeTaxExpenseBenefit"
[2] "CashAndCashEquivalentsAtCarryingValue"
[3] "CashAndCashEquivalentsPeriodIncreaseDecrease"
[4] "NetCashProvidedByUsedInOperatingActivities"
[5] "NetCashProvidedByUsedInFinancingActivities"
[6] "NetCashProvidedByUsedInInvestingActivities"
[7] "PropertyPlantAndEquipmentNet"
</code>```

I am trying to get a new dataframe with just certain rows. Currently, I have this code:

```<code>year <-rbind(statement[which(statement$indicator_id==asset_indicators[1]),],
         statement[which(statement$indicator_id==asset_indicators[2]),],
         statement[which(statement$indicator_id==asset_indicators[3]),],
         statement[which(statement$indicator_id==asset_indicators[4]),],
         statement[which(statement$indicator_id==asset_indicators[5]),],
         statement[which(statement$indicator_id==asset_indicators[6]),],
         statement[which(statement$indicator_id==asset_indicators[7]),] )
</code>```

I'm wondering if there's a way to do this more efficiently? I tried making a for loop but it took hours to run while this takes just a few seconds. It would be nice if it updated automatically if I changed the number of indicators to use.

Does anyone have any ideas how to do this?

答:
Try %in%:

```<code>year <- statement[statement$indicator_id %in% asset_indicators,]
</code>```

Title: rbind loop in R

Body:
I have data with 2 million rows and 7 columns. There are also thousands of different companies and indicators.

A sample of the data is:

company_id                                                             indicator_id     X2011
1    1000045                 AccountsPayableAndAccruedLiabilitiesCurrentAndNoncurrent   6612429
2    1000045 AccumulatedDepreciationDepletionAndAmortizationPropertyPlantAndEquipment        NA
3    1000045                                                AdjustmentForAmortization        NA
4    1000045                                                                   Assets 257236034
5    1000045                                         AssetsHeldForSaleAtCarryingValue   1373001
6    1000045                      AssetsOfDisposalGroupIncludingDiscontinuedOperation        NA
      X2012     X2013     X2014     X2015
1   7405579   8924919   7841070   5839000
2   2111343   2242703   2236449   2462000
3 -11482251 -13490892 -13852305 -13811000
4 263835468 283429579 302528591 325309000
5   1203664   1696330        NA        NA
6        NA        NA   1746887   2148000

and some of the indicators I want are:

    asset_indicators
[1] "DeferredIncomeTaxExpenseBenefit"
[2] "CashAndCashEquivalentsAtCarryingValue"
[3] "CashAndCashEquivalentsPeriodIncreaseDecrease"
[4] "NetCashProvidedByUsedInOperatingActivities"
[5] "NetCashProvidedByUsedInFinancingActivities"
[6] "NetCashProvidedByUsedInInvestingActivities"
[7] "PropertyPlantAndEquipmentNet"

I am trying to get a new dataframe with just certain rows. Currently, I have this code:

year <-rbind(statement[which(statement$indicator_id==asset_indicators[1]),],
         statement[which(statement$indicator_id==asset_indicators[2]),],
         statement[which(statement$indicator_id==asset_indicators[3]),],
         statement[which(statement$indicator_id==asset_indicators[4]),],
         statement[which(statement$indicator_id==asset_indicators[5]),],
         statement[which(statement$indicator_id==asset_indicators[6]),],
         statement[which(statement$indicator_id==asset_indicators[7]),] )

I'm wondering if there's a way to do this more efficiently? I tried making a for loop but it took hours to run while this takes just a few seconds. It would be nice if it updated automatically if I changed the number of indicators to use.

Does anyone have any ideas how to do this?

Body:
Try %in%:

year <- statement[statement$indicator_id %in% asset_indicators,]


问:
A few coding convention/standard practice questions
I have this function that takes a string from main. The string contains all of the valid characters that a user can input from some menu options. Function will put character input into a variable and be compared to each character of the string. Compare input variable to the string characters until valid input is entered.

My question is, what is the best way to implement this loop? I don't like using while (true) with a return in the middle because it looks like an infinite loop with an exception in the middle, which makes it slightly harder to read, but I'm not sure how else I can do what I want it to do. What's the best practice for achieving my goal? Thanks.

```<code>char getValidKey(string validKeys)
{
    char letter;

    while (true) {
        cout << "Operation ? ";
        cin >> letter;
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        for (int i = 0; i < validKeys.length(); i++) {

            if (letter == validKeys[i])
                return letter;
        }

        cout << "Error. Invalid input.\n";
    }
}
</code>```

Also, I have a switch statement with multiple returns. Is it more common/preferred to assign calculations to a variable and have one return at the end or is this way generally okay?

```<code>string opStr;

switch (myOperation) {
    case 1:
        opStr = "RIGHT";
        break;
    case 2:
        opStr = "LEFT";
        break;
    case 3:
        opStr = "CENTER_ONLY";
        break;
    case 4:
        opStr = "CENTER_MISSING";
        break;
    default:
        opStr = "Error. Invalid input.";
        break;
}

return opStr;
</code>```

OR

```<code>switch (myOperation) {
    case 1:
        return "RIGHT";
        break;
    case 2:
        return "LEFT";
        break;
    case 3:
        return "CENTER_ONLY";
        break;
    case 4:
        return "CENTER_MISSING";
        break;
    default:
        return "Error. Invalid input.";
        break;
}
</code>```

答:
For the first case, refactor your code in smaller self-contained functions, and it becomes clear to understand the logic of getValidKey even from a while(true):

```<code>char isKeyValid(char x, const string& validKeys)
{
    return validKeys.find(x) != string::npos;
}

char readCharFromCin()
{
    char letter;

    cout << "Operation ? ";
    cin >> letter;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    return letter;
}

char getValidKey(const string& validKeys)
{
    while (true)
    {
        const char key = readCharFromCin();
        if(isKeyValid(key, validKeys)) return letter;

        cout << "Error. Invalid input.\n";
    }
}
</code>```

For the second case, avoid break and simply return from your switch. Make the function containing the switch only do one thing.

```<code>string switchOperation(int myOperation)
{
    switch (myOperation)
    {
        case 1:  return "RIGHT";
        case 2:  return "LEFT";
        case 3:  return "CENTER_ONLY";
        case 4:  return "CENTER_MISSING";
    }

    return "Error. Invalid input.";
}
</code>```

Also, try to maximize usage of const and pass string instances you're only reading by const& to avoid unnecessary copies.

Body:
I have this function that takes a string from main. The string contains all of the valid characters that a user can input from some menu options. Function will put character input into a variable and be compared to each character of the string. Compare input variable to the string characters until valid input is entered.

My question is, what is the best way to implement this loop? I don't like using while (true) with a return in the middle because it looks like an infinite loop with an exception in the middle, which makes it slightly harder to read, but I'm not sure how else I can do what I want it to do. What's the best practice for achieving my goal? Thanks.

char getValidKey(string validKeys)
{
    char letter;

    while (true) {
        cout << "Operation ? ";
        cin >> letter;
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        for (int i = 0; i < validKeys.length(); i++) {

            if (letter == validKeys[i])
                return letter;
        }

        cout << "Error. Invalid input.\n";
    }
}

Also, I have a switch statement with multiple returns. Is it more common/preferred to assign calculations to a variable and have one return at the end or is this way generally okay?

string opStr;

switch (myOperation) {
    case 1:
        opStr = "RIGHT";
        break;
    case 2:
        opStr = "LEFT";
        break;
    case 3:
        opStr = "CENTER_ONLY";
        break;
    case 4:
        opStr = "CENTER_MISSING";
        break;
    default:
        opStr = "Error. Invalid input.";
        break;
}

return opStr;

OR

switch (myOperation) {
    case 1:
        return "RIGHT";
        break;
    case 2:
        return "LEFT";
        break;
    case 3:
        return "CENTER_ONLY";
        break;
    case 4:
        return "CENTER_MISSING";
        break;
    default:
        return "Error. Invalid input.";
        break;
}

Body:
For the first case, refactor your code in smaller self-contained functions, and it becomes clear to understand the logic of getValidKey even from a while(true):

char isKeyValid(char x, const string& validKeys)
{
    return validKeys.find(x) != string::npos;
}

char readCharFromCin()
{
    char letter;

    cout << "Operation ? ";
    cin >> letter;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    return letter;
}

char getValidKey(const string& validKeys)
{
    while (true)
    {
        const char key = readCharFromCin();
        if(isKeyValid(key, validKeys)) return letter;

        cout << "Error. Invalid input.\n";
    }
}

For the second case, avoid break and simply return from your switch. Make the function containing the switch only do one thing.

string switchOperation(int myOperation)
{
    switch (myOperation)
    {
        case 1:  return "RIGHT";
        case 2:  return "LEFT";
        case 3:  return "CENTER_ONLY";
        case 4:  return "CENTER_MISSING";
    }

    return "Error. Invalid input.";
}

Also, try to maximize usage of const and pass string instances you're only reading by const& to avoid unnecessary copies.


问:
Why is Nhibernate creating a FK for a ReferencesAny?
I create the Database from the mappings. And I have a ReferenceAny that is creating a constraint that causes issues on the updates of a table.

I simplified the code, but these are my classes:

```<code>public interface IInterfaceA
{
    int Id { get; }
}

public class ClassA
{
    public virtual int Id { get; protected set; }
    public virtual IList<ClassC> Items { get; set;  }
}

public class ClassB
{
    public virtual int Id { get; protected set; }
    public virtual IList<ClassC> Items { get; set;  }
}

public class ClassC
{
    public virtual int Id { get; protected set; }
    public virtual IInterfaceA Parent { get; set; }
}
</code>```

These are my mappings:

```<code>public class ClassAMapping : ClassMap<ClassA>
{
    protected ClassAMapping()
    {
        Id(x => x.Id);
        HasMany(x => x.Items).KeyColumn("parent_id")
                .Where(string.Format("parent_type = '{0}'", typeof(ClassA).Name))
                .Inverse()
                .Cascade.AllDeleteOrphan();

    }
}

public class ClassBMapping : ClassMap<ClassB>
{
    protected ClassBMapping()
    {
        Id(x => x.Id);
        HasMany(x => x.Items).KeyColumn("parent_id")
                .Where(string.Format("parent_type = '{0}'", typeof(ClassB).Name))
                .Inverse()
                .Cascade.AllDeleteOrphan();

    }
}

public class ClassCMapping : ClassMap<ClassC>
{
    protected ClassCMapping()
    {
        Id(x => x.Id);
        ReferencesAny(x => x.Parent)
                .IdentityType<int>()
                .MetaType<string>()
                .EntityTypeColumn("parent_type")
                .EntityIdentifierColumn("parent_id")
            .AddMetaValue<ClassA>(typeof(ClassA).Name)
            .AddMetaValue<ClassB>(typeof(ClassB).Name);
    }
}
</code>```

I got the script for the FK that is being created:

```<code>ALTER TABLE [dbo].[ClassCTable]  WITH CHECK ADD  CONSTRAINT [FKA72ABA15F7EB0FA9] FOREIGN KEY([parent_id])
REFERENCES [dbo].[ClassBTable] ([Id])
</code>```

When I inset items linked to ClassA sometimes I get an error when the Id conflicts with the ClassB.

Why is the FK being created? Am I using the ReferenceAny wrong? Is there at least a way to Nhibernate not to create the FK?

答:
Silly me! I just noticed I forgot to tell the HasMany not to create the FK, I was puzzled because it was creating just one FK, but Of course they are conflicting that is why I just get one.

So the ClassA and ClassB mapping should look like this:

```<code>public class ClassAMapping : ClassMap<ClassA>
{
    protected ClassAMapping()
    {
        Id(x => x.Id);
        HasMany(x => x.Items).ForeignKeyConstraintName("none").KeyColumn("parent_id")
                .Where(string.Format("parent_type = '{0}'", typeof(ClassA).Name))
                .Inverse()
                .Cascade.AllDeleteOrphan();
    }
}

public class ClassBMapping : ClassMap<ClassB>
{
    protected ClassBMapping()
    {
        Id(x => x.Id);
        HasMany(x => x.Items).ForeignKeyConstraintName("none").KeyColumn("parent_id")
                .Where(string.Format("parent_type = '{0}'", typeof(ClassB).Name))
                .Inverse()
                .Cascade.AllDeleteOrphan();
    }
}
</code>```

Body:
I create the Database from the mappings. And I have a ReferenceAny that is creating a constraint that causes issues on the updates of a table.

I simplified the code, but these are my classes:

public interface IInterfaceA
{
    int Id { get; }
}

public class ClassA
{
    public virtual int Id { get; protected set; }
    public virtual IList<ClassC> Items { get; set;  }
}

public class ClassB
{
    public virtual int Id { get; protected set; }
    public virtual IList<ClassC> Items { get; set;  }
}

public class ClassC
{
    public virtual int Id { get; protected set; }
    public virtual IInterfaceA Parent { get; set; }
}

These are my mappings:

public class ClassAMapping : ClassMap<ClassA>
{
    protected ClassAMapping()
    {
        Id(x => x.Id);
        HasMany(x => x.Items).KeyColumn("parent_id")
                .Where(string.Format("parent_type = '{0}'", typeof(ClassA).Name))
                .Inverse()
                .Cascade.AllDeleteOrphan();

    }
}

public class ClassBMapping : ClassMap<ClassB>
{
    protected ClassBMapping()
    {
        Id(x => x.Id);
        HasMany(x => x.Items).KeyColumn("parent_id")
                .Where(string.Format("parent_type = '{0}'", typeof(ClassB).Name))
                .Inverse()
                .Cascade.AllDeleteOrphan();

    }
}

public class ClassCMapping : ClassMap<ClassC>
{
    protected ClassCMapping()
    {
        Id(x => x.Id);
        ReferencesAny(x => x.Parent)
                .IdentityType<int>()
                .MetaType<string>()
                .EntityTypeColumn("parent_type")
                .EntityIdentifierColumn("parent_id")
            .AddMetaValue<ClassA>(typeof(ClassA).Name)
            .AddMetaValue<ClassB>(typeof(ClassB).Name);
    }
}

I got the script for the FK that is being created:

ALTER TABLE [dbo].[ClassCTable]  WITH CHECK ADD  CONSTRAINT [FKA72ABA15F7EB0FA9] FOREIGN KEY([parent_id])
REFERENCES [dbo].[ClassBTable] ([Id])

When I inset items linked to ClassA sometimes I get an error when the Id conflicts with the ClassB.

Why is the FK being created? Am I using the ReferenceAny wrong? Is there at least a way to Nhibernate not to create the FK?

Body:
Silly me! I just noticed I forgot to tell the HasMany not to create the FK, I was puzzled because it was creating just one FK, but Of course they are conflicting that is why I just get one.

So the ClassA and ClassB mapping should look like this:

public class ClassAMapping : ClassMap<ClassA>
{
    protected ClassAMapping()
    {
        Id(x => x.Id);
        HasMany(x => x.Items).ForeignKeyConstraintName("none").KeyColumn("parent_id")
                .Where(string.Format("parent_type = '{0}'", typeof(ClassA).Name))
                .Inverse()
                .Cascade.AllDeleteOrphan();
    }
}

public class ClassBMapping : ClassMap<ClassB>
{
    protected ClassBMapping()
    {
        Id(x => x.Id);
        HasMany(x => x.Items).ForeignKeyConstraintName("none").KeyColumn("parent_id")
                .Where(string.Format("parent_type = '{0}'", typeof(ClassB).Name))
                .Inverse()
                .Cascade.AllDeleteOrphan();
    }
}


问:
Rundeck failing execution of ansible commands/playbooks
I have ansible playbook that restore aws MySQL RDS from snapshot. If run, manually from command-line, the playbook runs well and do the tasks. But when run through the web interface of rundeck, following error is encountered,

```<code>fatal: [localhost]: UNREACHABLE! => {"changed": false, "msg": "Authentication or permission failure. In some cases, you may have been able to authenticate and did not have permissions on the remote directory. Consider changing the remote temp path in ansible.cfg to a path rooted in \"/tmp\". Failed command was: ( umask 77 && mkdir -p \"` echo $HOME/.ansible/tmp/ansible-tmp-1491222004.1-29099027555878 `\" && echo ansible-tmp-1491222004.1-29099027555878=\"` echo $HOME/.ansible/tmp/ansible-tmp-1491222004.1-29099027555878 `\" ), exited with result 1", "unreachable": true}
</code>```

My Rundeck server on the same Ansible server

I tried to add the line below in ansible.cfg

```<code>remote_tmp = $HOME/.ansible/tmp
local_tmp = $HOME/.ansible/tmp
</code>```

I set privilege 1777 for $HOME/.ansible/tmp already but it didn't solve my problem.
Could you please help?
Thanks!!!

答:
set those in ansible.cfg:

```<code>remote_tmp = $HOME/.ansible/tmp
local_tmp = $HOME/.ansible/tmp
</code>```

Ansible issue #21339

Body:
I have ansible playbook that restore aws MySQL RDS from snapshot. If run, manually from command-line, the playbook runs well and do the tasks. But when run through the web interface of rundeck, following error is encountered,

fatal: [localhost]: UNREACHABLE! => {"changed": false, "msg": "Authentication or permission failure. In some cases, you may have been able to authenticate and did not have permissions on the remote directory. Consider changing the remote temp path in ansible.cfg to a path rooted in \"/tmp\". Failed command was: ( umask 77 && mkdir -p \"` echo $HOME/.ansible/tmp/ansible-tmp-1491222004.1-29099027555878 `\" && echo ansible-tmp-1491222004.1-29099027555878=\"` echo $HOME/.ansible/tmp/ansible-tmp-1491222004.1-29099027555878 `\" ), exited with result 1", "unreachable": true}

My Rundeck server on the same Ansible server

I tried to add the line below in ansible.cfg

remote_tmp = $HOME/.ansible/tmp
local_tmp = $HOME/.ansible/tmp

I set privilege 1777 for $HOME/.ansible/tmp already but it didn't solve my problem.
Could you please help?
Thanks!!!

Body:
set those in ansible.cfg:

remote_tmp = $HOME/.ansible/tmp
local_tmp = $HOME/.ansible/tmp

Ansible issue #21339


问:
Lua table contents separated at equal sign
I am learning Lua, and i want to use it with Rainmeter.
In Rainmeter i use an external txt file to store skin positions with the following type of lines:

```<code>pza=A1
pzb=B2
pzc=D3
... (and so on...)
</code>```

In my Lua script i made an array with reading the lines in it. So the first line is pza=A1, the second is pzb=B2, and so.
Is there any way to check only the value after the equal sign? So separating somehow the pza=A1, to get the "pza" as key, and to get "A1" as value?

Thank you very much for the help in advance!

答:
you can use gmatch and patterns:

```<code>local s=[[
    pza=A1
    pzb=B2
    pzc=D3
]]

local t= {}
for k,v in s:gmatch('(%w+)=(%w+)') do
  t[k]=v
  print(k,t[k])
end
</code>```

result:

```<code>pza A1
pzb B2
pzc D3
</code>```

Body:
I am learning Lua, and i want to use it with Rainmeter.
In Rainmeter i use an external txt file to store skin positions with the following type of lines:

pza=A1
pzb=B2
pzc=D3
... (and so on...)

In my Lua script i made an array with reading the lines in it. So the first line is pza=A1, the second is pzb=B2, and so.
Is there any way to check only the value after the equal sign? So separating somehow the pza=A1, to get the "pza" as key, and to get "A1" as value?

Thank you very much for the help in advance!

Body:
you can use gmatch and patterns:

local s=[[
    pza=A1
    pzb=B2
    pzc=D3
]]

local t= {}
for k,v in s:gmatch('(%w+)=(%w+)') do
  t[k]=v
  print(k,t[k])
end

result:

pza A1
pzb B2
pzc D3


问:
Cannot load obfuscated assembly
I'm working for the first time with dotfuscator. My project is written in C# and .NET 3.5, it has a main program and some plugins; this is the slice of code that loads the plugins:

```<code>// Load the file
Assembly asm = Assembly.LoadFile( pluginPath );

// Instantiate the types I need
foreach( Type type in asm.GetTypes() )
{
    ...
}
</code>```

Now the problem is: if i don't obfuscate everything is fine but when i use dotfuscator asm.GetTypes() throw a ReflectionTypeLoadException which says

The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I googled for hours with no result. Thanks in advance.

EDIT: After some researches and debugging I think it's a problem in the manifest, because the reflection can't see (or loads) the types inside the assembly. I opened the obfuscated assembly with Reflector but everything seems fine.

答:
I don't think Obfuscation works well with reflection. In fact, I think that's the number one trade off when using obfuscation.

See this link for how to overcome types that need to be reflected over

ContentLicense: CC BY-SA 2.5

Title: Cannot load obfuscated assembly

Body:
I'm working for the first time with dotfuscator. My project is written in C# and .NET 3.5, it has a main program and some plugins; this is the slice of code that loads the plugins:

// Load the file
Assembly asm = Assembly.LoadFile( pluginPath );

// Instantiate the types I need
foreach( Type type in asm.GetTypes() )
{
    ...
}

Now the problem is: if i don't obfuscate everything is fine but when i use dotfuscator asm.GetTypes() throw a ReflectionTypeLoadException which says

The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I googled for hours with no result. Thanks in advance.

EDIT: After some researches and debugging I think it's a problem in the manifest, because the reflection can't see (or loads) the types inside the assembly. I opened the obfuscated assembly with Reflector but everything seems fine.


问:
ReactJS ES6 syntax for handling events
I am fairly new to ReactJS, Redux and ES6, and I am trying to implement an event-handler where my chat body would hide or unhide as i click the header (kind of like what Facebook chat widget does). My problem is I cannot get the syntax correctly from a copied source. Here is my code:

```<code>import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';

class ChatWidget extends Component {

  handleClick(event) {
    console.log("test")
  }

  render() {
    return (
      <div className={chat.box}>

        <div className={chat.container}>

          <div onClick={onClick={this.handleClick.bind(this)}}
               className={chat.header}>
            <span className={chat.name}>Idol</span>
          </div>

          <div className={chat.body}>
            This is the Body of the chat
          </div>

          <div className={chat.chat}>
            <input type="text" placeholder="Ask anything..." />
          </div>
        </div>

      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);
</code>```

Error:

```<code>> 16 |           <div onClick={onClick={this.handleClick.bind(this)}}
     |                                      ^
</code>```

答:
Instead of

onClick={onClick={this.handleClick.bind(this)}}

Write this:

onClick={this.handleClick.bind(this)}

Title: ReactJS ES6 syntax for handling events

Body:
I am fairly new to ReactJS, Redux and ES6, and I am trying to implement an event-handler where my chat body would hide or unhide as i click the header (kind of like what Facebook chat widget does). My problem is I cannot get the syntax correctly from a copied source. Here is my code:

import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';

class ChatWidget extends Component {

  handleClick(event) {
    console.log("test")
  }

  render() {
    return (

            Idol

            This is the Body of the chat

            <input type="text" placeholder="Ask anything..." />

    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);

Error:

> 16 |           <div onClick={onClick={this.handleClick.bind(this)}}
     |                                      ^


问:
PhoneGap Build: confusing and conflicting information?
I'm using Phonegap build to create a simple app.

in my conf.xml file I have chosen the cli version like this:

```<code><preference name="phonegap-version" value='cli-6.5.0' />
</code>```

But when I upload my app to Phonegap build, I get the below error:

This is confusing and doesn't make sense.

Is this the phonegap build error or I'm actually missing something?

答:
The latest Phongap CLI Version is 6.5.0

As you can see here the default version is 6.5.0.

What you can do is remove that line in the config.xml file and by doing that it will use the most recent CLI (6.5.0)

Body:
I'm using Phonegap build to create a simple app.

in my conf.xml file I have chosen the cli version like this:

<preference name="phonegap-version" value='cli-6.5.0' />

But when I upload my app to Phonegap build, I get the below error:

This is confusing and doesn't make sense.

Is this the phonegap build error or I'm actually missing something?


问:
Insert values from ArrayList into a JTable
```<code>public void populateJTable() {
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    Object[] rowData = new Object[4];
    TrackService ts = new TrackService();
    ArrayList<Track> tracks = ts.jsonToTracks();

    for (int i = 0; i < tracks.size(); i++) {
        rowData[0] = tracks.get(i).getTrackName();
        rowData[1] = tracks.get(i).getArtist();
        model.addRow(rowData);
    }
    jTable1 = new JTable(model);
}
</code>```

In my json file I have stored metadata of an mp3 file which stores 5 values. My 'jsonToTracks' method stores them in an ArrayList.
I'm trying to get 2 of the values (trackName and artist) from inside my ArrayList and display them in my JTable.
My JTable has 4 columns - Name, Artist, Key, Mood. I'm trying to store the trackName and Artist in their corresponding columns. The Key and Mood column should be blank and the Name and Artist fields should be populated.
I can't see what I'm doing wrong, can anyone help?

答:
Maybe you should try, moving your rowData initialization inside for loop.</p>

```<code>public void populateJTable() {
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    TrackService ts = new TrackService();
    ArrayList<Track> tracks = ts.jsonToTracks();

    for (int i = 0; i < tracks.size(); i++) {
        Object[] rowData = new Object[4];
        rowData[0] = tracks.get(i).getTrackName();
        rowData[1] = tracks.get(i).getArtist();
        model.addRow(rowData);
    }
    jTable1 = new JTable(model);
}
</code>```

Body:
public void populateJTable() {
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    Object[] rowData = new Object[4];
    TrackService ts = new TrackService();
    ArrayList<Track> tracks = ts.jsonToTracks();

    for (int i = 0; i < tracks.size(); i++) {
        rowData[0] = tracks.get(i).getTrackName();
        rowData[1] = tracks.get(i).getArtist();
        model.addRow(rowData);
    }
    jTable1 = new JTable(model);
}

In my json file I have stored metadata of an mp3 file which stores 5 values. My 'jsonToTracks' method stores them in an ArrayList.
I'm trying to get 2 of the values (trackName and artist) from inside my ArrayList and display them in my JTable.
My JTable has 4 columns - Name, Artist, Key, Mood. I'm trying to store the trackName and Artist in their corresponding columns. The Key and Mood column should be blank and the Name and Artist fields should be populated.
I can't see what I'm doing wrong, can anyone help?

Body:
Maybe you should try, moving your rowData initialization inside for loop.

public void populateJTable() {
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    TrackService ts = new TrackService();
    ArrayList<Track> tracks = ts.jsonToTracks();

    for (int i = 0; i < tracks.size(); i++) {
        Object[] rowData = new Object[4];
        rowData[0] = tracks.get(i).getTrackName();
        rowData[1] = tracks.get(i).getArtist();
        model.addRow(rowData);
    }
    jTable1 = new JTable(model);
}


问:
Order of Evaluation of Arguments in Ocaml
I would like to know why does ocaml evaluate the calls from right to left, is that a FP principle or it doesn't matter at all to a FP language ?

A quicksort example :

```<code>let rec qs = function
    | [] -> []
    | h::t -> let l, r = List.partition ((>) h) t in
    List.iter (fun e -> print_int e; print_char ' ') l; Printf.printf " <<%d>> " h;
    List.iter (fun e -> print_int e; print_char ' ') r; print_char '\n';
    (qs l)@(h::qs r)
</code>```

In my example the call to (qs r) is evaluated first and then (qs l) but I expected it to be otherwise.

```<code># qs [5;43;1;10;2];;
1 2  <<5>> 43 10
10   <<43>>
     <<10>>
     <<1>> 2
     <<2>>
- : int list = [1; 2; 5; 10; 43]
</code>```

EDIT :

from https://caml.inria.fr/pub/docs/oreilly-book/html/book-ora029.html
<s>

In Objective CAML, the order of evaluation of arguments is not
  specified. As it happens, today all implementations of Objective CAML
  evaluate arguments from left to right. All the same, making use of
  this implementation feature could turn out to be dangerous if future
  versions of the language modify the implementation.
  </s>

答:
The order of evaluation of arguments to a function is not specified in OCaml.

This is documented in Section 6.7 of the manual.

In essence this gives the greatest possible freedom to the system (compiler or interpreter) to evaluate expressions in an order that is advantageous in some way. It means you (as an OCaml programmer) must write code that doesn't depend on the order of evaluation.

If your code is purely functional, its behavior can't depend on the order. So you need to be careful only when writing code with effects.

Update

If you care about order, use let:

```<code>let a = <expr1> in
let b = <expr2> in
f a b
</code>```

Or, more generally:

```<code>let f = <expr0> in
let a = <expr1> in
let b = <expr2> in
f a b
</code>```

Update 2

For what it's worth, the book you cite above was published in 2002. A lot has changed since then, including the name of the language. A more current resource is Real World OCaml.

Body:
I would like to know why does ocaml evaluate the calls from right to left, is that a FP principle or it doesn't matter at all to a FP language ?

A quicksort example :

let rec qs = function
    | [] -> []
    | h::t -> let l, r = List.partition ((>) h) t in
    List.iter (fun e -> print_int e; print_char ' ') l; Printf.printf " <<%d>> " h;
    List.iter (fun e -> print_int e; print_char ' ') r; print_char '\n';
    (qs l)@(h::qs r)

In my example the call to (qs r) is evaluated first and then (qs l) but I expected it to be otherwise.

# qs [5;43;1;10;2];;
1 2  <<5>> 43 10
10   <<43>>
     <<10>>
     <<1>> 2
     <<2>>
- : int list = [1; 2; 5; 10; 43]

EDIT :

from https://caml.inria.fr/pub/docs/oreilly-book/html/book-ora029.html
<s>

In Objective CAML, the order of evaluation of arguments is not
  specified. As it happens, today all implementations of Objective CAML
  evaluate arguments from left to right. All the same, making use of
  this implementation feature could turn out to be dangerous if future
  versions of the language modify the implementation.
  </s>

Body:
The order of evaluation of arguments to a function is not specified in OCaml.

This is documented in Section 6.7 of the manual.

In essence this gives the greatest possible freedom to the system (compiler or interpreter) to evaluate expressions in an order that is advantageous in some way. It means you (as an OCaml programmer) must write code that doesn't depend on the order of evaluation.

If your code is purely functional, its behavior can't depend on the order. So you need to be careful only when writing code with effects.

Update

If you care about order, use let:

let a = <expr1> in
let b = <expr2> in
f a b

Or, more generally:

let f = <expr0> in
let a = <expr1> in
let b = <expr2> in
f a b

Update 2

For what it's worth, the book you cite above was published in 2002. A lot has changed since then, including the name of the language. A more current resource is Real World OCaml.


问:
on register, check if username exists -- capitalization problem
My homefried account registration system proceeds thusly:

complete registration form

check if username already exists - reject/pass

copy data to temp user table, send confirmation email

upon using link in confirmation email, copy data from temp to active user table

The other day a user emailed me to say he was getting the error message "Could not create user."

I couldn't recall ever hearing that, so I dug into my registration code and that error pops out if the query to insert the temp data into the active user table fails.

It failed because his username, which has a unique index in the table, already existed in the active user table... but he had passed the initial existing username check...?

Turned out the name he had tried to register was "User" but there was already a "user" -- so case-insensitivity is coming into play.

Does username exist? query string:

```<code>SELECT username FROM user_basic_data WHERE username='$cleanTempUsername'
</code>```

Confirmed, now insert into active table string:

```<code>INSERT INTO user_basic_data (username, ...) VALUES ('$activeUsername', ...)
</code>```

So the case-sensitivity apparently applies when I run a select statement ("User" != "user") but does not apply when I run an insert.

Capitalization is important to many users, so what's my fix of least resistance from here?

答:
if you want case sensitive usernames use a varbinary datatype...</p>

```<code>create table users
(
user_id int unsigned not null auto_increment primary key,
username varbinary(32) unique not null,
...
)
engine=innodb;

insert into users (username) values ('foo'),('Foo'),('FOO');
</code>```

Body:
My homefried account registration system proceeds thusly:

complete registration form

check if username already exists - reject/pass

copy data to temp user table, send confirmation email

upon using link in confirmation email, copy data from temp to active user table

The other day a user emailed me to say he was getting the error message "Could not create user."

I couldn't recall ever hearing that, so I dug into my registration code and that error pops out if the query to insert the temp data into the active user table fails.

It failed because his username, which has a unique index in the table, already existed in the active user table... but he had passed the initial existing username check...?

Turned out the name he had tried to register was "User" but there was already a "user" -- so case-insensitivity is coming into play.

Does username exist? query string:

SELECT username FROM user_basic_data WHERE username='$cleanTempUsername'

Confirmed, now insert into active table string:

INSERT INTO user_basic_data (username, ...) VALUES ('$activeUsername', ...)

So the case-sensitivity apparently applies when I run a select statement ("User" != "user") but does not apply when I run an insert.

Capitalization is important to many users, so what's my fix of least resistance from here?

Body:
if you want case sensitive usernames use a varbinary datatype...

create table users
(
user_id int unsigned not null auto_increment primary key,
username varbinary(32) unique not null,
...
)
engine=innodb;

insert into users (username) values ('foo'),('Foo'),('FOO');


问:
HTML5 form audio input from iOS device directly
I want to build a HTML5 form, in which user can submit audio file from the desktop, and for mobile device, user have to record the audio directly. I use the following html5 code for the audio input

<input type="file" accept="audio/*" id="capture" capture="microphone">

It works properly, but not iOS device, and which always give me .mov video files instead of any audio.

Is it the limitation of iOS? And is there any workaround for my case?

答: Looks like it's just not supported through iOS and it's been that way for a few versions.  Check out this link from another post.</p>


问:
Liferay link to other language page
I am using freemarker template on Liferay Portal CE 6.2 and my site has 2 languages (italian and english). Is there any variable or function to get the link to the same page in the other language?

Example: I am on page /en/operations and I want that by clicking on the "italian" button the browser goes to /it/attivita, which is the translated page specified on pages admin.

答:
I found the solution on the liferay forum: https://web.liferay.com/it/community/forums/-/message_boards/message/74709035

```<code><#assign languageUrl = portletURLFactory.create(request, "82", layout.getPlid(), "ACTION_PHASE") />
${languageUrl.setParameter( "struts_action", "/language/view" )}
${languageUrl.setParameter( "redirect", theme_display.getURLCurrent() )}
${languageUrl.setPortletMode( "view" )}
${languageUrl.setWindowState( "normal" )}
${languageUrl.setParameter( "languageId", "xx_XX" )}
</code>```

set the xx_XX to the locale you want to switch to and add a link to languageUrl:

```<code><a href="${languageUrl}">Italian</a>
</code>```

Title: Liferay link to other language page

Body:
I found the solution on the liferay forum: https://web.liferay.com/it/community/forums/-/message_boards/message/74709035

<#assign languageUrl = portletURLFactory.create(request, "82", layout.getPlid(), "ACTION_PHASE") />
${languageUrl.setParameter( "struts_action", "/language/view" )}
${languageUrl.setParameter( "redirect", theme_display.getURLCurrent() )}
${languageUrl.setPortletMode( "view" )}
${languageUrl.setWindowState( "normal" )}
${languageUrl.setParameter( "languageId", "xx_XX" )}

set the xx_XX to the locale you want to switch to and add a link to languageUrl:

<a href="${languageUrl}">Italian</a>


问:
Making a NxN tic tac toe GUI wpf c#
I am making a NxN tic tac toe game in WPF c#. I want user to enter Rows and Column count(NxN), and my code will generate those number of columns and rows. I can't figure it out, how will I produce that number of rows and columns dynamically. I have posted my XAML code, is there a way that I can loop my XAML code?
    thanks</p>

```<code><Grid x:Name="Container">
    <!-- First here i want to make N columns-->
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <!-- Here i want to make N rows-->
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!-- Then here i want to add that number of buttons in N x N columns and rows -->
    <Button x:Name="Button0_0" Grid.Row="0" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button0_1" Grid.Row="0" Grid.Column="1" Click="Button_Click" />
    <Button x:Name="Button0_2" Grid.Row="0" Grid.Column="2" Click="Button_Click"/>

    <Button x:Name="Button1_0" Grid.Row="1" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button1_1" Grid.Row="1" Grid.Column="1" Click="Button_Click"/>
    <Button x:Name="Button1_2" Grid.Row="1" Grid.Column="2" Click="Button_Click"/>

    <Button x:Name="Button2_0" Grid.Row="2" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button2_1" Grid.Row="2" Grid.Column="1" Click="Button_Click"/>
    <Button x:Name="Button2_2" Grid.Row="2" Grid.Column="2" Click="Button_Click"/>
</Grid>
</code>```

答:
I have code for some AttachedProperties on my blog that does exactly this.

XAML code ends up looking like this :

```<code><Grid local:GridHelpers.RowCount="{Binding RowCount}"
      local:GridHelpers.ColumnCount="{Binding ColumnCount}" />
</code>```

Here's the code for the Attached properties, in case the blog post link ever goes down. It also includes some properties to specify your Star rows/columns.

```<code>public class GridHelpers
{
    #region RowCount Property

    /// <summary>
    /// Adds the specified number of Rows to RowDefinitions.
    /// Default Height is Auto
    /// </summary>
    public static readonly DependencyProperty RowCountProperty =
        DependencyProperty.RegisterAttached(
            "RowCount", typeof(int), typeof(GridHelpers),
            new PropertyMetadata(-1, RowCountChanged));

    // Get
    public static int GetRowCount(DependencyObject obj)
    {
        return (int)obj.GetValue(RowCountProperty);
    }

    // Set
    public static void SetRowCount(DependencyObject obj, int value)
    {
        obj.SetValue(RowCountProperty, value);
    }

    // Change Event - Adds the Rows
    public static void RowCountChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is Grid) || (int)e.NewValue < 0)
            return;

        Grid grid = (Grid)obj;
        grid.RowDefinitions.Clear();

        for (int i = 0; i < (int)e.NewValue; i++)
            grid.RowDefinitions.Add(
                new RowDefinition() { Height = GridLength.Auto });

        SetStarRows(grid);
    }

    #endregion

    #region ColumnCount Property

    /// <summary>
    /// Adds the specified number of Columns to ColumnDefinitions.
    /// Default Width is Auto
    /// </summary>
    public static readonly DependencyProperty ColumnCountProperty =
        DependencyProperty.RegisterAttached(
            "ColumnCount", typeof(int), typeof(GridHelpers),
            new PropertyMetadata(-1, ColumnCountChanged));

    // Get
    public static int GetColumnCount(DependencyObject obj)
    {
        return (int)obj.GetValue(ColumnCountProperty);
    }

    // Set
    public static void SetColumnCount(DependencyObject obj, int value)
    {
        obj.SetValue(ColumnCountProperty, value);
    }

    // Change Event - Add the Columns
    public static void ColumnCountChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is Grid) || (int)e.NewValue < 0)
            return;

        Grid grid = (Grid)obj;
        grid.ColumnDefinitions.Clear();

        for (int i = 0; i < (int)e.NewValue; i++)
            grid.ColumnDefinitions.Add(
                new ColumnDefinition() { Width = GridLength.Auto });

        SetStarColumns(grid);
    }

    #endregion

    #region StarRows Property

    /// <summary>
    /// Makes the specified Row's Height equal to Star.
    /// Can set on multiple Rows
    /// </summary>
    public static readonly DependencyProperty StarRowsProperty =
        DependencyProperty.RegisterAttached(
            "StarRows", typeof(string), typeof(GridHelpers),
            new PropertyMetadata(string.Empty, StarRowsChanged));

    // Get
    public static string GetStarRows(DependencyObject obj)
    {
        return (string)obj.GetValue(StarRowsProperty);
    }

    // Set
    public static void SetStarRows(DependencyObject obj, string value)
    {
        obj.SetValue(StarRowsProperty, value);
    }

    // Change Event - Makes specified Row's Height equal to Star
    public static void StarRowsChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is Grid) || string.IsNullOrEmpty(e.NewValue.ToString()))
            return;

        SetStarRows((Grid)obj);
    }

    #endregion

    #region StarColumns Property

    /// <summary>
    /// Makes the specified Column's Width equal to Star.
    /// Can set on multiple Columns
    /// </summary>
    public static readonly DependencyProperty StarColumnsProperty =
        DependencyProperty.RegisterAttached(
            "StarColumns", typeof(string), typeof(GridHelpers),
            new PropertyMetadata(string.Empty, StarColumnsChanged));

    // Get
    public static string GetStarColumns(DependencyObject obj)
    {
        return (string)obj.GetValue(StarColumnsProperty);
    }

    // Set
    public static void SetStarColumns(DependencyObject obj, string value)
    {
        obj.SetValue(StarColumnsProperty, value);
    }

    // Change Event - Makes specified Column's Width equal to Star
    public static void StarColumnsChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is Grid) || string.IsNullOrEmpty(e.NewValue.ToString()))
            return;

        SetStarColumns((Grid)obj);
    }

    #endregion

    private static void SetStarColumns(Grid grid)
    {
        string[] starColumns =
            GetStarColumns(grid).Split(',');

        for (int i = 0; i < grid.ColumnDefinitions.Count; i++)
        {
            if (starColumns.Contains(i.ToString()))
                grid.ColumnDefinitions[i].Width =
                    new GridLength(1, GridUnitType.Star);
        }
    }

    private static void SetStarRows(Grid grid)
    {
        string[] starRows =
            GetStarRows(grid).Split(',');

        for (int i = 0; i < grid.RowDefinitions.Count; i++)
        {
            if (starRows.Contains(i.ToString()))
                grid.RowDefinitions[i].Height =
                    new GridLength(1, GridUnitType.Star);
        }
    }
}
</code>```

Title: Making a NxN tic tac toe GUI wpf c#

Body:
I am making a NxN tic tac toe game in WPF c#. I want user to enter Rows and Column count(NxN), and my code will generate those number of columns and rows. I can't figure it out, how will I produce that number of rows and columns dynamically. I have posted my XAML code, is there a way that I can loop my XAML code?
    thanks

<Grid x:Name="Container">

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Button x:Name="Button0_0" Grid.Row="0" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button0_1" Grid.Row="0" Grid.Column="1" Click="Button_Click" />
    <Button x:Name="Button0_2" Grid.Row="0" Grid.Column="2" Click="Button_Click"/>

    <Button x:Name="Button1_0" Grid.Row="1" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button1_1" Grid.Row="1" Grid.Column="1" Click="Button_Click"/>
    <Button x:Name="Button1_2" Grid.Row="1" Grid.Column="2" Click="Button_Click"/>

    <Button x:Name="Button2_0" Grid.Row="2" Grid.Column="0" Click="Button_Click"/>
    <Button x:Name="Button2_1" Grid.Row="2" Grid.Column="1" Click="Button_Click"/>
    <Button x:Name="Button2_2" Grid.Row="2" Grid.Column="2" Click="Button_Click"/>
</Grid>

Body:
I have code for some AttachedProperties on my blog that does exactly this.

XAML code ends up looking like this :

<Grid local:GridHelpers.RowCount="{Binding RowCount}"
      local:GridHelpers.ColumnCount="{Binding ColumnCount}" />

Here's the code for the Attached properties, in case the blog post link ever goes down. It also includes some properties to specify your Star rows/columns.

public class GridHelpers
{
    #region RowCount Property

    /// <summary>
    /// Adds the specified number of Rows to RowDefinitions.
    /// Default Height is Auto
    /// </summary>
    public static readonly DependencyProperty RowCountProperty =
        DependencyProperty.RegisterAttached(
            "RowCount", typeof(int), typeof(GridHelpers),
            new PropertyMetadata(-1, RowCountChanged));

    // Get
    public static int GetRowCount(DependencyObject obj)
    {
        return (int)obj.GetValue(RowCountProperty);
    }

    // Set
    public static void SetRowCount(DependencyObject obj, int value)
    {
        obj.SetValue(RowCountProperty, value);
    }

    // Change Event - Adds the Rows
    public static void RowCountChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is Grid) || (int)e.NewValue < 0)
            return;

        Grid grid = (Grid)obj;
        grid.RowDefinitions.Clear();

        for (int i = 0; i < (int)e.NewValue; i++)
            grid.RowDefinitions.Add(
                new RowDefinition() { Height = GridLength.Auto });

        SetStarRows(grid);
    }

    #endregion

    #region ColumnCount Property

    /// <summary>
    /// Adds the specified number of Columns to ColumnDefinitions.
    /// Default Width is Auto
    /// </summary>
    public static readonly DependencyProperty ColumnCountProperty =
        DependencyProperty.RegisterAttached(
            "ColumnCount", typeof(int), typeof(GridHelpers),
            new PropertyMetadata(-1, ColumnCountChanged));

    // Get
    public static int GetColumnCount(DependencyObject obj)
    {
        return (int)obj.GetValue(ColumnCountProperty);
    }

    // Set
    public static void SetColumnCount(DependencyObject obj, int value)
    {
        obj.SetValue(ColumnCountProperty, value);
    }

    // Change Event - Add the Columns
    public static void ColumnCountChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is Grid) || (int)e.NewValue < 0)
            return;

        Grid grid = (Grid)obj;
        grid.ColumnDefinitions.Clear();

        for (int i = 0; i < (int)e.NewValue; i++)
            grid.ColumnDefinitions.Add(
                new ColumnDefinition() { Width = GridLength.Auto });

        SetStarColumns(grid);
    }

    #endregion

    #region StarRows Property

    /// <summary>
    /// Makes the specified Row's Height equal to Star.
    /// Can set on multiple Rows
    /// </summary>
    public static readonly DependencyProperty StarRowsProperty =
        DependencyProperty.RegisterAttached(
            "StarRows", typeof(string), typeof(GridHelpers),
            new PropertyMetadata(string.Empty, StarRowsChanged));

    // Get
    public static string GetStarRows(DependencyObject obj)
    {
        return (string)obj.GetValue(StarRowsProperty);
    }

    // Set
    public static void SetStarRows(DependencyObject obj, string value)
    {
        obj.SetValue(StarRowsProperty, value);
    }

    // Change Event - Makes specified Row's Height equal to Star
    public static void StarRowsChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is Grid) || string.IsNullOrEmpty(e.NewValue.ToString()))
            return;

        SetStarRows((Grid)obj);
    }

    #endregion

    #region StarColumns Property

    /// <summary>
    /// Makes the specified Column's Width equal to Star.
    /// Can set on multiple Columns
    /// </summary>
    public static readonly DependencyProperty StarColumnsProperty =
        DependencyProperty.RegisterAttached(
            "StarColumns", typeof(string), typeof(GridHelpers),
            new PropertyMetadata(string.Empty, StarColumnsChanged));

    // Get
    public static string GetStarColumns(DependencyObject obj)
    {
        return (string)obj.GetValue(StarColumnsProperty);
    }

    // Set
    public static void SetStarColumns(DependencyObject obj, string value)
    {
        obj.SetValue(StarColumnsProperty, value);
    }

    // Change Event - Makes specified Column's Width equal to Star
    public static void StarColumnsChanged(
        DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        if (!(obj is Grid) || string.IsNullOrEmpty(e.NewValue.ToString()))
            return;

        SetStarColumns((Grid)obj);
    }

    #endregion

    private static void SetStarColumns(Grid grid)
    {
        string[] starColumns =
            GetStarColumns(grid).Split(',');

        for (int i = 0; i < grid.ColumnDefinitions.Count; i++)
        {
            if (starColumns.Contains(i.ToString()))
                grid.ColumnDefinitions[i].Width =
                    new GridLength(1, GridUnitType.Star);
        }
    }

    private static void SetStarRows(Grid grid)
    {
        string[] starRows =
            GetStarRows(grid).Split(',');

        for (int i = 0; i < grid.RowDefinitions.Count; i++)
        {
            if (starRows.Contains(i.ToString()))
                grid.RowDefinitions[i].Height =
                    new GridLength(1, GridUnitType.Star);
        }
    }
}


问:
Running Luigi task from cmd - "No module named tasks"
I am having problems running a Luigi task through the Windows cmd. Here are the facts:

Running Anaconda installed in C:\ProgramData\Anaconda2 (Python 2.7)

Anaconda has added its paths to the PATH variable but there is no PYTHONPATH variable

The task i am trying to run is located in C:\....\tasks.py

Trying to run it as follows:

C:\.... luigi --module tasks MyTask --dt 20170316

  ImportError: No module named tasks

I tried creating a PYTHONPATH variable and adding the exact path to the directory containing my tasks.py file but it didn't work. Another problem I am having, which may be related is when I launch the luigi scheduler through cmd using:

```<code>luigid
</code>```

it works fine but whenever I try to start it using:

```<code>luigid --background
</code>```

I get the following error:

```<code>No module named pwd
</code>```

It seems like there is something wrong with my setup overall, any help would be appreciated.

答:
Take the examples directory in the luigi repository (git clone ... and you have the luigi directory). There you can find a few different examples, among them:

hello_world.py contains stuff like task_namespace = 'examples' (that's the same as the python module examples in the repository where all these python files are saved):

this could be executed using just the luigi command (no need to have the daemon luigid) from the outside of the python module examples as: cd luigi && PYTHONPATH=. luigi --module examples.hello_world examples.HelloWorldTask --local-scheduler

top_artists.py does not contain any reference to things like task_namespace:

this could be run from within the python module examples: cd luigi/examples && PYTHONPATH='.' luigi --module top_artists AggregateArtists --local-scheduler --date-interval 2012-06

This worked for me using miniconda (similar to anaconda) and cygwin, but I think it could work even if you don't use cygwin (maybe powershell or cmd don't allow you to concatenate commands using && but you can always run those commands one after the other).

I am not sure of the reasons/explanations, but to troubleshoot a bit this behaviour you could play with hello_world.py and run it as cd luigi/examples && PYTHONPATH=. luigi --module hello_world HelloWorldTask --local-scheduler (please note that the luigi command is invoked without examples. as the prefix for the command parameters), this will give the following exception:

```<code>raise TaskClassNotFoundException(cls._missing_task_msg(name))
luigi.task_register.TaskClassNotFoundException: No task HelloWorldTask. Candidates are: Config,ExternalTask,RangeBase,RangeByMinutes,RangeByMinutesBase,RangeDaily,RangeDailyBase,RangeHourly,RangeHourlyBase,Task,TestNotificationsTask,WrapperTask,batch_email,core,email,examples.HelloWorldTask,execution_summary,retcode,scheduler,sendgrid,smtp,worker
</code>```

To give some hints to the other issue you have with the daemon, I start it on cygwin with a command like this: luigid &. That ampersand suffix gives you back the command line prompt. To check which PID is associated to the daemon then I still use the same command line prompt on cygwin and I run ps aux | grep luigid. This approach probably will work ONLY on cygwin (because of some bash related internals).

Body:
I am having problems running a Luigi task through the Windows cmd. Here are the facts:

Running Anaconda installed in C:\ProgramData\Anaconda2 (Python 2.7)

Anaconda has added its paths to the PATH variable but there is no PYTHONPATH variable

The task i am trying to run is located in C:\....\tasks.py

Trying to run it as follows:

C:\.... luigi --module tasks MyTask --dt 20170316

  ImportError: No module named tasks

I tried creating a PYTHONPATH variable and adding the exact path to the directory containing my tasks.py file but it didn't work. Another problem I am having, which may be related is when I launch the luigi scheduler through cmd using:

luigid

it works fine but whenever I try to start it using:

luigid --background

I get the following error:

No module named pwd

It seems like there is something wrong with my setup overall, any help would be appreciated.

Body:
Take the examples directory in the luigi repository (git clone ... and you have the luigi directory). There you can find a few different examples, among them:

hello_world.py contains stuff like task_namespace = 'examples' (that's the same as the python module examples in the repository where all these python files are saved):

this could be executed using just the luigi command (no need to have the daemon luigid) from the outside of the python module examples as: cd luigi && PYTHONPATH=. luigi --module examples.hello_world examples.HelloWorldTask --local-scheduler

top_artists.py does not contain any reference to things like task_namespace:

this could be run from within the python module examples: cd luigi/examples && PYTHONPATH='.' luigi --module top_artists AggregateArtists --local-scheduler --date-interval 2012-06

This worked for me using miniconda (similar to anaconda) and cygwin, but I think it could work even if you don't use cygwin (maybe powershell or cmd don't allow you to concatenate commands using && but you can always run those commands one after the other).

I am not sure of the reasons/explanations, but to troubleshoot a bit this behaviour you could play with hello_world.py and run it as cd luigi/examples && PYTHONPATH=. luigi --module hello_world HelloWorldTask --local-scheduler (please note that the luigi command is invoked without examples. as the prefix for the command parameters), this will give the following exception:

raise TaskClassNotFoundException(cls._missing_task_msg(name))
luigi.task_register.TaskClassNotFoundException: No task HelloWorldTask. Candidates are: Config,ExternalTask,RangeBase,RangeByMinutes,RangeByMinutesBase,RangeDaily,RangeDailyBase,RangeHourly,RangeHourlyBase,Task,TestNotificationsTask,WrapperTask,batch_email,core,email,examples.HelloWorldTask,execution_summary,retcode,scheduler,sendgrid,smtp,worker

To give some hints to the other issue you have with the daemon, I start it on cygwin with a command like this: luigid &. That ampersand suffix gives you back the command line prompt. To check which PID is associated to the daemon then I still use the same command line prompt on cygwin and I run ps aux | grep luigid. This approach probably will work ONLY on cygwin (because of some bash related internals).


问:
MATLAB: Rearranging feature matrix
I have a feature matrix of size ~1M x 3 where the columns are doc#,wordID#,wordcount

What's a fast way in Matlab to rearrange this feature matrix so it is instead of size #docs x # unique words i.e.

(length(unique(featurematrix(:,1))) x length(unique(featurematrix(:,2)))

so that each row instead represents an entire document, each column represents a different word, and the values are the wordcounts from the 3rd column of the original matrix?

I started writing a bunch of loops, but had the feeling there's probably some short idiomatic way to do this already built-in to Matlab.

答:
You can actually use accumarray to accomplish this

```<code>data = [1, 1, 1;
        1, 2, 2;
        1, 5, 3;
        2, 1, 4;
        2, 3, 5];

result = accumarray(data(:,1:2), data(:,3))
%   1     2     0     0     3
%   4     0     5     0     0
</code>```

Alternately you could use sparse

```<code>result = full(sparse(data(:,1), data(:,2), data(:,3)))
</code>```

Title: MATLAB: Rearranging feature matrix

Body:
You can actually use accumarray to accomplish this

data = [1, 1, 1;
        1, 2, 2;
        1, 5, 3;
        2, 1, 4;
        2, 3, 5];

result = accumarray(data(:,1:2), data(:,3))
%   1     2     0     0     3
%   4     0     5     0     0

Alternately you could use sparse

result = full(sparse(data(:,1), data(:,2), data(:,3)))


问:
How to close all opened drivers in Selenium?
I need to close all open Chrome drivers in Selenium. All my methods are closing only one of them. The reason why I need to close all drivers at the same time - in the start of my program I don't know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle.

How I opened these drivers:

```<code>WebDriver driver = new ChromeDriver();
driver.get(firstURL);

driver = new ChromeDriver();
driver.get(secondURL);
</code>```

How I tried to close both drivers:

First try:

```<code>driver.close();
</code>```

Second try:

```<code>driver.quit();
</code>```

Third try:

```<code>driver.close();
driver.close();
</code>```

Fourth try:

```<code>driver.quit();
driver.quit();
</code>```

答:
First let's look at your code:

```<code>WebDriver driver = new ChromeDriver();
driver.get(firstURL);

driver = new ChromeDriver();
driver.get(secondURL);
</code>```

Here is what is happening:

You open a new Chrome instance.

You then do something with that instance: navigate to a website.

The next step, several things are happening: you open a new Chrome instance, and you overwrite the reference to the previous instance you opened. Essentially, at this point you lost track of the first browser you just opened!

You now do something with the second opened instance: navigate to a website.

From you question it is not clear what exactly you are trying to accomplish. You have several options:

Open one instance of a browser before your test. If you are using, for example JUnit, this is often done in the @Before method.

Do some work in your test.

Close the browser after the test. Again in JUnit, this wold be done in the @After method.

Another alternative is that you may legitimately need multiple browsers. You will need to keep track of all of them.

You could create a List of drivers, and every time you open a new one, add it to that list.

At the end of your tests, iterate over that list, and close all of them.

Body:
I need to close all open Chrome drivers in Selenium. All my methods are closing only one of them. The reason why I need to close all drivers at the same time - in the start of my program I don't know how many drivers I need to open, so I try to open a few drivers with same driver names in cycle.

How I opened these drivers:

WebDriver driver = new ChromeDriver();
driver.get(firstURL);

driver = new ChromeDriver();
driver.get(secondURL);

How I tried to close both drivers:

First try:

driver.close();

Second try:

driver.quit();

Third try:

driver.close();
driver.close();

Fourth try:

driver.quit();
driver.quit();

Body:
First let's look at your code:

WebDriver driver = new ChromeDriver();
driver.get(firstURL);

driver = new ChromeDriver();
driver.get(secondURL);

Here is what is happening:

You open a new Chrome instance.

You then do something with that instance: navigate to a website.

The next step, several things are happening: you open a new Chrome instance, and you overwrite the reference to the previous instance you opened. Essentially, at this point you lost track of the first browser you just opened!

You now do something with the second opened instance: navigate to a website.

From you question it is not clear what exactly you are trying to accomplish. You have several options:

Open one instance of a browser before your test. If you are using, for example JUnit, this is often done in the @Before method.

Do some work in your test.

Close the browser after the test. Again in JUnit, this wold be done in the @After method.

Another alternative is that you may legitimately need multiple browsers. You will need to keep track of all of them.

You could create a List of drivers, and every time you open a new one, add it to that list.

At the end of your tests, iterate over that list, and close all of them.


问:
.net / c# test wanted for a non techical MD
Dear all i am looking for an half finished .net application to test my .net c# applicants.

As I come from a differnt coding background, it is difficult for me to assess people skills hence a great test would do a good job!

Regarding checking candidates' test performance, I can ask a friend, no problem !

Does a practical test exist out there? Would I need to pay for it?

答:
I would recommend giving the applicant a small problem to solve during the interview. Have them write out a solution to the problem on the white board in pseudo code and have them explain their thought process.

Once they've done that, then give them access to a computer with the necessary tools installed and watch them code up the solution.

My favorite interview problem is converting to roman numerals.

OwnerDisplayName: frank publisher

LastEditorDisplayName: Tom Anderson

OwnerDisplayName: Stever B


问:
how to debug the code which is hang
I have a multithreaded code which is hang in some case. I want to know what's the recommended way to debug?</p>

答:
When it hangs, you can attach the debugger and inspect thread state, including callstacks, to your heart's content.  Often there will be one (or more) thread(s) that is (are) in a wait state, and you might be able to work out why that is.

If the state is not self-explanatory at the time of the hang, you can resort to techniques suggested to provide context information for the preceding program flow.

Title: how to debug the code which is hang