问:
"Connection refused! Is selenium server started?" error in VueJS Nightwatch E2E tests using ChromeDriver and Chrome
I have a VueJS app that has the default Nightwatch E2E tests. I just spent some time getting user accounts and auth set up. After doing so, when I try to run my E2E tests, they fail mysteriously. Here's the command line output I get:

```<code>code/premium-poker-tools [master●] » npm run e2e

> premium-poker-tools@1.0.0 e2e /Users/adamzerner/code/premium-poker-tools
> node test/e2e/runner.js

> Starting dev server...

Starting to optimize CSS...
> Listening at http://localhost:8080

Starting selenium server... started - PID:  58502
[BABEL] Note: The code generator has deoptimised the styling of "/Users/adamzerner/code/premium-poker-tools/test/e2e/specs/hit-calculator.js" as it exceeds the max of "500KB".

  player
1
2
3
    1) "before all" hook

  0 passing (2s)
  1 failing

  1) player "before all" hook:
     Connection refused! Is selenium server started?

npm ERR! code ELIFECYCLE
npm ERR! errno 10
npm ERR! premium-poker-tools@1.0.0 e2e: `node test/e2e/runner.js`
npm ERR! Exit status 10
npm ERR!
npm ERR! Failed at the premium-poker-tools@1.0.0 e2e script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/adamzerner/.npm/_logs/2019-05-23T19_47_08_016Z-debug.log
code/premium-poker-tools [master●] »
</code>```

And here is /Users/adamzerner/.npm/_logs/2019-05-27T17_44_07_557Z-debug.log:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/Cellar/node/11.11.0/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'run',
1 verbose cli   'e2e' ]
2 info using npm@6.9.0
3 info using node@v11.11.0
4 verbose run-script [ 'pree2e', 'e2e', 'poste2e' ]
5 info lifecycle premium-poker-tools@1.0.0~pree2e: premium-poker-tools@1.0.0
6 info lifecycle premium-poker-tools@1.0.0~e2e: premium-poker-tools@1.0.0
7 verbose lifecycle premium-poker-tools@1.0.0~e2e: unsafe-perm in lifecycle true
8 verbose lifecycle premium-poker-tools@1.0.0~e2e: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/adamzerner/code/premium-poker-tools/node_modules/.bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/adamzerner/.rvm/bin
9 verbose lifecycle premium-poker-tools@1.0.0~e2e: CWD: /Users/adamzerner/code/premium-poker-tools
10 silly lifecycle premium-poker-tools@1.0.0~e2e: Args: [ '-c', 'node test/e2e/runner.js' ]
11 silly lifecycle premium-poker-tools@1.0.0~e2e: Returned: code: 10  signal: null
12 info lifecycle premium-poker-tools@1.0.0~e2e: Failed to exec e2e script
13 verbose stack Error: premium-poker-tools@1.0.0 e2e: `node test/e2e/runner.js`
13 verbose stack Exit status 10
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:197:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:197:13)
13 verbose stack     at maybeClose (internal/child_process.js:984:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:265:5)
14 verbose pkgid premium-poker-tools@1.0.0
15 verbose cwd /Users/adamzerner/code/premium-poker-tools
16 verbose Darwin 18.6.0
17 verbose argv "/usr/local/Cellar/node/11.11.0/bin/node" "/usr/local/bin/npm" "run" "e2e"
18 verbose node v11.11.0
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 10
22 error premium-poker-tools@1.0.0 e2e: `node test/e2e/runner.js`
22 error Exit status 10
23 error Failed at the premium-poker-tools@1.0.0 e2e script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 10, true ]
</code>```

For one, the Connection refused! Is selenium server started? error seems wrong. Above that it says Starting selenium server... started - PID:  58502, and I see a Chrome browser pop up very briefly and then immediately close.

Here is the code for the before block in question:

```<code>before(function (browser, done) {
  console.log(1);
  equityCalculator = browser.page['equity-calculator']();
  console.log(2);
  equityCalculator.navigate();
  console.log(3);
  browser.pause(20000);
  equityCalculator
    .waitForElementVisible('@app', 50000, function () {
      console.log(4);
      browser.resizeWindow(1440, 852, function () {
        console.log(5);
        done();
      });
    })
  ;
});
</code>```

I've been trying to pin down where the problem occurs, but I'm having a lot of trouble. 1, 2, and 3 get logged out, but not 4 or 5, so that helps. But if 3 gets logged out, why isn't browser.pause(20000) working?

I've also been trying to mess around in my actual code to see where the issue is. I tried some alert statements in main.js to try to pinpoint the issue:

```<code>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
alert(1);

window.$ = require('jquery');
require('bootstrap');

alert(2);

import Vue from 'vue';
import store from '@/store';
import App from './App';
import router from './router';
import monkeyPatches from '@/services/monkey-patches';
import axios from 'axios';
import VueAxios from 'vue-axios';

alert(3);

Vue.config.productionTip = false
Vue.use(VueAxios, axios);
axios.interceptors.request.use(
  function(config) {
    config.withCredentials = true;
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router: router,
  store: store,
  template: '<App/>',
  components: { App }
});

$(function () {
  $('[data-toggle="popover"]').popover();
});

// if (navigator.serviceWorker) {
//   navigator.serviceWorker.register('/service-worker.js').catch(function() {
//     console.log('Service worker registration failed.');
//   });
// }
</code>```

But weirdly, alert(1) isn't even working. So I feel at a loss. From what I understand, the top of main.js is the "beginning" of a Vue app, and if it's not even reaching that point, what is going on? equityCalculator = browser.page['equity-calculator'](); and equityCalculator.navigate(); seem pretty standard. Here's a snippet of the page object:

```<code>module.exports = {
  url: 'http://localhost:8080/equity-calculator',
  elements: {
    'app': '#app',
</code>```

When I start my dev server and go to that url, it totally works. And my E2E tests were all working perfectly before I implemented user accounts and auth, I didn't change this file, and yet now I'm having the issue.

I'm not sure where I can go from here. Help!

Update:

Excerpt from package.json:

```<code>{
  ...
  "dependencies": {
    ...
    "chromedriver": "^2.45.0",
    "cross-spawn": "^6.0.5",
    "nightwatch": "^0.9.21",
    "selenium-server": "^3.141.59",
  },
}
</code>```

Here's nightwatch.conf.js:

```<code>require('babel-register')
let config = require('../../config')

// http://nightwatchjs.org/gettingstarted#settings-file
module.exports = {
  src_folders: ['test/e2e/specs'],
  output_folder: 'test/e2e/reports',
  custom_assertions_path: ['test/e2e/custom-assertions'],
  page_objects_path: 'test/e2e/page-objects',
  globals_path: 'test/e2e/globals.js',
  test_runner : 'mocha',

  selenium: {
    start_process: true,
    server_path: require('selenium-server').path,
    host: '127.0.0.1',
    port: 4444,
    cli_args: {
      'webdriver.chrome.driver': require('chromedriver').path
    }
  },

  test_settings: {
    default: {
      selenium_port: 4444,
      selenium_host: 'localhost',
      silent: true,
      globals: {
        devServerURL: 'http://localhost:' + (process.env.PORT || config.dev.port),
        handStrings: [
          'aa', 'aks', 'aqs', 'ajs', 'ats', 'a9s', 'a8s', 'a7s', 'a6s', 'a5s', 'a4s', 'a3s', 'a2s',
          'ako', 'kk', 'kqs', 'kjs', 'kts', 'k9s', 'k8s', 'k7s', 'k6s', 'k5s', 'k4s', 'k3s', 'k2s',
          'aqo', 'kqo', 'qq', 'qjs', 'qts', 'q9s', 'q8s', 'q7s', 'q6s', 'q5s', 'q4s', 'q3s', 'q2s',
          'ajo', 'kjo', 'qjo', 'jj', 'jts', 'j9s', 'j8s', 'j7s', 'j6s', 'j5s', 'j4s', 'j3s', 'j2s',
          'ato', 'kto', 'qto', 'jto', 'tt', 't9s', 't8s', 't7s', 't6s', 't5s', 't4s', 't3s', 't2s',
          'a9o', 'k9o', 'q9o', 'j9o', 't9o', '99', '98s', '97s', '96s', '95s', '94s', '93s', '92s',
          'a8o', 'k8o', 'q8o', 'j8o', 't8o', '98o', '88', '87s', '86s', '85s', '84s', '83s', '82s',
          'a7o', 'k7o', 'q7o', 'j7o', 't7o', '97o', '87o', '77', '76s', '75s', '74s', '73s', '72s',
          'a6o', 'k6o', 'q6o', 'j6o', 't6o', '96o', '86o', '76o', '66', '65s', '64s', '63s', '62s',
          'a5o', 'k5o', 'q5o', 'j5o', 't5o', '95o', '85o', '75o', '65o', '55', '54s', '53s', '52s',
          'a4o', 'k4o', 'q4o', 'j4o', 't4o', '94o', '84o', '74o', '64o', '54o', '44', '43s', '42s',
          'a3o', 'k3o', 'q3o', 'j3o', 't3o', '93o', '83o', '73o', '63o', '53o', '43o', '33', '32s',
          'a2o', 'k2o', 'q2o', 'j2o', 't2o', '92o', '82o', '72o', '62o', '52o', '42o', '32o', '22',
        ],
      }
    },

    chrome: {
      desiredCapabilities: {
        browserName: 'chrome',
        javascriptEnabled: true,
        acceptSslCerts: true
      }
    },

    firefox: {
      desiredCapabilities: {
        browserName: 'firefox',
        javascriptEnabled: true,
        acceptSslCerts: true
      }
    }
  }
}
</code>```

And for Java/JDK:

```<code>code/premium-poker-tools-api [master] » java --version
java 9.0.4
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)
</code>```

When I look in my Java Control Panel, it says that I'm up to date.

I'm not sure how to figure out which Selenium version or Chrome version I'm using. For Chrome, if I open up Chrome and go to "About Google Chrome" it says 74.0.3729.169, the up to date one, and I assume my tests are using that same version.

答:
This log message...

```<code>Starting selenium server... started - PID:  58502
</code>```

and the subsequent error message...

```<code>Connection refused! Is selenium server started?
</code>```

...implies that the WebDriver instance i.e. ChromeDriver though initiated but was unable to communicate with the WebBrowsing i.e. Chrome session.

Some more details about the:

Selenium version.

JDK version.

Selenium Server mode (Standalone/Grid).

ChromeDriver version.

Chrome version.

Would have helped us to debug the issue in a better way. However as you have mentioned "1, 2, and 3 get logged out, but not 4 or 5", possibly the issue stems out from the following code block:

```<code>equityCalculator
  .waitForElementVisible('@app', 50000, function () {
    console.log(4);
    browser.resizeWindow(1440, 852, function () {
      console.log(5);
      done();
    });
  })
</code>```

Reason

As per the discussion Connection refused! Is selenium server started nightwatch on edge your main issue seems to be incompatibility between the version of the binaries you are using.

Solution

Upgrade JDK to  recent levels JDK 8u212.

Upgrade Selenium to  current levels Version 3.141.59.

Upgrade ChromeDriver to  ChromeDriver v74.0 level.

Upgrade Chrome version to Chrome v74 levels. (as per ChromeDriver v74.0 release notes)

Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.

If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.

Take a System Reboot.

Execute your @Test.

Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Outro

'Connection refused! Is selenium server started?\n' while running Nightwatch.js tests against Selenium Grid

Resolution

updating npm resolved the issue (as per OP's comments)

```<code>npm update
</code>```

Body:
I have a VueJS app that has the default Nightwatch E2E tests. I just spent some time getting user accounts and auth set up. After doing so, when I try to run my E2E tests, they fail mysteriously. Here's the command line output I get:

code/premium-poker-tools [master●] » npm run e2e

> premium-poker-tools@1.0.0 e2e /Users/adamzerner/code/premium-poker-tools
> node test/e2e/runner.js

> Starting dev server...

Starting to optimize CSS...
> Listening at http://localhost:8080

Starting selenium server... started - PID:  58502
[BABEL] Note: The code generator has deoptimised the styling of "/Users/adamzerner/code/premium-poker-tools/test/e2e/specs/hit-calculator.js" as it exceeds the max of "500KB".

  player
1
2
3
    1) "before all" hook

  0 passing (2s)
  1 failing

  1) player "before all" hook:
     Connection refused! Is selenium server started?

npm ERR! code ELIFECYCLE
npm ERR! errno 10
npm ERR! premium-poker-tools@1.0.0 e2e: `node test/e2e/runner.js`
npm ERR! Exit status 10
npm ERR!
npm ERR! Failed at the premium-poker-tools@1.0.0 e2e script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/adamzerner/.npm/_logs/2019-05-23T19_47_08_016Z-debug.log
code/premium-poker-tools [master●] »

And here is /Users/adamzerner/.npm/_logs/2019-05-27T17_44_07_557Z-debug.log:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/Cellar/node/11.11.0/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'run',
1 verbose cli   'e2e' ]
2 info using npm@6.9.0
3 info using node@v11.11.0
4 verbose run-script [ 'pree2e', 'e2e', 'poste2e' ]
5 info lifecycle premium-poker-tools@1.0.0~pree2e: premium-poker-tools@1.0.0
6 info lifecycle premium-poker-tools@1.0.0~e2e: premium-poker-tools@1.0.0
7 verbose lifecycle premium-poker-tools@1.0.0~e2e: unsafe-perm in lifecycle true
8 verbose lifecycle premium-poker-tools@1.0.0~e2e: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/adamzerner/code/premium-poker-tools/node_modules/.bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/adamzerner/.rvm/bin
9 verbose lifecycle premium-poker-tools@1.0.0~e2e: CWD: /Users/adamzerner/code/premium-poker-tools
10 silly lifecycle premium-poker-tools@1.0.0~e2e: Args: [ '-c', 'node test/e2e/runner.js' ]
11 silly lifecycle premium-poker-tools@1.0.0~e2e: Returned: code: 10  signal: null
12 info lifecycle premium-poker-tools@1.0.0~e2e: Failed to exec e2e script
13 verbose stack Error: premium-poker-tools@1.0.0 e2e: `node test/e2e/runner.js`
13 verbose stack Exit status 10
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:197:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:197:13)
13 verbose stack     at maybeClose (internal/child_process.js:984:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:265:5)
14 verbose pkgid premium-poker-tools@1.0.0
15 verbose cwd /Users/adamzerner/code/premium-poker-tools
16 verbose Darwin 18.6.0
17 verbose argv "/usr/local/Cellar/node/11.11.0/bin/node" "/usr/local/bin/npm" "run" "e2e"
18 verbose node v11.11.0
19 verbose npm  v6.9.0
20 error code ELIFECYCLE
21 error errno 10
22 error premium-poker-tools@1.0.0 e2e: `node test/e2e/runner.js`
22 error Exit status 10
23 error Failed at the premium-poker-tools@1.0.0 e2e script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 10, true ]

For one, the Connection refused! Is selenium server started? error seems wrong. Above that it says Starting selenium server... started - PID:  58502, and I see a Chrome browser pop up very briefly and then immediately close.

Here is the code for the before block in question:

before(function (browser, done) {
  console.log(1);
  equityCalculator = browser.page['equity-calculator']();
  console.log(2);
  equityCalculator.navigate();
  console.log(3);
  browser.pause(20000);
  equityCalculator
    .waitForElementVisible('@app', 50000, function () {
      console.log(4);
      browser.resizeWindow(1440, 852, function () {
        console.log(5);
        done();
      });
    })
  ;
});

I've been trying to pin down where the problem occurs, but I'm having a lot of trouble. 1, 2, and 3 get logged out, but not 4 or 5, so that helps. But if 3 gets logged out, why isn't browser.pause(20000) working?

I've also been trying to mess around in my actual code to see where the issue is. I tried some alert statements in main.js to try to pinpoint the issue:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
alert(1);

window.$ = require('jquery');
require('bootstrap');

alert(2);

import Vue from 'vue';
import store from '@/store';
import App from './App';
import router from './router';
import monkeyPatches from '@/services/monkey-patches';
import axios from 'axios';
import VueAxios from 'vue-axios';

alert(3);

Vue.config.productionTip = false
Vue.use(VueAxios, axios);
axios.interceptors.request.use(
  function(config) {
    config.withCredentials = true;
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router: router,
  store: store,
  template: '<App/>',
  components: { App }
});

$(function () {
  $('[data-toggle="popover"]').popover();
});

// if (navigator.serviceWorker) {
//   navigator.serviceWorker.register('/service-worker.js').catch(function() {
//     console.log('Service worker registration failed.');
//   });
// }

But weirdly, alert(1) isn't even working. So I feel at a loss. From what I understand, the top of main.js is the "beginning" of a Vue app, and if it's not even reaching that point, what is going on? equityCalculator = browser.page['equity-calculator'](); and equityCalculator.navigate(); seem pretty standard. Here's a snippet of the page object:

module.exports = {
  url: 'http://localhost:8080/equity-calculator',
  elements: {
    'app': '#app',

When I start my dev server and go to that url, it totally works. And my E2E tests were all working perfectly before I implemented user accounts and auth, I didn't change this file, and yet now I'm having the issue.

I'm not sure where I can go from here. Help!

Update:

Excerpt from package.json:

{
  ...
  "dependencies": {
    ...
    "chromedriver": "^2.45.0",
    "cross-spawn": "^6.0.5",
    "nightwatch": "^0.9.21",
    "selenium-server": "^3.141.59",
  },
}

Here's nightwatch.conf.js:

require('babel-register')
let config = require('../../config')

// http://nightwatchjs.org/gettingstarted#settings-file
module.exports = {
  src_folders: ['test/e2e/specs'],
  output_folder: 'test/e2e/reports',
  custom_assertions_path: ['test/e2e/custom-assertions'],
  page_objects_path: 'test/e2e/page-objects',
  globals_path: 'test/e2e/globals.js',
  test_runner : 'mocha',

  selenium: {
    start_process: true,
    server_path: require('selenium-server').path,
    host: '127.0.0.1',
    port: 4444,
    cli_args: {
      'webdriver.chrome.driver': require('chromedriver').path
    }
  },

  test_settings: {
    default: {
      selenium_port: 4444,
      selenium_host: 'localhost',
      silent: true,
      globals: {
        devServerURL: 'http://localhost:' + (process.env.PORT || config.dev.port),
        handStrings: [
          'aa', 'aks', 'aqs', 'ajs', 'ats', 'a9s', 'a8s', 'a7s', 'a6s', 'a5s', 'a4s', 'a3s', 'a2s',
          'ako', 'kk', 'kqs', 'kjs', 'kts', 'k9s', 'k8s', 'k7s', 'k6s', 'k5s', 'k4s', 'k3s', 'k2s',
          'aqo', 'kqo', 'qq', 'qjs', 'qts', 'q9s', 'q8s', 'q7s', 'q6s', 'q5s', 'q4s', 'q3s', 'q2s',
          'ajo', 'kjo', 'qjo', 'jj', 'jts', 'j9s', 'j8s', 'j7s', 'j6s', 'j5s', 'j4s', 'j3s', 'j2s',
          'ato', 'kto', 'qto', 'jto', 'tt', 't9s', 't8s', 't7s', 't6s', 't5s', 't4s', 't3s', 't2s',
          'a9o', 'k9o', 'q9o', 'j9o', 't9o', '99', '98s', '97s', '96s', '95s', '94s', '93s', '92s',
          'a8o', 'k8o', 'q8o', 'j8o', 't8o', '98o', '88', '87s', '86s', '85s', '84s', '83s', '82s',
          'a7o', 'k7o', 'q7o', 'j7o', 't7o', '97o', '87o', '77', '76s', '75s', '74s', '73s', '72s',
          'a6o', 'k6o', 'q6o', 'j6o', 't6o', '96o', '86o', '76o', '66', '65s', '64s', '63s', '62s',
          'a5o', 'k5o', 'q5o', 'j5o', 't5o', '95o', '85o', '75o', '65o', '55', '54s', '53s', '52s',
          'a4o', 'k4o', 'q4o', 'j4o', 't4o', '94o', '84o', '74o', '64o', '54o', '44', '43s', '42s',
          'a3o', 'k3o', 'q3o', 'j3o', 't3o', '93o', '83o', '73o', '63o', '53o', '43o', '33', '32s',
          'a2o', 'k2o', 'q2o', 'j2o', 't2o', '92o', '82o', '72o', '62o', '52o', '42o', '32o', '22',
        ],
      }
    },

    chrome: {
      desiredCapabilities: {
        browserName: 'chrome',
        javascriptEnabled: true,
        acceptSslCerts: true
      }
    },

    firefox: {
      desiredCapabilities: {
        browserName: 'firefox',
        javascriptEnabled: true,
        acceptSslCerts: true
      }
    }
  }
}

And for Java/JDK:

code/premium-poker-tools-api [master] » java --version
java 9.0.4
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode)

When I look in my Java Control Panel, it says that I'm up to date.

I'm not sure how to figure out which Selenium version or Chrome version I'm using. For Chrome, if I open up Chrome and go to "About Google Chrome" it says 74.0.3729.169, the up to date one, and I assume my tests are using that same version.

Body:
This log message...

Starting selenium server... started - PID:  58502

and the subsequent error message...

Connection refused! Is selenium server started?

...implies that the WebDriver instance i.e. ChromeDriver though initiated but was unable to communicate with the WebBrowsing i.e. Chrome session.

Some more details about the:

Selenium version.

JDK version.

Selenium Server mode (Standalone/Grid).

ChromeDriver version.

Chrome version.

Would have helped us to debug the issue in a better way. However as you have mentioned "1, 2, and 3 get logged out, but not 4 or 5", possibly the issue stems out from the following code block:

equityCalculator
  .waitForElementVisible('@app', 50000, function () {
    console.log(4);
    browser.resizeWindow(1440, 852, function () {
      console.log(5);
      done();
    });
  })

Reason

As per the discussion Connection refused! Is selenium server started nightwatch on edge your main issue seems to be incompatibility between the version of the binaries you are using.

Solution

Upgrade JDK to  recent levels JDK 8u212.

Upgrade Selenium to  current levels Version 3.141.59.

Upgrade ChromeDriver to  ChromeDriver v74.0 level.

Upgrade Chrome version to Chrome v74 levels. (as per ChromeDriver v74.0 release notes)

Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.

If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.

Take a System Reboot.

Execute your @Test.

Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Outro

'Connection refused! Is selenium server started?\n' while running Nightwatch.js tests against Selenium Grid

Resolution

updating npm resolved the issue (as per OP's comments)

npm update


来源: stackexchange

问:
NSDate, NSCalendar and NSDateComponents timing
```<code>NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+2"]];

NSDateComponents *dateComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];

NSInteger day = [dateComponents day];
NSInteger month = [dateComponents month];
NSInteger year = [dateComponents year];

 NSLog(@" %i %i %i ", day, month, year);
</code>```

That code show me "12 2147483647 2147483647"

How can I get the month and year (integer)

How can add/forward one day? (if we are the first of the month too!)

Thant you for your attention :-)

答:
Add more units to NSDayCalendarUnit | NSWeekdayCalendarUnit - you are not requesting month or year, therefore they are invalid!

Add/subtract a NSDateComponents object configured for 1 day and [NSCalendar dateByAddingComponents:toDate:options:]. Alternatively, and probably just as correct, use [NSDate dateWithTimeInterval:sinceDate:]

ContentLicense: CC BY-SA 3.0

Body:
NSDate *today = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+2"]];

NSDateComponents *dateComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];

NSInteger day = [dateComponents day];
NSInteger month = [dateComponents month];
NSInteger year = [dateComponents year];

 NSLog(@" %i %i %i ", day, month, year);

That code show me "12 2147483647 2147483647"

How can I get the month and year (integer)

How can add/forward one day? (if we are the first of the month too!)

Thant you for your attention :-)


问:
Wordpress - Create Page with custom CSS and JS only
I am creating a Wordpress plugin that adds a page that embeds a React app.

On plugin activation, a post is inserted with wp_insert_post() function, and then the load_app_template() function is triggered to set the post template.
This template contains wp_head() in the head section and my React app.

The problem is that some other plugins are loading some JS and CSS in the head that are disturbing the React app behavior. I am trying to remove all JS and CSS given by Wordpress & other plugins and add my own.

If I remove wp_head() from the post template, then I cannot register styles and scripts with my plugin through wp_register_script.

How to remove all JS and CSS from Wordpress and plugins and add my own from my plugin ?

There could be two ways :

Remove wp_head() and manually add links to my JS and CSS in the HTML template. I can do that for Jquery and Bootstrap but I don't know how to put links of JS files from my plugin directory.

Keep wp_head(), deregister all CSS and JS and add my own afterwards with Wordpress hooks. I am not able to remove some Javascript from other plugins with this solution. I tried deregistering all following this answer.

Thank you !

答:
Try to remove unnecessary scripts and styles using wordpress hooks
(this might help you figure out how to do so: https://wordpress.stackexchange.com/questions/233140/how-can-i-get-a-list-of-all-enqueued-scripts-and-styles) if your template is used on page.</p>

ContentLicense: CC BY-SA 4.0


问:
TextField uppercase and lowercase validation
I am working on textfields validations and getting confused how to validate textfield must contain at least 1 character from all of the following categories:
English uppercase characters (A - Z).
English lowercase characters (a - z).</p>

答:
Credit : TextField uppercase and lowercase validation

Here is the regext for the condition :- Minimum 8 characters, 1 uppercase and 1 number.

^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[$@$!%?&])[A-Za-z\d$@$!%?&]{8,}

```<code>extension String {
func isValidPassword() -> Bool {
    let regularExpression = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}"
    let passwordValidation = NSPredicate.init(format: "SELF MATCHES %@", regularExpression)

    return passwordValidation.evaluate(with: self)
    }
}

//Example 1

var password = "@Abcdef011" //string from UITextField (Password)
password.isValidPassword() // -> true

//Example 2

var password = "wer011" //string from UITextField
password.isValidPassword() // -> false
</code>```

Body:
Credit : TextField uppercase and lowercase validation

Here is the regext for the condition :- Minimum 8 characters, 1 uppercase and 1 number.

^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[$@$!%?&])[A-Za-z\d$@$!%?&]{8,}

extension String {
func isValidPassword() -> Bool {
    let regularExpression = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&])[A-Za-z\\d$@$!%*?&]{8,}"
    let passwordValidation = NSPredicate.init(format: "SELF MATCHES %@", regularExpression)

    return passwordValidation.evaluate(with: self)
    }
}

//Example 1

var password = "@Abcdef011" //string from UITextField (Password)
password.isValidPassword() // -> true

//Example 2

var password = "wer011" //string from UITextField
password.isValidPassword() // -> false


问:
Oracle : Selecting date by month with where clause
I came across a problem that in selecting the date for current desired month and year. I tried the 2 statements shown below but failed to execute the query

```<code>select to_char(sysdate, 'Month') from income

select * from income where to_char(sysdate,month) = 'feb'
</code>```

Update

But after researching and learning more in depth on oracle docs website. What i came out with is to use  "between" clause. Specifying the first day and last day of the month . Doing so, it will execute the desired month/year

For an example

```<code>SELECT column_name
FROM table_name where column_name = (Your own value) AND
column_date >= to_date('01/02/2012', 'dd/mm/yyyy')
and column_date <  to_date('01/03/2012', 'dd/mm/yyyy')
</code>```

I hope this help :)

答:
If you want to pass in a string like 'May 2012', then I would recommend:

```<code>select i.*
from income i
where i.datecol >= to_date('May 2012', 'Mon YYYY') and
      i.datecol < to_date('May 2012', 'Mon YYYY') + interval '1' month;
</code>```

That said, I think your application should turn the string value into a date range and you should use that range in your query:

```<code>select i.*
from income i
where i.datecol >= :datestart
      i.datecol < :dateend + interval '1 day';
</code>```

I strong encourage you to avoid between with dates, particularly in Oracle.  The date data type has a built-in time component, and that can throw off the comparisons.

Body:
I came across a problem that in selecting the date for current desired month and year. I tried the 2 statements shown below but failed to execute the query

select to_char(sysdate, 'Month') from income

select * from income where to_char(sysdate,month) = 'feb'

Update

But after researching and learning more in depth on oracle docs website. What i came out with is to use  "between" clause. Specifying the first day and last day of the month . Doing so, it will execute the desired month/year

For an example

SELECT column_name
FROM table_name where column_name = (Your own value) AND
column_date >= to_date('01/02/2012', 'dd/mm/yyyy')
and column_date <  to_date('01/03/2012', 'dd/mm/yyyy')

I hope this help :)

Body:
If you want to pass in a string like 'May 2012', then I would recommend:

select i.*
from income i
where i.datecol >= to_date('May 2012', 'Mon YYYY') and
      i.datecol < to_date('May 2012', 'Mon YYYY') + interval '1' month;

That said, I think your application should turn the string value into a date range and you should use that range in your query:

select i.*
from income i
where i.datecol >= :datestart
      i.datecol < :dateend + interval '1 day';

I strong encourage you to avoid between with dates, particularly in Oracle.  The date data type has a built-in time component, and that can throw off the comparisons.


问:
collapsing toolbar layout won't collapse
I have a collapsing toolbar layout that has 2 issues with it:

1) it is static and does not collapse and I can't find the reason why

2) the last row in the recyclerview is being shown half way offscreen, I think it should be fixed one the collapsing is fixed?

XML code:

```<code>
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Controllers.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/AppBarLayout"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
            app:contentScrim="@color/colorPrimary"
            app:title="Hero Title">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#000000" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hero Title"
                android:textStyle="bold"
                android:textSize="20dp"
                android:textColor="#ffffff"/>

            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="150dp"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Dark">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/herosRecyclerView"
        android:layout_width="395dp"
        android:layout_height="715dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</android.support.design.widget.CoordinatorLayout>

</code>```

and here is an image of what I mean by half offscreen:

https://imgur.com/Fz8TmKK

答:
Please try this. It will work.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorWhite"
        tools:context=".Controllers.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/AppBarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.design.widget.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:textAlignment="center"
                app:contentScrim="@color/colorPrimary"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                app:title="Hero Title">

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="150dp"
                    android:background="#000000"
                    app:layout_collapseMode="parallax"
                    app:layout_collapseParallaxMultiplier="0.7" />

                <android.support.v7.widget.Toolbar
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Dark">

                </android.support.v7.widget.Toolbar>

            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/herosRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </FrameLayout>

    </android.support.design.widget.CoordinatorLayout>
</code>```

Body:
I have a collapsing toolbar layout that has 2 issues with it:

1) it is static and does not collapse and I can't find the reason why

2) the last row in the recyclerview is being shown half way offscreen, I think it should be fixed one the collapsing is fixed?

XML code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Controllers.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/AppBarLayout"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|snap|exitUntilCollapsed"
            app:contentScrim="@color/colorPrimary"
            app:title="Hero Title">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#000000" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hero Title"
                android:textStyle="bold"
                android:textSize="20dp"
                android:textColor="#ffffff"/>

            <android.support.v7.widget.Toolbar
                android:layout_width="match_parent"
                android:layout_height="150dp"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Dark">

            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/herosRecyclerView"
        android:layout_width="395dp"
        android:layout_height="715dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</android.support.design.widget.CoordinatorLayout>

and here is an image of what I mean by half offscreen:

https://imgur.com/Fz8TmKK

Body:
Please try this. It will work.

<?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorWhite"
        tools:context=".Controllers.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/AppBarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.design.widget.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:textAlignment="center"
                app:contentScrim="@color/colorPrimary"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                app:title="Hero Title">

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="150dp"
                    android:background="#000000"
                    app:layout_collapseMode="parallax"
                    app:layout_collapseParallaxMultiplier="0.7" />

                <android.support.v7.widget.Toolbar
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Dark">

                </android.support.v7.widget.Toolbar>

            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/herosRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </FrameLayout>

    </android.support.design.widget.CoordinatorLayout>


问:
PHP IMagick RGB to CMYK inverts?
I'm trying to convert a RGB .gif to a CMYK .gif using IMagick PHP module.

I've wrote this piece of code

```<code>$i = new Imagick('mosaique.gif');
$i->setImageColorspace(Imagick::COLORSPACE_CMYK);
$i->setImageFormat('gif');
$i->writeImage('mosaique-cmyk.gif');
</code>```

But the resultant "mosaique-cmyk.gif" still a RGB... but with inverted colors (O_O)

What am I doing wrong?

EDIT:

I've tried with a .jpg and the image is converted to CMYK but it stills in negative.

EDIT 2:

I've tried to run my script making a .pdf on another server and it works fine.

Are there any known bug in IMagick?
Are there some options to set in the php5 library?

The version that returns me the inverted image is newer than the one that works correctly

WRONG RESULT
PHP 5.3.3
IMagick 3.0.0RC1
ImageMagick 6.6.2

CORRECT RESULT
PHP 5.2.10
IMagick 2.1.1
ImageMagick 6.5.1

答:
see here http://imagemagick.org/Usage/formats/#color_profile

convert cmyk_image.jpg -colorspace
  rgb rgb_image.jpg

ContentLicense: CC BY-SA 2.5

Title: PHP IMagick RGB to CMYK inverts?

Body:
I'm trying to convert a RGB .gif to a CMYK .gif using IMagick PHP module.

I've wrote this piece of code

$i = new Imagick('mosaique.gif');
$i->setImageColorspace(Imagick::COLORSPACE_CMYK);
$i->setImageFormat('gif');
$i->writeImage('mosaique-cmyk.gif');

But the resultant "mosaique-cmyk.gif" still a RGB... but with inverted colors (O_O)

What am I doing wrong?

EDIT:

I've tried with a .jpg and the image is converted to CMYK but it stills in negative.

EDIT 2:

I've tried to run my script making a .pdf on another server and it works fine.

Are there any known bug in IMagick?
Are there some options to set in the php5 library?

The version that returns me the inverted image is newer than the one that works correctly

WRONG RESULT
PHP 5.3.3
IMagick 3.0.0RC1
ImageMagick 6.6.2

CORRECT RESULT
PHP 5.2.10
IMagick 2.1.1
ImageMagick 6.5.1


问:
Sec:authorize doesn't work in spring security 4
i'm trying to use spring security. I created two users in memory admin and users.

```<code>auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
</code>```

This is my pom.xml:

```<code><dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>
</code>```

and this is my html page:

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/myStyle.css"/>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script type="text/javascript" src="js/myApp.js"></script>
<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
</head>
<body ng-app="myStockApp">
<div ng-controller="mainctr">
<div data-ng-init="listArticles()">

<div sec:authorize="hasRole('ROLE_ADMIN')">Only for admin</div>

//code ...
</code>```

I would like that only the admin sees that div, but when i logged as a user, the div above appears, or it should be disappear. can you tell me where is the probleme ? thank you.

答:
after searching and trying to understand the problem i found out that there is a problem with the dialect

you can see here how to add the dialect:
How do I add Thymeleaf SpringSecurityDialect to spring boot

tl;dr
add this to your config

```<code>    @Bean
 public SpringSecurityDialect securityDialect() {
     return new SpringSecurityDialect();
 }
</code>```

Body:
i'm trying to use spring security. I created two users in memory admin and users.

auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
        auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");

This is my pom.xml:

<dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>

and this is my html page:

<!DOCTYPE html>

<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" type="text/css" href="css/myStyle.css"/>

<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />

Only for admin

//code ...

I would like that only the admin sees that div, but when i logged as a user, the div above appears, or it should be disappear. can you tell me where is the probleme ? thank you.

Body:
after searching and trying to understand the problem i found out that there is a problem with the dialect

you can see here how to add the dialect:
How do I add Thymeleaf SpringSecurityDialect to spring boot

tl;dr
add this to your config

    @Bean
 public SpringSecurityDialect securityDialect() {
     return new SpringSecurityDialect();
 }


问:
GOP size does not correlate with actual latency
As far as I know, GOP size should correlate with observable video delay (latency). For example, if GOP size is 2, then delay in video should be near two seconds and so on, at least with CBR. But, when I set GOP size to 2, publish stream to ingest server, consume this stream and measure latency, it is between 0.8-1.2 seconds, not 2+ seconds as excepted. Increasing GOP size leads to same results: with GOP 4 latency is near 2.5 seconds, not 4 seconds.

How I measure this latency: stream working stopwatch from web-camera using OBS to ingest server and calculate difference between stopwatch value and value displayed in stream consumed from ingest. For greater measurement accuracy, I make a photo with stopwatch and actual image from ingest in one field of view.

My OBS settings is here:

Can you suggest, why do I get such results and how relevant is my statement about correlation between GOP size and video latency? Maybe, H264 settings like "zerolatency" makes some magic?

Thanks.

答: For streaming, each group of pictures is made of IPPPPPP --a key frame followed by some number of seconds' worth of P frames. In principle, an encoder need not incur a delay of any given length.  When you send constant bit rate streams, the delay happens because the encoder must sometimes recode some frames at a lower or higher bit rate.


问:
How to use own copy of static library in each shared library
I have some static library that I can't change or rebuild. The library uses global variables. Something like this:

```<code>//lib A
#include <iostream>

static int i = 0;

void printA(){
    std::cout << i++ << std::endl;
}
</code>```

I want to create two shared libraries that have their own "copy" of static library and its global state:

```<code>//lib B
#include "liba.h"

void printB(){
    printA();
}
</code>```

```<code>//lib C
#include "liba.h"

void printC(){
    printA();
}
</code>```

... and use them simultaneously:

```<code>#include "libb.h"
#include "libc.h"

int main(){
    printB();
    printB();
    printC();
    printC();
}
</code>```

I expect following output:

```<code>0
1
0
1
</code>```

.. but actually get:

```<code>0
1
2
3
</code>```

Seems like libB and libC share common counter variable. If had access to libA source code, I would rebuild it with -fvisibility=hidden. But unfortunately I have only binary.

Is there any way to achieve expected behavior without libA rebuilding?

答:
If LibA uses a static counter which libB and libC increment by calling printA, then there's no way to do what you want without object file manipulation or non-portable hacks.

The linker resolves all references to global variables (even statics) to the same symbol at link time.

If you're willing to manipulate object files, then the following should work for you:

```<code>$ objcopy --prefix-symbols=copy_ liba.a liba-copy.a
</code>```

```<code>#define printA copy_ printA
#include "liba.h"
/* ... */
</code>```

If you can get the symbols from the static library using nm (the name you'll be looking for will be in the form of <counter name>.<process ID>) and you do something like the following, then you can read and write the static counter variable at runtime:

```<code>int counter asm("<counter name>.<process ID>");
counter = 0;
</code>```

Note that this process will have to be repeated after every update of the library.

Body:
I have some static library that I can't change or rebuild. The library uses global variables. Something like this:

//lib A
#include <iostream>

static int i = 0;

void printA(){
    std::cout << i++ << std::endl;
}

I want to create two shared libraries that have their own "copy" of static library and its global state:

//lib B
#include "liba.h"

void printB(){
    printA();
}

//lib C
#include "liba.h"

void printC(){
    printA();
}

... and use them simultaneously:

#include "libb.h"
#include "libc.h"

int main(){
    printB();
    printB();
    printC();
    printC();
}

I expect following output:

0
1
0
1

.. but actually get:

0
1
2
3

Seems like libB and libC share common counter variable. If had access to libA source code, I would rebuild it with -fvisibility=hidden. But unfortunately I have only binary.

Is there any way to achieve expected behavior without libA rebuilding?

Body:
If LibA uses a static counter which libB and libC increment by calling printA, then there's no way to do what you want without object file manipulation or non-portable hacks.

The linker resolves all references to global variables (even statics) to the same symbol at link time.

If you're willing to manipulate object files, then the following should work for you:

$ objcopy --prefix-symbols=copy_ liba.a liba-copy.a

#define printA copy_ printA
#include "liba.h"
/* ... */

If you can get the symbols from the static library using nm (the name you'll be looking for will be in the form of <counter name>.<process ID>) and you do something like the following, then you can read and write the static counter variable at runtime:

int counter asm("<counter name>.<process ID>");
counter = 0;

Note that this process will have to be repeated after every update of the library.


问:
WPF 3D x-coordinate appears backwards
Using WPF 3D, I define my geometry as follows:

```<code><MeshGeometry3D Positions="0 0 0  1 1 0  1 0 0" />
</code>```

My camera is defined as

```<code><PerspectiveCamera FarPlaneDistance="20"
                    LookDirection="0,0,1"
                    UpDirection="0,1,0"
                    NearPlaneDistance="0"
                    Position="0,0,-10"
                    FieldOfView="45" />
</code>```

However, when I look at the resulting picture, I get this:

It would appear that the X co-ordinate is backwards, i.e., the X axis is facing left. Curiously, when I try to flip the sign, i.e., when I write

```<code><MeshGeometry3D Positions="0 0 0  -1 1 0  -1 0 0" />
</code>```

The image disappears entirely. What's going on here?

答:
I'm going to answer your second question first...3d engines like WPF usually employ backface culling, where faces that point away from the camera aren't rendered in order to improve performance. You can fix this by either changing the order of the points in your MeshGeometry3D or assigning a BackMaterial to your GeometryModel3D (as opposed to the regular Material).

With respect to your first question, it's not the X that's flipped around, it's the Z. If you look at the WPF 3D Graphics Overview on the Microsoft site you'll see that Z is negative going into the screen. You've set your camera at [0,0,-10] and set the look direction to [0,0,1], so the camera is effectively "behind" the object and looking backwards. Change these values to [0,0,10] and [0,0,-1], and add a BackMaterial like I mentioned above, and all will be good in the world again.

Title: WPF 3D x-coordinate appears backwards

Body:
Using WPF 3D, I define my geometry as follows:

<MeshGeometry3D Positions="0 0 0  1 1 0  1 0 0" />

My camera is defined as

<PerspectiveCamera FarPlaneDistance="20"
                    LookDirection="0,0,1"
                    UpDirection="0,1,0"
                    NearPlaneDistance="0"
                    Position="0,0,-10"
                    FieldOfView="45" />

However, when I look at the resulting picture, I get this:

It would appear that the X co-ordinate is backwards, i.e., the X axis is facing left. Curiously, when I try to flip the sign, i.e., when I write

<MeshGeometry3D Positions="0 0 0  -1 1 0  -1 0 0" />

The image disappears entirely. What's going on here?


问:
Create multiple background button
I'm trying to do a button that have a double background, one that contains an icon (with fixed width) and the rest is normal text.

What I got for now is:

.button {
  position: relative;
  display: inline-block;
  background-color: red;
  height: 50px;
  line-height: 50px;
  padding-left: 30px;
}

span {
  background-color: blue;
  position: absolute;
  left: 0;
  width: 30px;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" rel="stylesheet"/>

<div class="button">
  <span>x</span> Test
</div>

<div class="button">
  <span><i class="fas fa-address-card"></i></span> Test
</div></code>```

The problem of that method is that a 1px border is shown at the bottom and seems not very stable as method. How can I achieve this effect cleanly? Thanks

答:
You could use display: grid to place the items and have them vertically and horizontally centered and a linear-gradient to control the colors. It is automatically responsive and will work with all values you apply for height or width of .button.

.button {
  display: grid;
  grid-template-columns: 1fr 1fr;
  align-items: center;
  text-align: center;
  background: linear-gradient(to right, lightblue 50%, lightcoral 50%);

  /* styling */
  width: 100px;
  height: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" rel="stylesheet" />

<div class="button">
  <span>x</span>
  Test
</div>

<br>

<div class="button">
  <i class="fas fa-address-card"></i>
  Test
</div></code>```

In case you want the icon-part or the label-part to be a certain size just change grid-template-columns to something like grid-template-columns: 25% 75%; and the linear-gradient respectively (background: linear-gradient(to right, lightblue 25%, lightcoral 75%)).

Title: Create multiple background button

Body:
I'm trying to do a button that have a double background, one that contains an icon (with fixed width) and the rest is normal text.

What I got for now is:

.button {
  position: relative;
  display: inline-block;
  background-color: red;
  height: 50px;
  line-height: 50px;
  padding-left: 30px;
}

span {
  background-color: blue;
  position: absolute;
  left: 0;
  width: 30px;
  text-align: center;
}

<link href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" rel="stylesheet"/>

  x Test

   Test

The problem of that method is that a 1px border is shown at the bottom and seems not very stable as method. How can I achieve this effect cleanly? Thanks

Body:
You could use display: grid to place the items and have them vertically and horizontally centered and a linear-gradient to control the colors. It is automatically responsive and will work with all values you apply for height or width of .button.

.button {
  display: grid;
  grid-template-columns: 1fr 1fr;
  align-items: center;
  text-align: center;
  background: linear-gradient(to right, lightblue 50%, lightcoral 50%);

  /* styling */
  width: 100px;
  height: 30px;
}

<link href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" rel="stylesheet" />

<div class="button">
  <span>x</span>
  Test
</div>

<br>

<div class="button">
  <i class="fas fa-address-card"></i>
  Test
</div>

In case you want the icon-part or the label-part to be a certain size just change grid-template-columns to something like grid-template-columns: 25% 75%; and the linear-gradient respectively (background: linear-gradient(to right, lightblue 25%, lightcoral 75%)).


问:
What are the supported hashing algorithms in a Substrate runtime module?
What hashing algorithms do I have access to when building a Substrate runtime module?

Can I import other hashing algorithms to be used within a Substrate runtime module?

答:
As of writing this post, Substrate provides a HashingApi trait in the core/sr-io crate which provides the following hash functions:

export_api! {
    pub(crate) trait HashingApi {
        /// Conduct a 256-bit Keccak hash.
        fn keccak_256(data: &[u8]) -> [u8; 32] ;

        /// Conduct a 128-bit Blake2 hash.
        fn blake2_128(data: &[u8]) -> [u8; 16];

        /// Conduct a 256-bit Blake2 hash.
        fn blake2_256(data: &[u8]) -> [u8; 32];

        /// Conduct four XX hashes to give a 256-bit result.
        fn twox_256(data: &[u8]) -> [u8; 32];

        /// Conduct two XX hashes to give a 128-bit result.
        fn twox_128(data: &[u8]) -> [u8; 16];

        /// Conduct two XX hashes to give a 64-bit result.
        fn twox_64(data: &[u8]) -> [u8; 8];
    }
}
```

Because these functions are written for the Runtime, which must build to Wasm, they must compile without the use of the standard Rust library (std).

If you want to introduce new hashing algorithms or any new library to your Substrate runtime, you must make sure that it too can be built without std, but other than that, I believe the sky is the limit.

Body:
As of writing this post, Substrate provides a HashingApi trait in the core/sr-io crate which provides the following hash functions:

export_api! {
    pub(crate) trait HashingApi {
        /// Conduct a 256-bit Keccak hash.
        fn keccak_256(data: &[u8]) -> [u8; 32] ;

        /// Conduct a 128-bit Blake2 hash.
        fn blake2_128(data: &[u8]) -> [u8; 16];

        /// Conduct a 256-bit Blake2 hash.
        fn blake2_256(data: &[u8]) -> [u8; 32];

        /// Conduct four XX hashes to give a 256-bit result.
        fn twox_256(data: &[u8]) -> [u8; 32];

        /// Conduct two XX hashes to give a 128-bit result.
        fn twox_128(data: &[u8]) -> [u8; 16];

        /// Conduct two XX hashes to give a 64-bit result.
        fn twox_64(data: &[u8]) -> [u8; 8];
    }
}

Because these functions are written for the Runtime, which must build to Wasm, they must compile without the use of the standard Rust library (std).

If you want to introduce new hashing algorithms or any new library to your Substrate runtime, you must make sure that it too can be built without std, but other than that, I believe the sky is the limit.


问:
Convert XGBoost to PMML in python
I have the following dataframe

train_x:

```<code>col1 col2 col3
1      4    89
0.4    1.6  14
100    678  970
</code>```

train_y:

```<code>target
0
0
1
</code>```

I want to convert the xgboost model to pmml as below:

```<code>from sklearn2pmml import sklearn2pmml, PMMLPipeline
from sklearn_pandas import DataFrameMapper
from xgboost.sklearn import XGBClassifier
pipeline = PMMLPipeline([("mapper", DataFrameMapper([
                                    ([num_features,SimpleImputer(strategy='median')],
                                     [num_features,StandardScaler()],
                                     [cat_features,SimpleImputer(strategy='constant', fill_value='missing')],
                                     [cat_features,OneHotEncoder(sparse=False, handle_unknown='ignore')])
                                     ])),
                         ("classifier", XGBClassifier(**best_params,n_jobs=-1))
])
</code>```

and fit the pipeline

```<code>pipeline.fit(train_x, train_y)
</code>```

but i get the error below

TypeError: _build_feature() takes from 2 to 3 positional arguments but 4 were given**

答:
This TypeError is raised by the DataFrameMapper.fit method, because you've specified invalid column-to-transformer mappings.

You should be specifying a list of two-element tuples ([(), ()]), but right now you're supplying a singleton list, which contains a tuple, which contains four lists ([([], [], [], [])]).

Title: Convert XGBoost to PMML in python

Body:
I have the following dataframe

train_x:

col1 col2 col3
1      4    89
0.4    1.6  14
100    678  970

train_y:

target
0
0
1

I want to convert the xgboost model to pmml as below:

from sklearn2pmml import sklearn2pmml, PMMLPipeline
from sklearn_pandas import DataFrameMapper
from xgboost.sklearn import XGBClassifier
pipeline = PMMLPipeline([("mapper", DataFrameMapper([
                                    ([num_features,SimpleImputer(strategy='median')],
                                     [num_features,StandardScaler()],
                                     [cat_features,SimpleImputer(strategy='constant', fill_value='missing')],
                                     [cat_features,OneHotEncoder(sparse=False, handle_unknown='ignore')])
                                     ])),
                         ("classifier", XGBClassifier(**best_params,n_jobs=-1))
])

and fit the pipeline

pipeline.fit(train_x, train_y)

but i get the error below

TypeError: _build_feature() takes from 2 to 3 positional arguments but 4 were given**


问:
Typescript: Cannot find namespace
I have the following simple NodeJS code:

```<code>const express = require('express');

const server: express.Application = express();
</code>```

I'm adding Typescript to my project and am new to it so forgive me. With the above code I get the following issues/errors:

For the require:

```<code>var require: NodeRequire (id: string) => any (+1 overload)
'require' call may be converted to an import.
</code>```

For the express.Application usage:

```<code>Cannot find namespace 'express'.
</code>```

If I switch the 'require' to 'import' it fixes the namespace error but is no longer valid Node code so doesn't run (throws a new error about unexpected token for the import).

What's the correct way to write Node code like this with Typescript to avoid these errors?

My tsconfig.json looks like this:

```<code>{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve",
    "lib": ["dom", "es2017"],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext",
  },
  "exclude": ["node_modules"],
}
</code>```

答:
Maybe you have to use import instead of require:

```<code>import * as express from 'express';
</code>```

Title: Typescript: Cannot find namespace

Body:
I have the following simple NodeJS code:

const express = require('express');

const server: express.Application = express();

I'm adding Typescript to my project and am new to it so forgive me. With the above code I get the following issues/errors:

For the require:

var require: NodeRequire (id: string) => any (+1 overload)
'require' call may be converted to an import.

For the express.Application usage:

Cannot find namespace 'express'.

If I switch the 'require' to 'import' it fixes the namespace error but is no longer valid Node code so doesn't run (throws a new error about unexpected token for the import).

What's the correct way to write Node code like this with Typescript to avoid these errors?

My tsconfig.json looks like this:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve",
    "lib": ["dom", "es2017"],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "resolveJsonModule": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext",
  },
  "exclude": ["node_modules"],
}

Body:
Maybe you have to use import instead of require:

import * as express from 'express';


问:
Alexa SMAPI - updating intent returns error: "The specified skill or locale does not have a model associated."
I am using the Amazon Alexa Skill Management API (SMAPI) for the goal of cloning one of my skills, and changing key variables such as the skill name and I can do that successfully: I GET the manifest, make some changes, and CREATE a new skill using that updated manifest.

Then I wait for the skill status to finish being created, and then I am able to successfully GET my blueprint skill's interaction model, but when I UPDATE the new skill with the interaction model, I receive this error:

"{"message": "The specified skill or locale does not have a model associated."}"

I've been searching through the API for a way to "associate" a model for the new skill before updating, but I can't find anything. The API does say that using Update Interaction Model "Creates an InteractionModel for the skill." So I am expecting it to create the model if the skill does not have one associated yet.

I have contacted and not yet heard back from Amazon Support.

DETAILS

Here are the steps I am attempting which result in the above error:

I'm using my own webpage built in PHP to manage my Alexa Skills using SMAPI.

First I use Amazon Login to gain an access_token with required permissions:

```<code> alexa::ask:skills:read
 alexa::ask:skills:readwrite
 alexa::ask:models:read
 alexa::ask:models:readwrite
 alexa::ask:skills:test
</code>```

This successfully returns an access_token. I then use the access_token to get the list of skills. Then ouput those skills with a button to clone it. That will use the skill's ID as the blueprint skillId below.

Clone Skill code:

```<code>//GET THE MANIFEST OF THE BLUEPRINT SKILL
$manifestObj = getAlexaSkillManifest($access_token, $skillId);

//CHANGE THE NAME IN THE SKILL MANIFEST
$manifestObj['manifest']['publishingInformation']['locales']['en-US']['name'] = "clone test";

//CREATE NEW SKILL USING BLUEPRINT MANIFEST
$createdSkill = createAlexaSkillManifest($access_token, $vendorId, $manifestObj['manifest'], $body);
$newSkillId = $createdSkill['skillId'];

//SUCCESSFUL SO FAR

//GET BLUEPRINT SKILL'S INTERACTION MODEL
$blueprintSkillIntents = getAlexaSkillIntents($access_token, $skillId);

//CHECK AND WAIT FOR THE NEW SKILL TO BE COMPLETELY CREATED BEFORE ATTEMPTING TO UPDATE THE NEW SKILL'S INTERACTION MODEL
for ($i=0; $i <= 3; $i++) {
    $status = getAlexaSkillStatus ($access_token, $newSkillId);
    if($status['manifest']['lastUpdateRequest']['status']=="SUCCEEDED") {

        //LOGGING HERE SHOWS THIS FIRES AFTER NEW SKILL STATUS IS COMPLETE

        //UPDATE NEW SKILL INTERACTION MODEL
        $newSkillIntents = updateAlexaSkillIntents($access_token, $newSkillId, $blueprintSkillIntents);
        break;
    }
    sleep(1);
}
</code>```

Get the blueprint interaction model function (SUCCESSFUL):

```<code>function getAlexaSkillIntents ($access_token, $skillId, $stage="development", $version="~current") {

    $locale="en-US";
    $url = "https://api.amazonalexa.com/v1/skills/$skillId/stages/$stage/interactionModel/locales/$locale/versions/$version";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$access_token));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, 'CURLOPT_HTTP_VERSION_NONE');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($result, true);
    return $result;
}

//SUCCESSFULLY RETURNS THE INTERACTION MODEL OF THE BLUEPRINT SKILL
</code>```

Update the new skill Interaction Model function (ERRORS):

```<code>function updateAlexaSkillIntents ($access_token, $skillId, $intentModel, $stage="development") {

    $intentModel=json_encode($intentModel);

    $locale="en-US";
    $url = "https://api.amazonalexa.com/v1/skills/$skillId/stages/$stage/interactionModel/locales/$locale";

    $fp = fopen('php://temp/maxmemory:256000', 'w');

    if (!$fp) { die('could not open temp memory data'); }

    fwrite($fp, $intentModel);
    fseek($fp, 0);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
    curl_setopt($ch, CURLOPT_INFILESIZE, strlen($intentModel));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$access_token));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, 'CURLOPT_HTTP_VERSION_NONE');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($result, true);
    return $result;
}
</code>```

That $result returns the error from Alexa SMAPI:

"{"message": "The specified skill or locale does not have a model associated."}"

How can I resolve this error? or How should I go about using SMAPI to clone a skill?

答:
I got the same error message when using ASK CLI to update my skill model. The problem was the locale. I was using en-UK in the command line while the skill supported only en-US.

Example:

```<code>ask api get-model --debug -s "skill id ..."--stage development -l en-US > model.json
</code>```

Body:
I am using the Amazon Alexa Skill Management API (SMAPI) for the goal of cloning one of my skills, and changing key variables such as the skill name and I can do that successfully: I GET the manifest, make some changes, and CREATE a new skill using that updated manifest.

Then I wait for the skill status to finish being created, and then I am able to successfully GET my blueprint skill's interaction model, but when I UPDATE the new skill with the interaction model, I receive this error:

"{"message": "The specified skill or locale does not have a model associated."}"

I've been searching through the API for a way to "associate" a model for the new skill before updating, but I can't find anything. The API does say that using Update Interaction Model "Creates an InteractionModel for the skill." So I am expecting it to create the model if the skill does not have one associated yet.

I have contacted and not yet heard back from Amazon Support.

DETAILS

Here are the steps I am attempting which result in the above error:

I'm using my own webpage built in PHP to manage my Alexa Skills using SMAPI.

First I use Amazon Login to gain an access_token with required permissions:

 alexa::ask:skills:read
 alexa::ask:skills:readwrite
 alexa::ask:models:read
 alexa::ask:models:readwrite
 alexa::ask:skills:test

This successfully returns an access_token. I then use the access_token to get the list of skills. Then ouput those skills with a button to clone it. That will use the skill's ID as the blueprint skillId below.

Clone Skill code:

//GET THE MANIFEST OF THE BLUEPRINT SKILL
$manifestObj = getAlexaSkillManifest($access_token, $skillId);

//CHANGE THE NAME IN THE SKILL MANIFEST
$manifestObj['manifest']['publishingInformation']['locales']['en-US']['name'] = "clone test";

//CREATE NEW SKILL USING BLUEPRINT MANIFEST
$createdSkill = createAlexaSkillManifest($access_token, $vendorId, $manifestObj['manifest'], $body);
$newSkillId = $createdSkill['skillId'];

//SUCCESSFUL SO FAR

//GET BLUEPRINT SKILL'S INTERACTION MODEL
$blueprintSkillIntents = getAlexaSkillIntents($access_token, $skillId);

//CHECK AND WAIT FOR THE NEW SKILL TO BE COMPLETELY CREATED BEFORE ATTEMPTING TO UPDATE THE NEW SKILL'S INTERACTION MODEL
for ($i=0; $i <= 3; $i++) {
    $status = getAlexaSkillStatus ($access_token, $newSkillId);
    if($status['manifest']['lastUpdateRequest']['status']=="SUCCEEDED") {

        //LOGGING HERE SHOWS THIS FIRES AFTER NEW SKILL STATUS IS COMPLETE

        //UPDATE NEW SKILL INTERACTION MODEL
        $newSkillIntents = updateAlexaSkillIntents($access_token, $newSkillId, $blueprintSkillIntents);
        break;
    }
    sleep(1);
}

Get the blueprint interaction model function (SUCCESSFUL):

function getAlexaSkillIntents ($access_token, $skillId, $stage="development", $version="~current") {

    $locale="en-US";
    $url = "https://api.amazonalexa.com/v1/skills/$skillId/stages/$stage/interactionModel/locales/$locale/versions/$version";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$access_token));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, 'CURLOPT_HTTP_VERSION_NONE');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($result, true);
    return $result;
}

//SUCCESSFULLY RETURNS THE INTERACTION MODEL OF THE BLUEPRINT SKILL

Update the new skill Interaction Model function (ERRORS):

function updateAlexaSkillIntents ($access_token, $skillId, $intentModel, $stage="development") {

    $intentModel=json_encode($intentModel);

    $locale="en-US";
    $url = "https://api.amazonalexa.com/v1/skills/$skillId/stages/$stage/interactionModel/locales/$locale";

    $fp = fopen('php://temp/maxmemory:256000', 'w');

    if (!$fp) { die('could not open temp memory data'); }

    fwrite($fp, $intentModel);
    fseek($fp, 0);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
    curl_setopt($ch, CURLOPT_INFILESIZE, strlen($intentModel));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$access_token));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, 'CURLOPT_HTTP_VERSION_NONE');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    $result = json_decode($result, true);
    return $result;
}

That $result returns the error from Alexa SMAPI:

"{"message": "The specified skill or locale does not have a model associated."}"

How can I resolve this error? or How should I go about using SMAPI to clone a skill?

Body:
I got the same error message when using ASK CLI to update my skill model. The problem was the locale. I was using en-UK in the command line while the skill supported only en-US.

Example:

ask api get-model --debug -s "skill id ..."--stage development -l en-US > model.json


问:
What event should i use to check when an input box loses focus in jquery
I have a function that is executed when a textbox gains focus and another function when it loses focus. problem is i dont know where to attach the function for the lost focus event. For the focus i am using</p>

```<code> $(" :input[class='Txtbox']").focus(function(){
        $(this).val("");

    });
</code>```

答:
Use the `blur' event handler. Then in the callback do anything you want (i'm sure you that already):</p>

```<code>$(" :input[class='Txtbox']").blur(function(){
    // Do Something...
});
</code>```

Body:
I have a function that is executed when a textbox gains focus and another function when it loses focus. problem is i dont know where to attach the function for the lost focus event. For the focus i am using

 $(" :input[class='Txtbox']").focus(function(){
        $(this).val("");

    });

Body:
Use the `blur' event handler. Then in the callback do anything you want (i'm sure you that already):

$(" :input[class='Txtbox']").blur(function(){
    // Do Something...
});


问:
MySQL 8.0 ERROR 3118 (HY000): Access denied for user 'root'@'localhost'. Account is locked
I tried to change my PHP login to MySQL 8.0 from using caching_sha2_password to mysql_native_password as below. Now I can't login at all to MySQL. I have restarted the mysqld to no avail.

Any ideas to remedy?

I followed this article php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

```<code>mysql> ALTER USER 'elstatuser'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysecretpassword';
ERROR 3009 (HY000): Column count of mysql.user is wrong. Expected 50, found 49. Created with MySQL 80012, now running 80013. Please use mysql_upgrade to fix this error.

[root@han ~]# mysql_upgrade --force -uroot -p
Enter password:
Checking server version.
Running queries to upgrade MySQL server.
Upgrading system table data.
Checking system database.
mysql.columns_priv                                 OK

mysql.component                                    OK
mysql.db                                           OK
mysql.default_roles                                OK
mysql.engine_cost                                  OK
mysql.func                                         OK
mysql.general_log                                  OK
mysql.global_grants                                OK
mysql.gtid_executed                                OK
mysql.help_category                                OK
mysql.help_keyword                                 OK
mysql.help_relation                                OK
mysql.help_topic                                   OK
mysql.innodb_index_stats                           OK
mysql.innodb_table_stats                           OK
mysql.password_history                             OK
mysql.plugin                                       OK
mysql.procs_priv                                   OK
mysql.proxies_priv                                 OK
mysql.role_edges                                   OK
mysql.server_cost                                  OK
mysql.servers                                      OK
mysql.slave_master_info                            OK
mysql.slave_relay_log_info                         OK
mysql.slave_worker_info                            OK
mysql.slow_log                                     OK
mysql.tables_priv                                  OK
mysql.time_zone                                    OK
mysql.time_zone_leap_second                        OK
mysql.time_zone_name                               OK
mysql.time_zone_transition                         OK
mysql.time_zone_transition_type                    OK
mysql.user                                         OK
The sys schema is already up to date (version 2.0.0).
Checking databases.
elstat.account                                     OK
[...]
wp.wp_users                                        OK
Upgrade process completed successfully.
Checking if update is needed.
[root@han ~]# logout
[thommym@han ~]$ mysql -u root -p
Enter password:
ERROR 3118 (HY000): Access denied for user 'root'@'localhost'. Account is locked.
[thommym@han ~]$
</code>```

答:
I had something similar happen in Windows when changing the auth plugin.

The default auth plugin for MySQL 8+ is caching_sha2_password; I wanted to change it to a simple mysql_native_password for simplicity's sake, as I'm just using the DBMS locally and didn't want to setup or need the additional protections beyond what our enterprise firewall already provides.

I believe I had to reset the root password, but it only worked once I'd edited the my.ini [client-side] config file (my.cnf on Unix-based machines) to adjust the password policy requirements:

```<code>mysql> SHOW VARIABLES LIKE 'validate_password%';
+--------------------------------------+--------+
| Variable_name                        | Value  |
+--------------------------------------+--------+
| validate_password_dictionary_file    |        |
| validate_password_length             | 8      |
| validate_password_mixed_case_count   | 1      |
| validate_password_number_count       | 1      |
| validate_password_policy             | MEDIUM |
| validate_password_special_char_count | 1      |
+--------------------------------------+--------+
6 rows in set (0.01 sec)
</code>```

Make changes as necessary to the above variables (for my purposes, simply setting validate_password_policy=LOW did the trick). Restart the MySQL service/daemon so the changes take effect, and then try using mysql_admin to reset the root password and restore the account.

Body:
I tried to change my PHP login to MySQL 8.0 from using caching_sha2_password to mysql_native_password as below. Now I can't login at all to MySQL. I have restarted the mysqld to no avail.

Any ideas to remedy?

I followed this article php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

mysql> ALTER USER 'elstatuser'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysecretpassword';
ERROR 3009 (HY000): Column count of mysql.user is wrong. Expected 50, found 49. Created with MySQL 80012, now running 80013. Please use mysql_upgrade to fix this error.

[root@han ~]# mysql_upgrade --force -uroot -p
Enter password:
Checking server version.
Running queries to upgrade MySQL server.
Upgrading system table data.
Checking system database.
mysql.columns_priv                                 OK

mysql.component                                    OK
mysql.db                                           OK
mysql.default_roles                                OK
mysql.engine_cost                                  OK
mysql.func                                         OK
mysql.general_log                                  OK
mysql.global_grants                                OK
mysql.gtid_executed                                OK
mysql.help_category                                OK
mysql.help_keyword                                 OK
mysql.help_relation                                OK
mysql.help_topic                                   OK
mysql.innodb_index_stats                           OK
mysql.innodb_table_stats                           OK
mysql.password_history                             OK
mysql.plugin                                       OK
mysql.procs_priv                                   OK
mysql.proxies_priv                                 OK
mysql.role_edges                                   OK
mysql.server_cost                                  OK
mysql.servers                                      OK
mysql.slave_master_info                            OK
mysql.slave_relay_log_info                         OK
mysql.slave_worker_info                            OK
mysql.slow_log                                     OK
mysql.tables_priv                                  OK
mysql.time_zone                                    OK
mysql.time_zone_leap_second                        OK
mysql.time_zone_name                               OK
mysql.time_zone_transition                         OK
mysql.time_zone_transition_type                    OK
mysql.user                                         OK
The sys schema is already up to date (version 2.0.0).
Checking databases.
elstat.account                                     OK
[...]
wp.wp_users                                        OK
Upgrade process completed successfully.
Checking if update is needed.
[root@han ~]# logout
[thommym@han ~]$ mysql -u root -p
Enter password:
ERROR 3118 (HY000): Access denied for user 'root'@'localhost'. Account is locked.
[thommym@han ~]$

Body:
I had something similar happen in Windows when changing the auth plugin.

The default auth plugin for MySQL 8+ is caching_sha2_password; I wanted to change it to a simple mysql_native_password for simplicity's sake, as I'm just using the DBMS locally and didn't want to setup or need the additional protections beyond what our enterprise firewall already provides.

I believe I had to reset the root password, but it only worked once I'd edited the my.ini [client-side] config file (my.cnf on Unix-based machines) to adjust the password policy requirements:

mysql> SHOW VARIABLES LIKE 'validate_password%';
+--------------------------------------+--------+
| Variable_name                        | Value  |
+--------------------------------------+--------+
| validate_password_dictionary_file    |        |
| validate_password_length             | 8      |
| validate_password_mixed_case_count   | 1      |
| validate_password_number_count       | 1      |
| validate_password_policy             | MEDIUM |
| validate_password_special_char_count | 1      |
+--------------------------------------+--------+
6 rows in set (0.01 sec)

Make changes as necessary to the above variables (for my purposes, simply setting validate_password_policy=LOW did the trick). Restart the MySQL service/daemon so the changes take effect, and then try using mysql_admin to reset the root password and restore the account.


问:
Bootstrap Datepicker strange sizing
I'm using the latest (1.4) version of the Bootstrap Datepicker from Eternicode on my ASP.Net MVC website. The datepicker works fine but for some reason when I click on the month/year "zoom-out" button, the content is squashed into half the horizontal width of the dropdown. I haven't modified the bootstrap css or js in any way. I've tried using the 1.3 version of the css/js with the same results...

The code I'm using works fine on this jsfiddle but not in my local environment.

HTML

```<code><input id="datepicker" type="text" type="text" class="form-control datepicker input-sm" />
</code>```

JS

```<code>$('#datepicker').datepicker({
    autoclose: true,
    format: 'dd-mm-yyyy',
    daysOfWeekDisabled: '0,6',
    todayHighlight: true,
    orientation: 'auto'
});
</code>```

The offending element appears to be
 that spans only half of the dropdown, whereas the parent datepicker-months div tag spans the entire width of the dropdown. For datepicker-days, I can't see any difference in code but it works fine. datepicker-years suffers the same problem as datepicker-months

答:
I also had the exact same issue. But eventually what came out was I had a class like below in my stylesheet-

```<code>table,td{  ../ some styles /..}
</code>```

Remove this table,td{ ..} class that is overlapping with your datepicker classes.

Title: Bootstrap Datepicker strange sizing

Body:
I'm using the latest (1.4) version of the Bootstrap Datepicker from Eternicode on my ASP.Net MVC website. The datepicker works fine but for some reason when I click on the month/year "zoom-out" button, the content is squashed into half the horizontal width of the dropdown. I haven't modified the bootstrap css or js in any way. I've tried using the 1.3 version of the css/js with the same results...

The code I'm using works fine on this jsfiddle but not in my local environment.

HTML

<input id="datepicker" type="text" type="text" class="form-control datepicker input-sm" />

JS

$('#datepicker').datepicker({
    autoclose: true,
    format: 'dd-mm-yyyy',
    daysOfWeekDisabled: '0,6',
    todayHighlight: true,
    orientation: 'auto'
});

The offending element appears to be
 that spans only half of the dropdown, whereas the parent datepicker-months div tag spans the entire width of the dropdown. For datepicker-days, I can't see any difference in code but it works fine. datepicker-years suffers the same problem as datepicker-months

Body:
I also had the exact same issue. But eventually what came out was I had a class like below in my stylesheet-

table,td{  ../ some styles /..}

Remove this table,td{ ..} class that is overlapping with your datepicker classes.


问:
Iterating through a tuple of tuples
I have a tuple of tuples and I want to get the second item of its tuple and I am pretty stack on it.Example of what I want:

```<code>t=((1,'a'),(2,'b'),(3,'c'),(4,'d'),(5,'e'),)
</code>```

and I want to get:

```<code>list=['a','b','c','d','e']
</code>```

答:
List comprehension:</p>

```<code>my_list = [entry[1] for entry in t]
</code>```

Title: Iterating through a tuple of tuples

Body:
I have a tuple of tuples and I want to get the second item of its tuple and I am pretty stack on it.Example of what I want:

t=((1,'a'),(2,'b'),(3,'c'),(4,'d'),(5,'e'),)

and I want to get:

list=['a','b','c','d','e']

Body:
List comprehension:

my_list = [entry[1] for entry in t]


问:
How to collapse all divs with change of a tab in jQuery Tabs UI?
I'm using several WordPress loops and jQuery UI Tabs that result in the Main tabs and entry-content div markup below. The WordPress loops generate the "entry-post" markup in each tab div, but I'm not showing the php, as the resulting html markup in each tab div is the important part.

I'm also using a bit of jQuery to independently expand/collapse each entry-content div:

```<code>$(".entry-content").hide();
$(".entry-title").click(function() {
$(this).parent().children(".entry-content").slideToggle(500); });
</code>```

What I've found is that each of the entry-content divs keeps their expanded state when switching tabs, i.e. if some of the entry-content divs are expanded in tabone and I switch to tabtwo and then back to tabone, they're still expanded in tabone.

What I need to do is collapse all the entry-content divs in a tab when a tab is changed. Below is the tab init and also the fx to change the tabs.

What do I need to add to this function to collapse all the entry-content divs when a tab is changed?

```<code>$(document).ready(function(){
var $tabs= $("#tabs").tabs();
});
$(function() {
$('#tabs').tabs({
fx: { opacity:'toggle' }
});
});
</code>```

Main tabs and entry-content div markup:

```<code><div id="tabs">
    <ul>
    <li><a href="#tabone">tabone</a></li>
    <li><a href="#tabtwo">tabtwo</a></li>
    <li><a href="#tabthree">tabthree</a></li>
    </ul>

    <div id="tabone">

<div class="entry-post">
<h1 class="entry-title">Title</h1>
<div class="entry-content">Lorem ipsum...
</div></div>

<div class="entry-post">
<h1 class="entry-title">Title</h1>
<div class="entry-content">Lorem ipsum...
</div></div>

<div class="entry-post">
<h1 class="entry-title">Title</h1>
<div class="entry-content">Lorem ipsum...
</div></div>
    </div>

    <div id="tabtwo">

<div class="entry-post">
<h1 class="entry-title">Title</h1>
<div class="entry-content">Lorem ipsum...
</div></div>

<div class="entry-post">
<h1 class="entry-title">Title</h1>
<div class="entry-content">Lorem ipsum...
</div></div>

<div class="entry-post">
<h1 class="entry-title">Title</h1>
<div class="entry-content">Lorem ipsum...
</div></div>
    </div>

    <div id="tabthree">

....

</div></div>
</code>```

答:
I'm not sure i understand you're question completely. But if you wan't to check whether the tab is triggered or not, try use this:

```<code>$( ".selector" ).tabs({
  show: function(event, ui) { ... }
});
</code>```

Simplified how you could collapse all divs with class "entry-post", whenever the tab is showed:

```<code>$(document).ready(function(){
  var $tabs = $("#tabs").tabs({
    show: function(){
      $('.entry-post').hide();
    }
  });
});
</code>```

Body:
I'm using several WordPress loops and jQuery UI Tabs that result in the Main tabs and entry-content div markup below. The WordPress loops generate the "entry-post" markup in each tab div, but I'm not showing the php, as the resulting html markup in each tab div is the important part.

I'm also using a bit of jQuery to independently expand/collapse each entry-content div:

$(".entry-content").hide();
$(".entry-title").click(function() {
$(this).parent().children(".entry-content").slideToggle(500); });

What I've found is that each of the entry-content divs keeps their expanded state when switching tabs, i.e. if some of the entry-content divs are expanded in tabone and I switch to tabtwo and then back to tabone, they're still expanded in tabone.

What I need to do is collapse all the entry-content divs in a tab when a tab is changed. Below is the tab init and also the fx to change the tabs.

What do I need to add to this function to collapse all the entry-content divs when a tab is changed?

$(document).ready(function(){
var $tabs= $("#tabs").tabs();
});
$(function() {
$('#tabs').tabs({
fx: { opacity:'toggle' }
});
});

Main tabs and entry-content div markup:

tabone

tabtwo

tabthree

Title

Lorem ipsum...

Title

Lorem ipsum...

Title

Lorem ipsum...

Title

Lorem ipsum...

Title

Lorem ipsum...

Title

Lorem ipsum...

....

Body:
I'm not sure i understand you're question completely. But if you wan't to check whether the tab is triggered or not, try use this:

$( ".selector" ).tabs({
  show: function(event, ui) { ... }
});

Simplified how you could collapse all divs with class "entry-post", whenever the tab is showed:

$(document).ready(function(){
  var $tabs = $("#tabs").tabs({
    show: function(){
      $('.entry-post').hide();
    }
  });
});


问:
Convert array of Strings to Array list
I have a String array with name and id, I need to convert that String array to List of objects.

This is my code:

```<code>private List<ObjectAttribute> getDtls(String newVal) {
    ObjectAttribute object = new ObjectAttribute();
    List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
    String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
    for (int i = 0; i <= newImageVal.length - 1; i++) {
        object.setImageName(newImageVal[i]);
        object.setImageId(newImageVal[++i]);
        objLst.add(object);
    }
    return objLst;
}
</code>```

but there is a problem that it always returns only the last value in objList. Can anyone correct this code.

答:
or you may do something like this using the streams way:

```<code>AtomicInteger ai = new AtomicInteger();
List<ObjectAttribute> objLst = Arrays.stream(newImageVal)
.map(img-> {
   ObjectAttribute object = new ObjectAttribute();
   object.setImageName(img);
   object.setImageId(ai.getAndIncrement());
   return obj;
 }).collect(Collectors.toList())
</code>```

Title: Convert array of Strings to Array list

Body:
I have a String array with name and id, I need to convert that String array to List of objects.

This is my code:

private List<ObjectAttribute> getDtls(String newVal) {
    ObjectAttribute object = new ObjectAttribute();
    List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
    String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
    for (int i = 0; i <= newImageVal.length - 1; i++) {
        object.setImageName(newImageVal[i]);
        object.setImageId(newImageVal[++i]);
        objLst.add(object);
    }
    return objLst;
}

but there is a problem that it always returns only the last value in objList. Can anyone correct this code.

Body:
or you may do something like this using the streams way:

AtomicInteger ai = new AtomicInteger();
List<ObjectAttribute> objLst = Arrays.stream(newImageVal)
.map(img-> {
   ObjectAttribute object = new ObjectAttribute();
   object.setImageName(img);
   object.setImageId(ai.getAndIncrement());
   return obj;
 }).collect(Collectors.toList())


答:
Try this using a list comprehension:

```<code>print([x for _, x in t])
</code>```

Another (not really recommended solution):

```<code>print(list(map(lambda x: x[1], t)))
</code>```

Both Output:

```<code>['a', 'b', 'c', 'd', 'e']
</code>```

Title: Iterating through a tuple of tuples

Body:
Try this using a list comprehension:

print([x for _, x in t])

Another (not really recommended solution):

print(list(map(lambda x: x[1], t)))

Both Output:

['a', 'b', 'c', 'd', 'e']