问:
Successful deploy on Dokku but seeing old site
I have a Dokku server running a Node.js site at Digital Ocean. I've been updating it with new version, but suddenly, I started getting an issue with deployment. I add new files to the local repository, do a git push dokku. The deployment process shows all the deploy output and it completes successfully.

However, after I hard reload the site, I see the old version. A reboot of the server didn't help either. Tried recommitting an empty commit and redeploying. Nothing.

```<code>To 104.104.104.104:mm
   93a8f81..3d4cd32  master -> master
Marcs-MBP:mm2 marc$ git commit --allow-empty -m "Trigger notification"
[master 06094b4] Trigger notification
Marcs-MBP:mm2 marcschipperheijn$ git push dokku
Counting objects: 1, done.
Writing objects: 100% (1/1), 193 bytes | 0 bytes/s, done.
Total 1 (delta 0), reused 0 (delta 0)
-----> Cleaning up...
-----> Building mm from herokuish...
-----> Adding BUILD_ENV to build environment...
-----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       NPM_CONFIG_PRODUCTION=false
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=true

-----> Installing binaries
       engines.node (package.json):  ~6.10.3
       engines.npm (package.json):   unspecified (use default)

       Resolving node version ~6.10.3 via semver.io...
       Downloading and installing node 6.10.3...
       Using default npm version: 3.10.10
       Resolving yarn version (latest) via semver.io...
       Downloading and installing yarn (0.24.5)...
       Installed yarn 0.24.5

-----> Restoring cache
       Loading 2 from cacheDirectories (default):
       - node_modules
       - bower_components (not cached - skipping)

-----> Building dependencies
       Installing node modules (yarn.lock)
       yarn install v0.24.5
       $ node internal/scripts/preinstall
       [1/4] Resolving packages...
       [2/4] Fetching packages...
       warning fsevents@1.0.15: The platform "linux" is incompatible with this module.
       info "fsevents@1.0.15" is an optional dependency and failed compatibility check. Excluding it from installation.
       [3/4] Linking dependencies...
       warning "react-styled-flexboxgrid@1.1.2" has incorrect peer dependency "styled-components@^1.3.1 || ^2.0.0-17".
       [4/4] Building fresh packages...
       $ npm run build

       > react-universally@13.0.0 build /tmp/build
       > babel-node internal/scripts/build --optimize

==> Registering environment variables from: /tmp/build/.env
==> Creating an optimised bundle configuration for the "client"
       loader option has been deprecated - replace with "use"
==> Creating an optimised bundle configuration for the "server"
       Hash: 3da1352e5e8f4a5467f3
       Version: webpack 2.6.1
       Time: 156672ms
       Asset     Size  Chunks             Chunk Names
       0-bbe31ddeb056e33b1f34.js   224 kB       0  [emitted]
       1-9a824b6c0e696a34878b.js  30.9 kB       1  [emitted]
       2-52dc2b15e4173a333218.js  10.2 kB       2  [emitted]
       index.js   700 kB       3  [emitted]  index
       0-bbe31ddeb056e33b1f34.js.map   216 kB       0  [emitted]
       1-9a824b6c0e696a34878b.js.map  26.8 kB       1  [emitted]
       2-52dc2b15e4173a333218.js.map  6.62 kB       2  [emitted]
       index.js.map   848 kB       3  [emitted]  index
       chunk    {0} 0-bbe31ddeb056e33b1f34.js, 0-bbe31ddeb056e33b1f34.js.map 165 kB {3} [rendered]
       [214] ./shared/SyncApp.js 2.73 kB {0} [built]
       [216] ./shared/styles/CommonStyles.js 6.44 kB {0} [built]
       [227] ./shared/resources/i8n/mm.en.js 6.06 kB {0} [optional] [built]
       [228] ./shared/resources/i8n/mm.pt.js 6.86 kB {0} [optional] [built]
       [230] ./shared/resources/react-intl/pt.js 3.55 kB {0} [optional] [built]
       [232] ./shared/utils/i8n/intl.js 405 bytes {0} [built]
       [236] ./shared/resources/i8n ^./mm..*$ 214 bytes {0} [built]
       [266] ./shared/screens/Home.js 5.32 kB {0} [built]
       [267] ./shared/screens/home/Bios.js 5.11 kB {0} [built]
       [276] ./shared/screens/index.js 244 bytes {0} [built]
       [277] ./shared/store/configureStore.js 688 bytes {0} [built]
       [278] ./shared/store/reducers.js 363 bytes {0} [built]
       [279] ./shared/styles/globalCss.js 903 bytes {0} [built]
       [280] ./shared/styles/icons.js 1.23 kB {0} [built]
       [290] ./shared/resources/react-intl ^./.*$ 202 bytes {0} [built]
       + 48 hidden modules
       chunk    {1} 1-9a824b6c0e696a34878b.js, 1-9a824b6c0e696a34878b.js.map 19.5 kB {0} [rendered]
       [223] ./shared/components/navigation/Button.js 2.32 kB {1} [built]
       [231] ./shared/utils.js 744 bytes {1} [built]
       [261] ./shared/modules/contact/ContactActionTypes.js 139 bytes {1} [built]
       [262] ./shared/modules/contact/actions/contactActions.js 1.64 kB {1} [built]
       [263] ./shared/modules/contact/forms/ContactForm.js 5.42 kB {1} [built]
       [264] ./shared/modules/forms/functions/formFunctions.js 2.54 kB {1} [built]
       [272] ./shared/screens/home/contact/Contact.js 6.61 kB {1} [built]
       [281] ./shared/utils/tapEvents.js 118 bytes {1} [built]
       chunk    {2} 2-52dc2b15e4173a333218.js, 2-52dc2b15e4173a333218.js.map 5.88 kB {0} [rendered]
       [274] ./shared/screens/home/hiring/Hiring.js 5.88 kB {2} [built]
       chunk    {3} index.js, index.js.map (index) 658 kB [entry] [rendered]
       [5] ./config/index.js 3.95 kB {3} [built]
       [14] external "app-root-dir" 42 bytes {3} [not cacheable]
       [15] external "path" 42 bytes {3} [not cacheable]
       [81] external "express" 42 bytes {3} [not cacheable]
       [90] ./server/index.js 2.54 kB {3} [built]
       [102] ./server/middleware/chatHandler.js 1.75 kB {3} [built]
       [103] ./server/middleware/clientBundle.js 346 bytes {3} [built]
       [104] ./server/middleware/errorHandlers.js 852 bytes {3} [built]
       [105] ./server/middleware/mailHandler.js 2.57 kB {3} [built]
       [106] ./server/middleware/offlinePage.js 1.22 kB {3} [built]
       [111] ./server/middleware/serviceWorker.js 414 bytes {3} [built]
       [192] external "body-parser" 42 bytes {3} [not cacheable]
       [194] external "compression" 42 bytes {3} [not cacheable]
       [204] external "http" 42 bytes {3} [not cacheable]
       [213] multi ./server/index.js 28 bytes {3} [built]
       + 218 hidden modules

       WARNING in ./shared/modules/chatbot/functions/botScript.js
       23:20-30 "export 'saveWeight' was not found in './chatAPI'

       WARNING in ./shared/modules/chatbot/functions/botScript.js
       52:20-30 "export 'saveWeight' was not found in './chatAPI'
       Hash: 4d672dace247f3f9adaf
       Version: webpack 2.6.1
       Time: 231240ms
       Asset     Size  Chunks             Chunk Names
       af41be6924f9c8211166d3617d12bef2.ttf  2.83 kB          [emitted]
       2b66f705e2dd0efa798a98fe687ed86d.eot  44.4 kB          [emitted]
       69f1400361a215519d385199118a34aa.ttf  44.3 kB          [emitted]
       c556ea6e1425e6e8871741ceba9c8e53.woff  19.1 kB          [emitted]
       8197018935f2e90f1531ef6c7276da46.svg  56.4 kB          [emitted]
       59b29634fc30144bbf16015659a3ae82.ttf  24.8 kB          [emitted]
       c2c196608bf159e903b4673296c661da.woff  11.5 kB          [emitted]
       27674ea7e09f7237517b005e7ea80d22.eot  33.8 kB          [emitted]
       4829f08385300b6c1f5dca7cd92ab89b.svg    98 kB          [emitted]
       1d6e07ebbc5886e714ee7de3b3b8164f.ttf  33.6 kB          [emitted]
       cd64e229e2bdc704d4ccf4e044d613ff.woff  22.2 kB          [emitted]
       16579436549dd1128209eb991d4d2be2.eot  2.98 kB          [emitted]
       16e1c72ddad39b87b5783655262524ec.svg  4.39 kB          [emitted]
       a28f51b9d3f0a244cb74fb5fc563d5cd.svg  51.2 kB          [emitted]
       7b88ba1717fdea9a44acf5a799c1da15.woff  2.19 kB          [emitted]
       806dfbd790b070ccfe05978cb27dd5bf.eot    25 kB          [emitted]
       0-6ef6da38246c71470f5d.js   238 kB       0  [emitted]
       1-2a39e135a3423ced8910.js   240 kB       1  [emitted]
       2-44370d88514c6cec2369.js  5.24 kB       2  [emitted]
       index-57c53cba4d0af05e5966.js   131 kB       3  [emitted]  index
       0-6ef6da38246c71470f5d.js.map  1.58 MB       0  [emitted]
       1-2a39e135a3423ced8910.js.map  1.86 MB       1  [emitted]
       2-44370d88514c6cec2369.js.map  19.2 kB       2  [emitted]
       index-57c53cba4d0af05e5966.js.map   927 kB       3  [emitted]  index
       offline.html  1.77 kB          [emitted]
       sw.js  16.8 kB          [emitted]
       chunk    {0} 0-6ef6da38246c71470f5d.js, 0-6ef6da38246c71470f5d.js.map 623 kB {3} [rendered]
       [74] ./shared/SyncApp.js 3.77 kB {0} [built]
       [77] ./shared/styles/CommonStyles.js 8.04 kB {0} [built]
       [186] ./~/react-intl-redux/lib/index.js 1.85 kB {0} [built]
       [219] ./shared/utils/i8n/intl.js 750 bytes {0} [built]
       [266] ./~/react-ga/src/utils/trim.js 203 bytes {0} [built]
       [267] ./~/react-intl-redux/lib/components/IntlProvider.js 862 bytes {0} [built]
       [288] ./shared/resources/i8n ^./mm..*$ 214 bytes {0} [built]
       [388] ./shared/screens/index.js 672 bytes {0} [built]
       [389] ./shared/store/configureStore.js 1.02 kB {0} [built]
       [391] ./shared/styles/globalCss.js 938 bytes {0} [built]
       [392] ./shared/styles/icons.js 1.26 kB {0} [built]
       [631] ./~/react-ga/src/index.js 12.9 kB {0} [built]
       [633] ./~/react-ga/src/utils/format.js 421 bytes {0} [built]
       [635] ./~/react-ga/src/utils/removeLeadingSlash.js 149 bytes {0} [built]
       [650] ./~/react-redux/lib/components/Provider.js 3.44 kB {0} [built]
       + 263 hidden modules
       chunk    {1} 1-2a39e135a3423ced8910.js, 1-2a39e135a3423ced8910.js.map 642 kB {0} [rendered]
       [85] ./~/redux-form/es/structure/plain/index.js 587 bytes {1} [built]
       [119] ./~/babel-runtime/helpers/createClass.js 904 bytes {1} [built]
       [120] ./~/babel-runtime/helpers/inherits.js 1.11 kB {1} [built]
       [121] ./~/babel-runtime/helpers/possibleConstructorReturn.js 542 bytes {1} [built]
       [189] ./~/redux-form/es/index.js 3.17 kB {1} [built]
       [210] ./shared/components/navigation/Button.js 3.13 kB {1} [built]
       [259] ./~/material-ui/styles/getMuiTheme.js 13 kB {1} [built]
       [260] ./~/material-ui/utils/colorManipulator.js 7.62 kB {1} [built]
       [373] ./shared/modules/contact/ContactActionTypes.js 250 bytes {1} [built]
       [374] ./shared/modules/contact/actions/contactActions.js 3.15 kB {1} [built]
       [375] ./shared/modules/contact/forms/ContactForm.js 6.44 kB {1} [built]
       [376] ./shared/modules/forms/functions/formFunctions.js 4.72 kB {1} [built]
       [384] ./shared/screens/home/contact/Contact.js 10.6 kB {1} [built]
       [393] ./shared/utils/tapEvents.js 307 bytes {1} [built]
       [609] ./~/material-ui/styles/MuiThemeProvider.js 2.15 kB {1} [built]
       + 376 hidden modules
       chunk    {2} 2-44370d88514c6cec2369.js, 2-44370d88514c6cec2369.js.map 8.89 kB {0} [rendered]
       [386] ./shared/screens/home/hiring/Hiring.js 8.89 kB {2} [built]
       chunk    {3} index-57c53cba4d0af05e5966.js, index-57c53cba4d0af05e5966.js.map (index) 349 kB [entry] [rendered]
       [0] external {"root":"React","commonjs2":"react","commonjs":"react","amd":"react"} 42 bytes {3} [not cacheable]
       [7] (webpack)/buildin/global.js 509 bytes {3} [built]
       [8] ./~/react-async-component/commonjs/index.js 851 bytes {3} [built]
       [16] ./client/index.js 3.94 kB {3} [built]
       [17] ./~/regenerator-runtime/runtime.js 24.4 kB {3} [built]
       [20] ./shared/components/widgets/Loading.js 1.99 kB {3} [built]
       [22] external {"root":"ReactDOM","commonjs2":"react-dom","commonjs":"react-dom","amd":"react-dom"} 42 bytes {3} [not cacheable]
       [23] ./shared/Helmet.js 5.88 kB {3} [built]
       [31] ./client/components/ReactHotLoader.js 688 bytes {3} [built]
       [32] ./client/polyfills/index.js 769 bytes {3} [built]
       [33] ./client/registerServiceWorker.js 1.66 kB {3} [built]
       [34] ./shared/App.js 2.42 kB {3} [built]
       [42] ./.modernizrrc 1.45 kB {3} [built]
       [45] ./~/react-async-bootstrapper/commonjs/index.js 640 bytes {3} [built]
       [73] multi regenerator-runtime/runtime ./client/index.js 40 bytes {3} [built]
       + 59 hidden modules

       WARNING in duplicate-package-checker:
       <prop-types>
       15.5.7 ./~/prop-types
       15.5.10 ./~/react-redux/~/prop-types

       Child __offline_serviceworker:
       Asset     Size  Chunks  Chunk Names
       __offline_serviceworker  7.38 kB       0  __offline_serviceworker
       chunk    {0} __offline_serviceworker (__offline_serviceworker) 17.5 kB [entry] [rendered]
       [0] ./~/offline-plugin/empty-entry.js 0 bytes {0} [built]
       [1] ./~/offline-plugin/lib/misc/sw-loader.js?json=%7B%22data_var_name%22%3A%22__wpo%22%2C%22loaders%22%3A%5B%5D%2C%22cacheMaps%22%3A%5B%5D%7D!./~/offline-plugin/empty-entry.js 17.5 kB {0} [built]
       Child html-webpack-plugin for "offline.html":
       Asset    Size  Chunks  Chunk Names
       offline.html  657 kB       0
       chunk    {0} offline.html 653 kB [entry] [rendered]
       [1] ./~/fbjs/lib/warning.js 2.1 kB {0} [built]
       [3] ./~/object-assign/index.js 2.11 kB {0} [built]
       [12] ./~/react/lib/React.js 3.32 kB {0} [built]
       [43] ./~/react/lib/ReactComponent.js 4.61 kB {0} [built]
       [45] ./~/react/react.js 56 bytes {0} [built]
       [74] ./shared/components/HTML/index.js 2.05 kB {0} [built]
       [75] ./~/react-dom/server.js 65 bytes {0} [built]
       [76] ./~/babel-loader/lib!./internal/webpack/withServiceWorker/offlinePageTemplate.js 6.51 kB {0} [built]
       [92] ./~/prop-types/index.js 1.08 kB {0} [built]
       [114] ./~/react-dom/lib/ReactDOMServer.js 735 bytes {0} [built]
       [118] ./~/react-dom/lib/ReactDefaultInjection.js 3.5 kB {0} [built]
       [158] ./~/react/lib/ReactChildren.js 6.19 kB {0} [built]
       [159] ./~/react/lib/ReactClass.js 26.9 kB {0} [built]
       [160] ./~/react/lib/ReactDOMFactories.js 5.53 kB {0} [built]
       [167] ./~/react/lib/onlyChild.js 1.34 kB {0} [built]
       + 154 hidden modules
       Done in 355.57s.

-----> Caching build
       Clearing previous node cache
       Saving 2 cacheDirectories (default):
       - node_modules
       - bower_components (nothing to cache)

-----> Build succeeded!
-----> Discovering process types
       Procfile declares types -> web
-----> Releasing mm (dokku/mm:latest)...
-----> Deploying mm (dokku/mm:latest)...
-----> Attempting to run scripts.dokku.predeploy from app.json (if defined)
-----> App Procfile file found (/home/dokku/mm/DOKKU_PROCFILE)
-----> DOKKU_SCALE file found (/home/dokku/mm/DOKKU_SCALE)
=====> web=1
-----> Attempting pre-flight checks
       For more efficient zero downtime deployments, create a file CHECKS.
       See http://dokku.viewdocs.io/dokku/deployment/zero-downtime-deploys/ for examples
       CHECKS file not found in container: Running simple container check...
-----> Waiting for 10 seconds ...
-----> Default container check successful!
-----> Running post-deploy
=====> renaming container (1fd3a69773f6) hungry_hopper to mm.web.1
-----> Configuring *.mysite.com.br...(using built-in template)
-----> Configuring mysite.com.br...(using built-in template)
-----> Creating http nginx.conf
-----> Running nginx-pre-reload
       Reloading nginx
-----> Setting config vars
       DOKKU_APP_RESTORE: 1
-----> Attempting to run scripts.dokku.postdeploy from app.json (if defined)
-----> Shutting down old containers in 60 seconds
=====> a5781b05b65c4e33fdcacdcc09b9bf76aeec0bd1c0301c17ea7f864723b5ac74
=====> Application deployed:
       http://*.mysite.com.br
       http://mysite.com.br

To 104.104.104.104:mm
   3d4cd32..06094b4  master -> master
</code>```

Any suggestions?

答: This turned out to be a Cloudflare caching issue. I had to manually purge the cache to get the new version to show. Who knew that Cloudflare would ignore a hard reload?</p>

Body:
I have a Dokku server running a Node.js site at Digital Ocean. I've been updating it with new version, but suddenly, I started getting an issue with deployment. I add new files to the local repository, do a git push dokku. The deployment process shows all the deploy output and it completes successfully.

However, after I hard reload the site, I see the old version. A reboot of the server didn't help either. Tried recommitting an empty commit and redeploying. Nothing.

To 104.104.104.104:mm
   93a8f81..3d4cd32  master -> master
Marcs-MBP:mm2 marc$ git commit --allow-empty -m "Trigger notification"
[master 06094b4] Trigger notification
Marcs-MBP:mm2 marcschipperheijn$ git push dokku
Counting objects: 1, done.
Writing objects: 100% (1/1), 193 bytes | 0 bytes/s, done.
Total 1 (delta 0), reused 0 (delta 0)
-----> Cleaning up...
-----> Building mm from herokuish...
-----> Adding BUILD_ENV to build environment...
-----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       NPM_CONFIG_PRODUCTION=false
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=true

-----> Installing binaries
       engines.node (package.json):  ~6.10.3
       engines.npm (package.json):   unspecified (use default)

       Resolving node version ~6.10.3 via semver.io...
       Downloading and installing node 6.10.3...
       Using default npm version: 3.10.10
       Resolving yarn version (latest) via semver.io...
       Downloading and installing yarn (0.24.5)...
       Installed yarn 0.24.5

-----> Restoring cache
       Loading 2 from cacheDirectories (default):
       - node_modules
       - bower_components (not cached - skipping)

-----> Building dependencies
       Installing node modules (yarn.lock)
       yarn install v0.24.5
       $ node internal/scripts/preinstall
       [1/4] Resolving packages...
       [2/4] Fetching packages...
       warning fsevents@1.0.15: The platform "linux" is incompatible with this module.
       info "fsevents@1.0.15" is an optional dependency and failed compatibility check. Excluding it from installation.
       [3/4] Linking dependencies...
       warning "react-styled-flexboxgrid@1.1.2" has incorrect peer dependency "styled-components@^1.3.1 || ^2.0.0-17".
       [4/4] Building fresh packages...
       $ npm run build

       > react-universally@13.0.0 build /tmp/build
       > babel-node internal/scripts/build --optimize

==> Registering environment variables from: /tmp/build/.env
==> Creating an optimised bundle configuration for the "client"
       loader option has been deprecated - replace with "use"
==> Creating an optimised bundle configuration for the "server"
       Hash: 3da1352e5e8f4a5467f3
       Version: webpack 2.6.1
       Time: 156672ms
       Asset     Size  Chunks             Chunk Names
       0-bbe31ddeb056e33b1f34.js   224 kB       0  [emitted]
       1-9a824b6c0e696a34878b.js  30.9 kB       1  [emitted]
       2-52dc2b15e4173a333218.js  10.2 kB       2  [emitted]
       index.js   700 kB       3  [emitted]  index
       0-bbe31ddeb056e33b1f34.js.map   216 kB       0  [emitted]
       1-9a824b6c0e696a34878b.js.map  26.8 kB       1  [emitted]
       2-52dc2b15e4173a333218.js.map  6.62 kB       2  [emitted]
       index.js.map   848 kB       3  [emitted]  index
       chunk    {0} 0-bbe31ddeb056e33b1f34.js, 0-bbe31ddeb056e33b1f34.js.map 165 kB {3} [rendered]
       [214] ./shared/SyncApp.js 2.73 kB {0} [built]
       [216] ./shared/styles/CommonStyles.js 6.44 kB {0} [built]
       [227] ./shared/resources/i8n/mm.en.js 6.06 kB {0} [optional] [built]
       [228] ./shared/resources/i8n/mm.pt.js 6.86 kB {0} [optional] [built]
       [230] ./shared/resources/react-intl/pt.js 3.55 kB {0} [optional] [built]
       [232] ./shared/utils/i8n/intl.js 405 bytes {0} [built]
       [236] ./shared/resources/i8n ^./mm..*$ 214 bytes {0} [built]
       [266] ./shared/screens/Home.js 5.32 kB {0} [built]
       [267] ./shared/screens/home/Bios.js 5.11 kB {0} [built]
       [276] ./shared/screens/index.js 244 bytes {0} [built]
       [277] ./shared/store/configureStore.js 688 bytes {0} [built]
       [278] ./shared/store/reducers.js 363 bytes {0} [built]
       [279] ./shared/styles/globalCss.js 903 bytes {0} [built]
       [280] ./shared/styles/icons.js 1.23 kB {0} [built]
       [290] ./shared/resources/react-intl ^./.*$ 202 bytes {0} [built]
       + 48 hidden modules
       chunk    {1} 1-9a824b6c0e696a34878b.js, 1-9a824b6c0e696a34878b.js.map 19.5 kB {0} [rendered]
       [223] ./shared/components/navigation/Button.js 2.32 kB {1} [built]
       [231] ./shared/utils.js 744 bytes {1} [built]
       [261] ./shared/modules/contact/ContactActionTypes.js 139 bytes {1} [built]
       [262] ./shared/modules/contact/actions/contactActions.js 1.64 kB {1} [built]
       [263] ./shared/modules/contact/forms/ContactForm.js 5.42 kB {1} [built]
       [264] ./shared/modules/forms/functions/formFunctions.js 2.54 kB {1} [built]
       [272] ./shared/screens/home/contact/Contact.js 6.61 kB {1} [built]
       [281] ./shared/utils/tapEvents.js 118 bytes {1} [built]
       chunk    {2} 2-52dc2b15e4173a333218.js, 2-52dc2b15e4173a333218.js.map 5.88 kB {0} [rendered]
       [274] ./shared/screens/home/hiring/Hiring.js 5.88 kB {2} [built]
       chunk    {3} index.js, index.js.map (index) 658 kB [entry] [rendered]
       [5] ./config/index.js 3.95 kB {3} [built]
       [14] external "app-root-dir" 42 bytes {3} [not cacheable]
       [15] external "path" 42 bytes {3} [not cacheable]
       [81] external "express" 42 bytes {3} [not cacheable]
       [90] ./server/index.js 2.54 kB {3} [built]
       [102] ./server/middleware/chatHandler.js 1.75 kB {3} [built]
       [103] ./server/middleware/clientBundle.js 346 bytes {3} [built]
       [104] ./server/middleware/errorHandlers.js 852 bytes {3} [built]
       [105] ./server/middleware/mailHandler.js 2.57 kB {3} [built]
       [106] ./server/middleware/offlinePage.js 1.22 kB {3} [built]
       [111] ./server/middleware/serviceWorker.js 414 bytes {3} [built]
       [192] external "body-parser" 42 bytes {3} [not cacheable]
       [194] external "compression" 42 bytes {3} [not cacheable]
       [204] external "http" 42 bytes {3} [not cacheable]
       [213] multi ./server/index.js 28 bytes {3} [built]
       + 218 hidden modules

       WARNING in ./shared/modules/chatbot/functions/botScript.js
       23:20-30 "export 'saveWeight' was not found in './chatAPI'

       WARNING in ./shared/modules/chatbot/functions/botScript.js
       52:20-30 "export 'saveWeight' was not found in './chatAPI'
       Hash: 4d672dace247f3f9adaf
       Version: webpack 2.6.1
       Time: 231240ms
       Asset     Size  Chunks             Chunk Names
       af41be6924f9c8211166d3617d12bef2.ttf  2.83 kB          [emitted]
       2b66f705e2dd0efa798a98fe687ed86d.eot  44.4 kB          [emitted]
       69f1400361a215519d385199118a34aa.ttf  44.3 kB          [emitted]
       c556ea6e1425e6e8871741ceba9c8e53.woff  19.1 kB          [emitted]
       8197018935f2e90f1531ef6c7276da46.svg  56.4 kB          [emitted]
       59b29634fc30144bbf16015659a3ae82.ttf  24.8 kB          [emitted]
       c2c196608bf159e903b4673296c661da.woff  11.5 kB          [emitted]
       27674ea7e09f7237517b005e7ea80d22.eot  33.8 kB          [emitted]
       4829f08385300b6c1f5dca7cd92ab89b.svg    98 kB          [emitted]
       1d6e07ebbc5886e714ee7de3b3b8164f.ttf  33.6 kB          [emitted]
       cd64e229e2bdc704d4ccf4e044d613ff.woff  22.2 kB          [emitted]
       16579436549dd1128209eb991d4d2be2.eot  2.98 kB          [emitted]
       16e1c72ddad39b87b5783655262524ec.svg  4.39 kB          [emitted]
       a28f51b9d3f0a244cb74fb5fc563d5cd.svg  51.2 kB          [emitted]
       7b88ba1717fdea9a44acf5a799c1da15.woff  2.19 kB          [emitted]
       806dfbd790b070ccfe05978cb27dd5bf.eot    25 kB          [emitted]
       0-6ef6da38246c71470f5d.js   238 kB       0  [emitted]
       1-2a39e135a3423ced8910.js   240 kB       1  [emitted]
       2-44370d88514c6cec2369.js  5.24 kB       2  [emitted]
       index-57c53cba4d0af05e5966.js   131 kB       3  [emitted]  index
       0-6ef6da38246c71470f5d.js.map  1.58 MB       0  [emitted]
       1-2a39e135a3423ced8910.js.map  1.86 MB       1  [emitted]
       2-44370d88514c6cec2369.js.map  19.2 kB       2  [emitted]
       index-57c53cba4d0af05e5966.js.map   927 kB       3  [emitted]  index
       offline.html  1.77 kB          [emitted]
       sw.js  16.8 kB          [emitted]
       chunk    {0} 0-6ef6da38246c71470f5d.js, 0-6ef6da38246c71470f5d.js.map 623 kB {3} [rendered]
       [74] ./shared/SyncApp.js 3.77 kB {0} [built]
       [77] ./shared/styles/CommonStyles.js 8.04 kB {0} [built]
       [186] ./~/react-intl-redux/lib/index.js 1.85 kB {0} [built]
       [219] ./shared/utils/i8n/intl.js 750 bytes {0} [built]
       [266] ./~/react-ga/src/utils/trim.js 203 bytes {0} [built]
       [267] ./~/react-intl-redux/lib/components/IntlProvider.js 862 bytes {0} [built]
       [288] ./shared/resources/i8n ^./mm..*$ 214 bytes {0} [built]
       [388] ./shared/screens/index.js 672 bytes {0} [built]
       [389] ./shared/store/configureStore.js 1.02 kB {0} [built]
       [391] ./shared/styles/globalCss.js 938 bytes {0} [built]
       [392] ./shared/styles/icons.js 1.26 kB {0} [built]
       [631] ./~/react-ga/src/index.js 12.9 kB {0} [built]
       [633] ./~/react-ga/src/utils/format.js 421 bytes {0} [built]
       [635] ./~/react-ga/src/utils/removeLeadingSlash.js 149 bytes {0} [built]
       [650] ./~/react-redux/lib/components/Provider.js 3.44 kB {0} [built]
       + 263 hidden modules
       chunk    {1} 1-2a39e135a3423ced8910.js, 1-2a39e135a3423ced8910.js.map 642 kB {0} [rendered]
       [85] ./~/redux-form/es/structure/plain/index.js 587 bytes {1} [built]
       [119] ./~/babel-runtime/helpers/createClass.js 904 bytes {1} [built]
       [120] ./~/babel-runtime/helpers/inherits.js 1.11 kB {1} [built]
       [121] ./~/babel-runtime/helpers/possibleConstructorReturn.js 542 bytes {1} [built]
       [189] ./~/redux-form/es/index.js 3.17 kB {1} [built]
       [210] ./shared/components/navigation/Button.js 3.13 kB {1} [built]
       [259] ./~/material-ui/styles/getMuiTheme.js 13 kB {1} [built]
       [260] ./~/material-ui/utils/colorManipulator.js 7.62 kB {1} [built]
       [373] ./shared/modules/contact/ContactActionTypes.js 250 bytes {1} [built]
       [374] ./shared/modules/contact/actions/contactActions.js 3.15 kB {1} [built]
       [375] ./shared/modules/contact/forms/ContactForm.js 6.44 kB {1} [built]
       [376] ./shared/modules/forms/functions/formFunctions.js 4.72 kB {1} [built]
       [384] ./shared/screens/home/contact/Contact.js 10.6 kB {1} [built]
       [393] ./shared/utils/tapEvents.js 307 bytes {1} [built]
       [609] ./~/material-ui/styles/MuiThemeProvider.js 2.15 kB {1} [built]
       + 376 hidden modules
       chunk    {2} 2-44370d88514c6cec2369.js, 2-44370d88514c6cec2369.js.map 8.89 kB {0} [rendered]
       [386] ./shared/screens/home/hiring/Hiring.js 8.89 kB {2} [built]
       chunk    {3} index-57c53cba4d0af05e5966.js, index-57c53cba4d0af05e5966.js.map (index) 349 kB [entry] [rendered]
       [0] external {"root":"React","commonjs2":"react","commonjs":"react","amd":"react"} 42 bytes {3} [not cacheable]
       [7] (webpack)/buildin/global.js 509 bytes {3} [built]
       [8] ./~/react-async-component/commonjs/index.js 851 bytes {3} [built]
       [16] ./client/index.js 3.94 kB {3} [built]
       [17] ./~/regenerator-runtime/runtime.js 24.4 kB {3} [built]
       [20] ./shared/components/widgets/Loading.js 1.99 kB {3} [built]
       [22] external {"root":"ReactDOM","commonjs2":"react-dom","commonjs":"react-dom","amd":"react-dom"} 42 bytes {3} [not cacheable]
       [23] ./shared/Helmet.js 5.88 kB {3} [built]
       [31] ./client/components/ReactHotLoader.js 688 bytes {3} [built]
       [32] ./client/polyfills/index.js 769 bytes {3} [built]
       [33] ./client/registerServiceWorker.js 1.66 kB {3} [built]
       [34] ./shared/App.js 2.42 kB {3} [built]
       [42] ./.modernizrrc 1.45 kB {3} [built]
       [45] ./~/react-async-bootstrapper/commonjs/index.js 640 bytes {3} [built]
       [73] multi regenerator-runtime/runtime ./client/index.js 40 bytes {3} [built]
       + 59 hidden modules

       WARNING in duplicate-package-checker:
       <prop-types>
       15.5.7 ./~/prop-types
       15.5.10 ./~/react-redux/~/prop-types

       Child __offline_serviceworker:
       Asset     Size  Chunks  Chunk Names
       __offline_serviceworker  7.38 kB       0  __offline_serviceworker
       chunk    {0} __offline_serviceworker (__offline_serviceworker) 17.5 kB [entry] [rendered]
       [0] ./~/offline-plugin/empty-entry.js 0 bytes {0} [built]
       [1] ./~/offline-plugin/lib/misc/sw-loader.js?json=%7B%22data_var_name%22%3A%22__wpo%22%2C%22loaders%22%3A%5B%5D%2C%22cacheMaps%22%3A%5B%5D%7D!./~/offline-plugin/empty-entry.js 17.5 kB {0} [built]
       Child html-webpack-plugin for "offline.html":
       Asset    Size  Chunks  Chunk Names
       offline.html  657 kB       0
       chunk    {0} offline.html 653 kB [entry] [rendered]
       [1] ./~/fbjs/lib/warning.js 2.1 kB {0} [built]
       [3] ./~/object-assign/index.js 2.11 kB {0} [built]
       [12] ./~/react/lib/React.js 3.32 kB {0} [built]
       [43] ./~/react/lib/ReactComponent.js 4.61 kB {0} [built]
       [45] ./~/react/react.js 56 bytes {0} [built]
       [74] ./shared/components/HTML/index.js 2.05 kB {0} [built]
       [75] ./~/react-dom/server.js 65 bytes {0} [built]
       [76] ./~/babel-loader/lib!./internal/webpack/withServiceWorker/offlinePageTemplate.js 6.51 kB {0} [built]
       [92] ./~/prop-types/index.js 1.08 kB {0} [built]
       [114] ./~/react-dom/lib/ReactDOMServer.js 735 bytes {0} [built]
       [118] ./~/react-dom/lib/ReactDefaultInjection.js 3.5 kB {0} [built]
       [158] ./~/react/lib/ReactChildren.js 6.19 kB {0} [built]
       [159] ./~/react/lib/ReactClass.js 26.9 kB {0} [built]
       [160] ./~/react/lib/ReactDOMFactories.js 5.53 kB {0} [built]
       [167] ./~/react/lib/onlyChild.js 1.34 kB {0} [built]
       + 154 hidden modules
       Done in 355.57s.

-----> Caching build
       Clearing previous node cache
       Saving 2 cacheDirectories (default):
       - node_modules
       - bower_components (nothing to cache)

-----> Build succeeded!
-----> Discovering process types
       Procfile declares types -> web
-----> Releasing mm (dokku/mm:latest)...
-----> Deploying mm (dokku/mm:latest)...
-----> Attempting to run scripts.dokku.predeploy from app.json (if defined)
-----> App Procfile file found (/home/dokku/mm/DOKKU_PROCFILE)
-----> DOKKU_SCALE file found (/home/dokku/mm/DOKKU_SCALE)
=====> web=1
-----> Attempting pre-flight checks
       For more efficient zero downtime deployments, create a file CHECKS.
       See http://dokku.viewdocs.io/dokku/deployment/zero-downtime-deploys/ for examples
       CHECKS file not found in container: Running simple container check...
-----> Waiting for 10 seconds ...
-----> Default container check successful!
-----> Running post-deploy
=====> renaming container (1fd3a69773f6) hungry_hopper to mm.web.1
-----> Configuring *.mysite.com.br...(using built-in template)
-----> Configuring mysite.com.br...(using built-in template)
-----> Creating http nginx.conf
-----> Running nginx-pre-reload
       Reloading nginx
-----> Setting config vars
       DOKKU_APP_RESTORE: 1
-----> Attempting to run scripts.dokku.postdeploy from app.json (if defined)
-----> Shutting down old containers in 60 seconds
=====> a5781b05b65c4e33fdcacdcc09b9bf76aeec0bd1c0301c17ea7f864723b5ac74
=====> Application deployed:
       http://*.mysite.com.br
       http://mysite.com.br

To 104.104.104.104:mm
   3d4cd32..06094b4  master -> master

Any suggestions?


来源: stackexchange

问:
function prototype variable scope C++
Are variables in function prototype declaration in C++ considered global in scope?

E.g. In the script below, we declare a function prototype of readArray that takes an array integerArray and integer maxNumElements as input and returns the number of elements the user has provided. Of course, the readArray function is called from main. My question is if displayArray can print the array edited in readArray by being provided the maximum number of elements the user has inserted. In short, are integerArray and numElements global?

```<code>/* prototype declaration*/
int readArray (int integerArray [], int maxNumElements);
void displayArray(int integerArray[], int numElements);

int main()
{
    int inputValues[128]; /*the array to be read*/
    int numberOfValues = readArray(inputValues, 128);
    displayArray(inputValues, numberOfValues);
    return 0;
}

int readArray(int integerArray[], int maxNumElements)
{
    int numberOfValues;
    for (numberOfValues = 0; numberOfValues < maxNumElements; numberOfValues++)
    { /*take integers as input from user and insert into array */
       /*return the number of elements the user as provided*/
    }
    return numberOfValues;
}

void displayArray(int integerArray[], int numElements)
{ /*print the array*/
    for (int = 0; i < numElements; i++)
    {
        cout << i << ":" << integerArray[i] << endl;
    }
    cout << endl;
}
</code>```

答:
I don't think it makes sense to speak of function parameters as variables. They basically serve as placeholder for data you will provide to the function when you call it.

So, in your example you are not operating on integerArray, rather you are operating on the data pointed to by int inputValues[128], which you declare in main(). inputValue is the variable, not integerArray.

In your case you happen to be doing what is called call-by-reference. I.e. your function prototypes are receiving a pointer to an integer. When you pass the pointer inputValues to readArray:

```<code>int numberOfValues = readArray(inputValues, 128);
</code>```

then you are giving it the address inputValues. readValues will then operate on the memory area pointed to by inputValues.

Thus, displayArray will display the data edited by readArray in your example.

Please note that this is a result of you doing a call-by-reference, not that the function parameters are in some sense in global scope.

If you function prototypes had looked something like this:

```<code>int readArray (vector<int> integerArray);
void displayArray(vector<int> integerArray);
</code>```

Then displayArray would not be printing the content of integerArray in any sense. When you call readArray, you would be doing a call by-value: It would get a copy of inputValues (in that case it would be declared as vector<int> inputValues) and when the function call returns, you are left with the original value of inputValues and in this particular case, displayArray would print an empty vector.

ContentLicense: CC BY-SA 3.0

Title: function prototype variable scope C++

Body:
Are variables in function prototype declaration in C++ considered global in scope?

E.g. In the script below, we declare a function prototype of readArray that takes an array integerArray and integer maxNumElements as input and returns the number of elements the user has provided. Of course, the readArray function is called from main. My question is if displayArray can print the array edited in readArray by being provided the maximum number of elements the user has inserted. In short, are integerArray and numElements global?

/* prototype declaration*/
int readArray (int integerArray [], int maxNumElements);
void displayArray(int integerArray[], int numElements);

int main()
{
    int inputValues[128]; /*the array to be read*/
    int numberOfValues = readArray(inputValues, 128);
    displayArray(inputValues, numberOfValues);
    return 0;
}

int readArray(int integerArray[], int maxNumElements)
{
    int numberOfValues;
    for (numberOfValues = 0; numberOfValues < maxNumElements; numberOfValues++)
    { /*take integers as input from user and insert into array */
       /*return the number of elements the user as provided*/
    }
    return numberOfValues;
}

void displayArray(int integerArray[], int numElements)
{ /*print the array*/
    for (int = 0; i < numElements; i++)
    {
        cout << i << ":" << integerArray[i] << endl;
    }
    cout << endl;
}

Body:
I don't think it makes sense to speak of function parameters as variables. They basically serve as placeholder for data you will provide to the function when you call it.

So, in your example you are not operating on integerArray, rather you are operating on the data pointed to by int inputValues[128], which you declare in main(). inputValue is the variable, not integerArray.

In your case you happen to be doing what is called call-by-reference. I.e. your function prototypes are receiving a pointer to an integer. When you pass the pointer inputValues to readArray:

int numberOfValues = readArray(inputValues, 128);

then you are giving it the address inputValues. readValues will then operate on the memory area pointed to by inputValues.

Thus, displayArray will display the data edited by readArray in your example.

Please note that this is a result of you doing a call-by-reference, not that the function parameters are in some sense in global scope.

If you function prototypes had looked something like this:

int readArray (vector<int> integerArray);
void displayArray(vector<int> integerArray);

Then displayArray would not be printing the content of integerArray in any sense. When you call readArray, you would be doing a call by-value: It would get a copy of inputValues (in that case it would be declared as vector<int> inputValues) and when the function call returns, you are left with the original value of inputValues and in this particular case, displayArray would print an empty vector.


问:
Get one of group elements using index failed
I tried to get one of elements with XPath in selenium WebdriverIO.

I have a group of  <input> elements which as children of an element
 the first of it's group(sorry about the dev's legacy product, but I am trying to play the QA part)

All <input> element are placed like this

```<code>/html/body/div[9]/div/form/div[1]/div[3]/div[1]/div/span[1]/input
/html/body/div[9]/div/form/div[1]/div[3]/div[2]/span[2]/input
/html/body/div[9]/div/form/div[1]/div[3]/div[6]/span[1]/input
/html/body/div[9]/div/form/div[1]/div[3]/div[7]/span[1]/input
/html/body/div[9]/div/form/div[1]/div[3]/div[8]/span[1]/input
</code>```

And when I tried to get one of it in for loop

```<code>var i, tar;
for (i = 1; (tar = '//div[@id="content"][1]//input['+i+']') && browser.isExisting(tar); i++) {
}
</code>```

Always get all of them instead one only(checked by Firefinder)

Can't this be done by using index?

答:
You can try with the following xpath (//div[@id="content"][1]//input)[1].
You can change the index to get the specific element.

Body:
I tried to get one of elements with XPath in selenium WebdriverIO.

I have a group of  <input> elements which as children of an element
 the first of it's group(sorry about the dev's legacy product, but I am trying to play the QA part)

All <input> element are placed like this

/html/body/div[9]/div/form/div[1]/div[3]/div[1]/div/span[1]/input
/html/body/div[9]/div/form/div[1]/div[3]/div[2]/span[2]/input
/html/body/div[9]/div/form/div[1]/div[3]/div[6]/span[1]/input
/html/body/div[9]/div/form/div[1]/div[3]/div[7]/span[1]/input
/html/body/div[9]/div/form/div[1]/div[3]/div[8]/span[1]/input

And when I tried to get one of it in for loop

var i, tar;
for (i = 1; (tar = '//div[@id="content"][1]//input['+i+']') && browser.isExisting(tar); i++) {
}

Always get all of them instead one only(checked by Firefinder)

Can't this be done by using index?


问:
Minimal Footprint / Bare-bones ASP.NET Core WebAPI
Just for fun, earlier today one of my colleagues asked if I could try and make a tiny-footprint WebAPI that echoed requests using ASP.NET Core. I was able to get the WebAPI done in about 70 lines of code. All thanks to ASP.NET Core being amazing! So, this is what I ended up with so far.

The Code

```<code>using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Linq;

namespace TinyWebApi
{
    class Program
    {
        static readonly IWebHost _host;
        static readonly string[] _urls = { "http://localhost:80" };

        static Program()
        {
            IConfiguration _configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();
            _host = BuildHost(new WebHostBuilder(), _configuration, _urls);
        }

        static void Main(string[] args)
        {
            _host.Run();
        }

        static IWebHost BuildHost(
            IWebHostBuilder builder, IConfiguration configuration, params string[] urls)
        {
            return builder
                .UseKestrel(options =>
                {
                    options.NoDelay = true;
                })
                .UseConfiguration(configuration)
                .UseUrls(urls)
                .Configure(app =>
                {
                    app.Map("/echo", EchoHandler);
                })
                .Build();
        }

        static void EchoHandler(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                await context.Response.WriteAsync(
                    JsonConvert.SerializeObject(new
                    {
                        StatusCode = (string)context.Response.StatusCode.ToString(),
                        PathBase = (string)context.Request.PathBase.Value.Trim('/'),
                        Path = (string)context.Request.Path.Value.Trim('/'),
                        Method = (string)context.Request.Method,
                        Scheme = (string)context.Request.Scheme,
                        ContentType = (string)context.Request.ContentType,
                        ContentLength = (long?)context.Request.ContentLength,
                        QueryString = (string)context.Request.QueryString.ToString(),
                        Query = context.Request.Query
                            .ToDictionary(
                                _ => _.Key,
                                _ => _.Value,
                                StringComparer.OrdinalIgnoreCase)
                    })
                );
            });
        }
    }
}
</code>```

(The code above works as expected, and it's not broken.)

The WebAPI

The WebAPI is supposed to echo back the request with a JSON.

Example Request

```<code>http://localhost/echo?q=foo&q=bar
</code>```

Example Response

```<code>{
  "StatusCode": "200",
  "PathBase": "echo",
  "Path": "",
  "Method": "GET",
  "Scheme": "http",
  "ContentType": null,
  "ContentLength": null,
  "QueryString": "?q=foo&q=bar",
  "Query": {
    "q": [
      "foo",
      "bar"
    ]
  }
}
</code>```

My Problem

I blew my colleague away with just the 70+ lines of code to do the job, but then when we took a look at the file size it wasn't as impressive...

At the moment with all these dependencies, my WebAPI is compiling to 54.3MB.

I am stuck with trying to figure out how to reduce the disk footprint of this project. The packages I have installed are bundled up with so much stuff we don't really need and I keep running into trouble trying to find out the best resource or method to removing the unneeded references for this project.

The .csproj

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
    <ApplicationIcon>Icon.ico</ApplicationIcon>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="1.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.2" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
  </ItemGroup>

</Project>
</code>```

Is there any quick way for me to know what references my project needs based on the code provided? I started earlier by wiping clear all the above dependencies and then trying to add them one by one, but it turns out to become a never ending headache of trying to solve missing references and it seems to take forever to solve. I'm sure someone out there has a solution for something like this, but I can't seem to find it. Thanks.

答:
What I did was just copy the code to a new .NET Core console project and resolved the missing references. To figure out which ones you need to add for the missing APIs I just did F12 on the missing member (Go to definition) in the working project with all references to see in which assembly the API is defined.

Since you're not using anything fancy here, so the ASP.NET Core Web application template shipped in VS already uses all of these APIs, so you could use that as the 'working project'.

The AddJsonFile for example was defined in Microsoft.Extensions.Configuration.Json package.

So in the end I was left with

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
  </ItemGroup>

</Project>
</code>```

When published it added up to 2.41MB.

Granted you probably wouldn't want to do this on a bigger project.
On this project in only takes a minute or so.

Body:
Just for fun, earlier today one of my colleagues asked if I could try and make a tiny-footprint WebAPI that echoed requests using ASP.NET Core. I was able to get the WebAPI done in about 70 lines of code. All thanks to ASP.NET Core being amazing! So, this is what I ended up with so far.

The Code

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Linq;

namespace TinyWebApi
{
    class Program
    {
        static readonly IWebHost _host;
        static readonly string[] _urls = { "http://localhost:80" };

        static Program()
        {
            IConfiguration _configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();
            _host = BuildHost(new WebHostBuilder(), _configuration, _urls);
        }

        static void Main(string[] args)
        {
            _host.Run();
        }

        static IWebHost BuildHost(
            IWebHostBuilder builder, IConfiguration configuration, params string[] urls)
        {
            return builder
                .UseKestrel(options =>
                {
                    options.NoDelay = true;
                })
                .UseConfiguration(configuration)
                .UseUrls(urls)
                .Configure(app =>
                {
                    app.Map("/echo", EchoHandler);
                })
                .Build();
        }

        static void EchoHandler(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                await context.Response.WriteAsync(
                    JsonConvert.SerializeObject(new
                    {
                        StatusCode = (string)context.Response.StatusCode.ToString(),
                        PathBase = (string)context.Request.PathBase.Value.Trim('/'),
                        Path = (string)context.Request.Path.Value.Trim('/'),
                        Method = (string)context.Request.Method,
                        Scheme = (string)context.Request.Scheme,
                        ContentType = (string)context.Request.ContentType,
                        ContentLength = (long?)context.Request.ContentLength,
                        QueryString = (string)context.Request.QueryString.ToString(),
                        Query = context.Request.Query
                            .ToDictionary(
                                _ => _.Key,
                                _ => _.Value,
                                StringComparer.OrdinalIgnoreCase)
                    })
                );
            });
        }
    }
}

(The code above works as expected, and it's not broken.)

The WebAPI

The WebAPI is supposed to echo back the request with a JSON.

Example Request

http://localhost/echo?q=foo&q=bar

Example Response

{
  "StatusCode": "200",
  "PathBase": "echo",
  "Path": "",
  "Method": "GET",
  "Scheme": "http",
  "ContentType": null,
  "ContentLength": null,
  "QueryString": "?q=foo&q=bar",
  "Query": {
    "q": [
      "foo",
      "bar"
    ]
  }
}

My Problem

I blew my colleague away with just the 70+ lines of code to do the job, but then when we took a look at the file size it wasn't as impressive...

At the moment with all these dependencies, my WebAPI is compiling to 54.3MB.

I am stuck with trying to figure out how to reduce the disk footprint of this project. The packages I have installed are bundled up with so much stuff we don't really need and I keep running into trouble trying to find out the best resource or method to removing the unneeded references for this project.

The .csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
    <ApplicationIcon>Icon.ico</ApplicationIcon>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="1.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.2" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
  </ItemGroup>

</Project>

Is there any quick way for me to know what references my project needs based on the code provided? I started earlier by wiping clear all the above dependencies and then trying to add them one by one, but it turns out to become a never ending headache of trying to solve missing references and it seems to take forever to solve. I'm sure someone out there has a solution for something like this, but I can't seem to find it. Thanks.

Body:
What I did was just copy the code to a new .NET Core console project and resolved the missing references. To figure out which ones you need to add for the missing APIs I just did F12 on the missing member (Go to definition) in the working project with all references to see in which assembly the API is defined.

Since you're not using anything fancy here, so the ASP.NET Core Web application template shipped in VS already uses all of these APIs, so you could use that as the 'working project'.

The AddJsonFile for example was defined in Microsoft.Extensions.Configuration.Json package.

So in the end I was left with

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
  </ItemGroup>

</Project>

When published it added up to 2.41MB.

Granted you probably wouldn't want to do this on a bigger project.
On this project in only takes a minute or so.


问:
Currency conversion in Rails
I have an ecommerce site with multi language.

I am handling the multi-language translation using the I18n API; like this:

```<code>def set_locale
    I18n.locale = session[:locale]
end
</code>```

This is pretty useful with static texts, so I can have different dictionaries to separate the texts.

How ever, this is an ecommerce; so price variables are needed.

I am trying to use mexican pesos and US dollars

The price is storaged in MXN in database.

I also have one option in the database with the mxn_to_usd value.

So 1 USD = 18 MXN.

Right now, to display prices; I am doing this:

```<code>number_to_currency(disc.price, :unit => "$")
</code>```

But this only works for one currency.

What i've tried is to rewrite the number_to_currency method; so when the I18n.locale is "EN" it converts the MXN (the one stored in DB) to US dollars.

But no success yet.

Any ideas?

答:
You can use the ultra lightweight concurrency gem which provides you with the basic conversion functionality using methods like:</p>

```<code>Concurrency.convert(100, "USD", "INR")  # would convert 100 dollars to Indian Rupees
Concurrency.conversion_rate("USD", "INR")  # would convert 1 USD to INR
</code>```

Title: Currency conversion in Rails

Body:
I have an ecommerce site with multi language.

I am handling the multi-language translation using the I18n API; like this:

def set_locale
    I18n.locale = session[:locale]
end

This is pretty useful with static texts, so I can have different dictionaries to separate the texts.

How ever, this is an ecommerce; so price variables are needed.

I am trying to use mexican pesos and US dollars

The price is storaged in MXN in database.

I also have one option in the database with the mxn_to_usd value.

So 1 USD = 18 MXN.

Right now, to display prices; I am doing this:

number_to_currency(disc.price, :unit => "$")

But this only works for one currency.

What i've tried is to rewrite the number_to_currency method; so when the I18n.locale is "EN" it converts the MXN (the one stored in DB) to US dollars.

But no success yet.

Any ideas?

Body:
You can use the ultra lightweight concurrency gem which provides you with the basic conversion functionality using methods like:

Concurrency.convert(100, "USD", "INR")  # would convert 100 dollars to Indian Rupees
Concurrency.conversion_rate("USD", "INR")  # would convert 1 USD to INR


问:
How to check if a pair of values exist on a 2-dimensional array in java
I have a 2d array of that form:

```<code>int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};
</code>```

and i want to check programmaticaly if a pair of values {j,k}
exist on my 2d array moves.

答:
You can do it with an enhanced for loop:

```<code>boolean exists = false;
for (int[] move : moves) {
    if (move[0] == i && move[1] == j) {
        exists = true;
        break;
    }
}
</code>```

At the end of the loop variable exists is set to true if a pair {i, j} exists in the moves array; otherwise, exists remains false.

Body:
I have a 2d array of that form:

int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};

and i want to check programmaticaly if a pair of values {j,k}
exist on my 2d array moves.

Body:
You can do it with an enhanced for loop:

boolean exists = false;
for (int[] move : moves) {
    if (move[0] == i && move[1] == j) {
        exists = true;
        break;
    }
}

At the end of the loop variable exists is set to true if a pair {i, j} exists in the moves array; otherwise, exists remains false.


问:
Firebase connection state always returning false on first run
I use the following function in my iOS app to check if we're connected to Firebase. When this function is run the first time in the app, it always returns false for the connection state (even if I'm connected to Firebase). Dismissing the "no internet" alert and calling the function again returns the correct connection state (true).

Do you know why Firebase doesn't return a true connection state the first time the function is run?

```<code>func checkInternetOnLoad(){

    let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")

    connectedRef.observeSingleEvent(of: .value, with: { (snapshot) in

        // Log snapshot value (Note: this is always false the first time the function is run
        print(snapshot.value as? Bool!)

        if let connected = snapshot.value as? Bool{

            if !connected{
                // We don't have internet

                // Show alert saying we don't have internet. Pressing "Try Now" reruns the function to check internet again.
                let alert = showError(title: "Your Phone's Offline", message: "If you're online and seeing this message, please contact support.", cancelMessage: "Try now", cancelAction: {
                    self.checkInternetOnLoad()
                })
                self.present(alert, animated: true, completion: nil)

            } else {

                // We have internet. Do stuff
            }

        }
    })
}
</code>```

答: Couldn't figure it out so my hacky workaround for now is to call the observeSingleEvent() function a second time five seconds later, which returns the correct connection state.</p>

Body:
I use the following function in my iOS app to check if we're connected to Firebase. When this function is run the first time in the app, it always returns false for the connection state (even if I'm connected to Firebase). Dismissing the "no internet" alert and calling the function again returns the correct connection state (true).

Do you know why Firebase doesn't return a true connection state the first time the function is run?

func checkInternetOnLoad(){

    let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")

    connectedRef.observeSingleEvent(of: .value, with: { (snapshot) in

        // Log snapshot value (Note: this is always false the first time the function is run
        print(snapshot.value as? Bool!)

        if let connected = snapshot.value as? Bool{

            if !connected{
                // We don't have internet

                // Show alert saying we don't have internet. Pressing "Try Now" reruns the function to check internet again.
                let alert = showError(title: "Your Phone's Offline", message: "If you're online and seeing this message, please contact support.", cancelMessage: "Try now", cancelAction: {
                    self.checkInternetOnLoad()
                })
                self.present(alert, animated: true, completion: nil)

            } else {

                // We have internet. Do stuff
            }

        }
    })
}


问:
Get a unique count of users over a rolling 3 month period
So I have a table that has a column for usernames and then a column with the 1st of the month for each time that user logged into our service. I would like to get a unique user count looking a rolling three months backward for every month in the table. So for example the data looks like this:

```<code>username  Month
Bob       01/01/2017
Joe       12/01/2017
Sam       01/01/2017
Bob       01/01/2017
Joe       12/01/2017
Frank     02/01/2017
Alice     02/01/2017
John      02/01/2017
Jen       03/01/2017
</code>```

and I would want my results to look like this:

```<code>Month         Rolling3MonthUniqueUserCount
12/01/2017    1
01/01/2017    3
02/01/2017    6
03/01/2017    6
</code>```

The query (or Multiple queries) have to do two things:

identify the day 3 months back from the date in
the table

Get the unique user count within that 3 month period

For the life of me I cant figure out how to do this, and any help would be appreciated. Thanks :)

P.S. Im using access which uses T-SQL. Which slightly limits the functions that you can use.

答:
In MS-Access, the simplest method is going to be correlated subqueries.

First, you need a list of months:

```<code>select distinct DateSerial(datecol), Month(datecol), 1)
from t;
</code>```

Then you can get the list of values using a correlated subquery:

```<code>select m.month,
       (select count(*)
        from t
        where t.datecol >= dateadd("m", -3, m.month) and
              t.datecol < m.month
       ) as rolling_count
from (select distinct DateSerial(datecol), Month(datecol), 1) as month
      from t
     ) as m;
</code>```

This calculates three complete previous months starting on the first.  So the count for January, February, and March would be on April 1st. You can adjust the query if you have a different definition in mind.

Does this work in MS Access?

```<code>select m.month,
       (select count(*)
        from (select distinct name
              from t
              where t.datecol >= dateadd("m", -3, m.month) and
                    t.datecol < m.month
             ) as x
       ) as rolling_count
from (select distinct DateSerial(datecol), Month(datecol), 1) as month
      from t
     ) as m;
</code>```

I don't remember the scoping rules for MS Access.

Body:
So I have a table that has a column for usernames and then a column with the 1st of the month for each time that user logged into our service. I would like to get a unique user count looking a rolling three months backward for every month in the table. So for example the data looks like this:

username  Month
Bob       01/01/2017
Joe       12/01/2017
Sam       01/01/2017
Bob       01/01/2017
Joe       12/01/2017
Frank     02/01/2017
Alice     02/01/2017
John      02/01/2017
Jen       03/01/2017

and I would want my results to look like this:

Month         Rolling3MonthUniqueUserCount
12/01/2017    1
01/01/2017    3
02/01/2017    6
03/01/2017    6

The query (or Multiple queries) have to do two things:

identify the day 3 months back from the date in
the table

Get the unique user count within that 3 month period

For the life of me I cant figure out how to do this, and any help would be appreciated. Thanks :)

P.S. Im using access which uses T-SQL. Which slightly limits the functions that you can use.

Body:
In MS-Access, the simplest method is going to be correlated subqueries.

First, you need a list of months:

select distinct DateSerial(datecol), Month(datecol), 1)
from t;

Then you can get the list of values using a correlated subquery:

select m.month,
       (select count(*)
        from t
        where t.datecol >= dateadd("m", -3, m.month) and
              t.datecol < m.month
       ) as rolling_count
from (select distinct DateSerial(datecol), Month(datecol), 1) as month
      from t
     ) as m;

This calculates three complete previous months starting on the first.  So the count for January, February, and March would be on April 1st. You can adjust the query if you have a different definition in mind.

Does this work in MS Access?

select m.month,
       (select count(*)
        from (select distinct name
              from t
              where t.datecol >= dateadd("m", -3, m.month) and
                    t.datecol < m.month
             ) as x
       ) as rolling_count
from (select distinct DateSerial(datecol), Month(datecol), 1) as month
      from t
     ) as m;

I don't remember the scoping rules for MS Access.


问:
Puppet - how to apply module to puppet client node?
just starting with Puppet, really new to this world.

I have

CentOS 6 Puppet Master

CentOS 6 Puppet Client

In Master have one module:

```<code> puppet module list
/etc/puppet/modules
âââ mstanislav-yum (v1.0.0)
</code>```

So I want to apply same module to my puppet client but I can't or I don't know why

```<code>root@puppetclient: puppet agent --test
Info: Retrieving plugin
Info: Caching catalog for puppetclient
Info: Applying configuration version '1355737643'
Finished catalog run in 0.10 seconds
</code>```

but there are not any changes to the client :-/

Any idea?

答:
If you have added the node declaration in another location that isn't site.pp (which is the recommended way to do it) then remember to add the "import" config to site.pp which would reference the node manifest.

This is how my config looks like. Main manifest DIR with nodes DIR and site.pp file:

```<code>drwxr-xr-x. 3 root root 4096 May 19 07:23 nodes
-rw-r--r--. 1 root root   62 Jun  4 16:31 site.pp
</code>```

This is the node declaration in my nodes DIR:

```<code>node 'fqdn of client' {
  include yum
}
</code>```

Finally, site.pp in the main manifest DIR would import the node as follow:

```<code>import 'nodes/*.pp'

node default { }
</code>```

Body:
just starting with Puppet, really new to this world.

I have

CentOS 6 Puppet Master

CentOS 6 Puppet Client

In Master have one module:

 puppet module list
/etc/puppet/modules
âââ mstanislav-yum (v1.0.0)

So I want to apply same module to my puppet client but I can't or I don't know why

root@puppetclient: puppet agent --test
Info: Retrieving plugin
Info: Caching catalog for puppetclient
Info: Applying configuration version '1355737643'
Finished catalog run in 0.10 seconds

but there are not any changes to the client :-/

Any idea?

Body:
If you have added the node declaration in another location that isn't site.pp (which is the recommended way to do it) then remember to add the "import" config to site.pp which would reference the node manifest.

This is how my config looks like. Main manifest DIR with nodes DIR and site.pp file:

drwxr-xr-x. 3 root root 4096 May 19 07:23 nodes
-rw-r--r--. 1 root root   62 Jun  4 16:31 site.pp

This is the node declaration in my nodes DIR:

node 'fqdn of client' {
  include yum
}

Finally, site.pp in the main manifest DIR would import the node as follow:

import 'nodes/*.pp'

node default { }


问:
In Xcode, is there a way to set up a table which is not for UI but like an 'engine' for processing data
I'm wondering if there is some sort of way to set up something similar to a spreadsheet in Xcode. I'm trying to create a 'tapping game' or a 'clicker game' and storing so many variables in regular coding would be really tough.

Having this 'table' would enable me to keep track of multipliers and upgrade levels instead of clogging my coding with it.

Preferably, I could then just tell my code what to pull and what to look for off of the table. The table would be an 'engine' of sorts and it would not be UI. The table would do all of the work behind scenes, then show it through UI based on labels and buttons.

答:
As traxido is saying, without more details we can't point you to a concrete example/solution. Base on the title the answer is yes. It's not a ui component though. It doesn't even need to be one.
What you want is a data structure to hold your data in a way that's convenient to access (save and retrieve).  You could create a class which is a composite of other data structures like arrays and dictionaries and possibly other data structures. You might end up having many questions before you're through.
So: the answer is yes. Try it yourself and ask new questions if you get stuck.
Provide the code and error messages and I bet you quickly get answers.</p>


答:
```<code>int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};

for(int j = 0; j < moves.length; j++){
    for(int k = 0; k < moves[j].length; k++){
        if(moves[j][k] != 0){
            System.out.println("Exist");
        }
    }
}
</code>```

If you want to check for specific index change moves[j][k] to your desired index. Or if you want to compare two values,

Change:

```<code>if(moves[j][k] != 0){
</code>```

To:

```<code>if(moves[j] == 44 && moves[k] == 44){
</code>```

If you want to return true or false rather than printing something you can use:

```<code>return true;
</code>```

Or If you want to return values in specific index rather than printing something you can use:

```<code>return moves[j][k];
</code>```

Title: How to check if a pair of values exist on a 2-dimensional array in java

Body:
int[][] moves ;
moves = new int[][]{{1, 2}, {1, -2}, {2, 1}, {2, -1}, {-1, 2},
            {-1, -2}, {-2, 1}, {-2, -1}};

for(int j = 0; j < moves.length; j++){
    for(int k = 0; k < moves[j].length; k++){
        if(moves[j][k] != 0){
            System.out.println("Exist");
        }
    }
}

If you want to check for specific index change moves[j][k] to your desired index. Or if you want to compare two values,

Change:

if(moves[j][k] != 0){

To:

if(moves[j] == 44 && moves[k] == 44){

If you want to return true or false rather than printing something you can use:

return true;

Or If you want to return values in specific index rather than printing something you can use:

return moves[j][k];


问:
Ionic Firebase app using AngularFire2
How can I convert asynchronous mode to synchronous? Just by Subscribing? I am getting data from Firebase using Firebase API's and displaying them in my app but due to asynchronous mode, the display event occurs before the data is retrieved. I am shifting to using AngularFire but not sure if AngularFire by default uses asynchronous. I want to wait for the data before my program moves to executing next steps.  I am using Ionic2, have a provider which connects to Firebase, fetches data, stores in a local array in the provider with the ".then" method. The display page injects the provider and stores Firebase array data locally again in the display page, And then use the local variable in the html (ion-item) to display it. Basically, I want the data to be refreshed with any changes to Firebase data by any user.</p>

答:
The only way to do this, is to use the 'async' in your template like below.

```<code><ion-list>
  <button ion-item class="center" *ngFor="let user of users | async" (click)="showOptions(user.$key, user.Name)">
    {{user.title}}
  </button>
</ion-list>
</code>```

Above, there is a list of users type: 'FirebaseListObservable' which is included from the 'angularfire2/database' like below:

```<code>import { FirebaseListObservable } from 'angularfire2/database';
</code>```

You can check this tutorial, which does exactly what you want and there is a live example on the description.

I suggest you to migrate to Ionic 3, it is much easier to use with firebase.

Title: Ionic Firebase app using AngularFire2

Body:
The only way to do this, is to use the 'async' in your template like below.

<ion-list>
  <button ion-item class="center" *ngFor="let user of users | async" (click)="showOptions(user.$key, user.Name)">
    {{user.title}}
  </button>
</ion-list>

Above, there is a list of users type: 'FirebaseListObservable' which is included from the 'angularfire2/database' like below:

import { FirebaseListObservable } from 'angularfire2/database';

You can check this tutorial, which does exactly what you want and there is a live example on the description.

I suggest you to migrate to Ionic 3, it is much easier to use with firebase.


答:
```<code>for(int i = 0; i < 8; i++)
    {
        if(moves[i][0] == j && moves[i][1] == k)
        {
            //Executable code
        }
    }
</code>```


问:
How to get a field from a result set and print as a string to the page (php/mysql/phpbb)
Im trying to make a custom function for my forum based on php. I have my index landing style page separate to my phpbb forums. I am trying to display the latest registered users username, as part of a statistics type widget for the home page. I have the following code so far:

```<code>//Function code

//Total Posts calculation
$result = $mysqli->query("SELECT DISTINCT post_id FROM phpBB_posts
WHERE post_id <= '1'");

$total_posts = $result->num_rows;

//Total topics calculation
$result2 = $mysqli->query("SELECT DISTINCT topic_id FROM phpBB_topics WHERE topic_id <= '1'");

$total_topics = $result2->num_rows;

//Member count calculation
$result3 = $mysqli->query("SELECT DISTINCT user_id FROM phpBB_users WHERE user_id <= '1'");

$total_members = $result3->num_rows;

//Newest member
$result4 = $mysqli->query("SELECT * FROM phpBB_users WHERE group_id <> 6 ORDER BY user_regdate DESC LIMIT 1");

$newestMember = $result4->name;

//End of function

//function output
printf("Total Posts: ".$total_posts."<br/> Total Topics: ".$total_topics."<br/>Total Members: ".$total_members."<br/>Our newest member is: ".$newestMember);
</code>```

The "Newest member" section is where i'm having trouble, the rest works as I want, if you have any pointers/criticism i'll gladly take it on board though.

I want to be able to return the value in the username column from the results set i get returned from that query, and print it as the variable $newestMember.

My logic as you can see was to get the list of users, so SELECT * then limit the list to actual users and exclude bots etc so WHERE group_id <> 6. Then sort the list by the registered date ORDER BY user_regdate and then only one row from the full list with DESC LIMIT 1. I've been checking mysql and php documentation and can't work out how to get the value from the returned row/username column (field) and store it as the newestMember variable and print to the page.
Can anyone point me in the right direction please?

Cheers, Jamie

答:
Managed to get it working modifying that code a little, deleted the mysqli->query that prepended the SELECT query and that made it work. What finally worked is as per below if anyone else comes across the same issue. Thanks for the nudge in the right direction CBroe! Needed a fresh pair of eyes and to look at it from a different angle :)</p>

```<code>//Newest member
$myresult = ("SELECT * FROM phpBB_users WHERE user_type <> 2 ORDER BY user_regdate DESC LIMIT 1");

if ($result = $mysqli->query($myresult)) {

/* fetch object array */
while ($row = $result->fetch_row()) {
        $newestMember = $row[7];
}

/* free result set */
$result->close();
}

//End of function

//function output
printf("Total Posts: ".$total_posts."<br/> Total Topics: ".$total_topics."<br/>Total Members: ".$total_members."<br/>Our newest member is: ".$newestMember);
</code>```

Body:
Im trying to make a custom function for my forum based on php. I have my index landing style page separate to my phpbb forums. I am trying to display the latest registered users username, as part of a statistics type widget for the home page. I have the following code so far:

//Function code

//Total Posts calculation
$result = $mysqli->query("SELECT DISTINCT post_id FROM phpBB_posts
WHERE post_id <= '1'");

$total_posts = $result->num_rows;

//Total topics calculation
$result2 = $mysqli->query("SELECT DISTINCT topic_id FROM phpBB_topics WHERE topic_id <= '1'");

$total_topics = $result2->num_rows;

//Member count calculation
$result3 = $mysqli->query("SELECT DISTINCT user_id FROM phpBB_users WHERE user_id <= '1'");

$total_members = $result3->num_rows;

//Newest member
$result4 = $mysqli->query("SELECT * FROM phpBB_users WHERE group_id <> 6 ORDER BY user_regdate DESC LIMIT 1");

$newestMember = $result4->name;

//End of function

//function output
printf("Total Posts: ".$total_posts."
 Total Topics: ".$total_topics."
Total Members: ".$total_members."
Our newest member is: ".$newestMember);

The "Newest member" section is where i'm having trouble, the rest works as I want, if you have any pointers/criticism i'll gladly take it on board though.

I want to be able to return the value in the username column from the results set i get returned from that query, and print it as the variable $newestMember.

My logic as you can see was to get the list of users, so SELECT * then limit the list to actual users and exclude bots etc so WHERE group_id <> 6. Then sort the list by the registered date ORDER BY user_regdate and then only one row from the full list with DESC LIMIT 1. I've been checking mysql and php documentation and can't work out how to get the value from the returned row/username column (field) and store it as the newestMember variable and print to the page.
Can anyone point me in the right direction please?

Cheers, Jamie

Body:
Managed to get it working modifying that code a little, deleted the mysqli->query that prepended the SELECT query and that made it work. What finally worked is as per below if anyone else comes across the same issue. Thanks for the nudge in the right direction CBroe! Needed a fresh pair of eyes and to look at it from a different angle :)

//Newest member
$myresult = ("SELECT * FROM phpBB_users WHERE user_type <> 2 ORDER BY user_regdate DESC LIMIT 1");

if ($result = $mysqli->query($myresult)) {

/* fetch object array */
while ($row = $result->fetch_row()) {
        $newestMember = $row[7];
}

/* free result set */
$result->close();
}

//End of function

//function output
printf("Total Posts: ".$total_posts."<br/> Total Topics: ".$total_topics."<br/>Total Members: ".$total_members."<br/>Our newest member is: ".$newestMember);


答:
```<code>for (int x = 0; x < moves.length; ++x) {
    if (moves[x] != j) {
        continue;
    }

    for (int y = 0; y < moves[x].length; ++y) {
        if (moves[x][y] == k) {
            return true;
        }
    }
}

return false;
</code>```


问:
PHP Classes function inside function?
I'm self-studying the PHP language. And I'm focused on the latest PHP OOP language.

I search for some "ready-to-install" PHP software and as I scan for some references to search and know, I saw lines of code with a structure like this (can't remember so I'll create my own):

```<code>$myapp->settings->getValue('openforum');
$myapp->settings->setValue('closeformaintenance', '1');
</code>```

So my question is, how can I reproduce the code above? I don't know what term to use that line of code (objects, I guess?).

Something like this:

```<code>$newLogin->search($uid)->setLogin($dateToday);
</code>```

Like that. I really need to do that way so I can organize my coding structure. Thanks by the way.

And also for the final question, IS THAT POSSIBLE?

答:
What you try to achieve is called method chaining. You can get this by the following:

```<code><?php
class TestClass {
    private $val = '';

    public function test1($val) {
        $this->val = $val;
        return $this;
    }
    public function test2() {
        echo 'Hello '.$this->val;
    }
}

$test->test1('World')->test2(); // Hello World
</code>```

You have simply to return the instance of the object on the method to allow the method chaining.

Title: PHP Classes function inside function?

Body:
I'm self-studying the PHP language. And I'm focused on the latest PHP OOP language.

I search for some "ready-to-install" PHP software and as I scan for some references to search and know, I saw lines of code with a structure like this (can't remember so I'll create my own):

$myapp->settings->getValue('openforum');
$myapp->settings->setValue('closeformaintenance', '1');

So my question is, how can I reproduce the code above? I don't know what term to use that line of code (objects, I guess?).

Something like this:

$newLogin->search($uid)->setLogin($dateToday);

Like that. I really need to do that way so I can organize my coding structure. Thanks by the way.

And also for the final question, IS THAT POSSIBLE?

Body:
What you try to achieve is called method chaining. You can get this by the following:

<?php
class TestClass {
    private $val = '';

    public function test1($val) {
        $this->val = $val;
        return $this;
    }
    public function test2() {
        echo 'Hello '.$this->val;
    }
}

$test->test1('World')->test2(); // Hello World

You have simply to return the instance of the object on the method to allow the method chaining.


问:
Shortcut key for context-sensitive help in Intellij Idea (coding in Java)
Isn't there some shortcut that takes you to context specific help?
For example, if I have my cursor on System.out.println, isn't there some shortcut key I press that takes me to the documentation on this particular method or class where the method is declared?</p>

答: Just to add an answer for the Mac users out there try using F1 for Quick Documentation.</p>


问:
Pandas fillna on a multiindex series
The series_A with NAs is indexed by a MultiIndex (X, Y), while the values to fill in are in the Series_B, which is indexed by X. How to effectively approach this kind of problem?

For example, here is the series_A:

```<code>bar  one    0.299368
     two         NaN
baz  one   -0.863838
     two   -0.251905
foo  one    1.063327
     two         NaN
qux  one    0.206053
     two    0.408204
</code>```

and series_B contains values to fill in:

```<code>bar  0.123
foo  0.456
</code>```

答:
Method 1

use unstack to put first level of index into columns and then use fillna

```<code>series_A.unstack(0).fillna(series_B).unstack().dropna()

bar  one    0.299368
     two    0.123000
baz  one   -0.863838
     two   -0.251905
foo  one    1.063327
     two    0.456000
qux  one    0.206053
quz  two    0.408204
dtype: float64
</code>```

Method 2

use add method to leverage its level and fill_value parameters then combine_first

```<code>series_A.combine_first(series_A.add(series_B, level=0, fill_value=0))

bar  one    0.299368
     two    0.123000
baz  one   -0.863838
     two   -0.251905
foo  one    1.063327
     two    0.456000
qux  one    0.206053
quz  two    0.408204
dtype: float64
</code>```

Method 3

use map on the Index object returned from series_A.index.get_level_vaues(0) with the callable series_B.get

```<code>series_A.fillna(
    pd.Series(series_A.index.get_level_values(0).map(series_B.get), series_A.index)
)

bar  one    0.299368
     two    0.123000
baz  one   -0.863838
     two   -0.251905
foo  one    1.063327
     two    0.456000
qux  one    0.206053
quz  two    0.408204
dtype: float64
</code>```

Method 4

use np.isnan and np.flatnonzero to find the positions of where the np.nans are.  Then find the values to insert with get_level_values and map.  Finally, place into location with iloc

```<code>i = np.flatnonzero(np.isnan(series_A.values))
series_A.iloc[i] = series_A.index.get_level_values(0)[i].map(series_B.get)
series_A

bar  one    0.299368
     two    0.123000
baz  one   -0.863838
     two   -0.251905
foo  one    1.063327
     two    0.456000
qux  one    0.206053
quz  two    0.408204
dtype: float64
</code>```

Title: Pandas fillna on a multiindex series

Body:
The series_A with NAs is indexed by a MultiIndex (X, Y), while the values to fill in are in the Series_B, which is indexed by X. How to effectively approach this kind of problem?

For example, here is the series_A:

bar  one    0.299368
     two         NaN
baz  one   -0.863838
     two   -0.251905
foo  one    1.063327
     two         NaN
qux  one    0.206053
     two    0.408204

and series_B contains values to fill in:

bar  0.123
foo  0.456

Body:
Method 1

use unstack to put first level of index into columns and then use fillna

series_A.unstack(0).fillna(series_B).unstack().dropna()

bar  one    0.299368
     two    0.123000
baz  one   -0.863838
     two   -0.251905
foo  one    1.063327
     two    0.456000
qux  one    0.206053
quz  two    0.408204
dtype: float64

Method 2

use add method to leverage its level and fill_value parameters then combine_first

series_A.combine_first(series_A.add(series_B, level=0, fill_value=0))

bar  one    0.299368
     two    0.123000
baz  one   -0.863838
     two   -0.251905
foo  one    1.063327
     two    0.456000
qux  one    0.206053
quz  two    0.408204
dtype: float64

Method 3

use map on the Index object returned from series_A.index.get_level_vaues(0) with the callable series_B.get

series_A.fillna(
    pd.Series(series_A.index.get_level_values(0).map(series_B.get), series_A.index)
)

bar  one    0.299368
     two    0.123000
baz  one   -0.863838
     two   -0.251905
foo  one    1.063327
     two    0.456000
qux  one    0.206053
quz  two    0.408204
dtype: float64

Method 4

use np.isnan and np.flatnonzero to find the positions of where the np.nans are.  Then find the values to insert with get_level_values and map.  Finally, place into location with iloc

i = np.flatnonzero(np.isnan(series_A.values))
series_A.iloc[i] = series_A.index.get_level_values(0)[i].map(series_B.get)
series_A

bar  one    0.299368
     two    0.123000
baz  one   -0.863838
     two   -0.251905
foo  one    1.063327
     two    0.456000
qux  one    0.206053
quz  two    0.408204
dtype: float64


问:
Loop over checkboxes in PHP
I have a checkbox in each table row, and I would like to press the "Save" which will loop over each checkbox:
(if checked)-> enter to database that this student has attended
else ->enter to database that this student has not attended.

My PHP code:

```<code><table border="1" cellpadding="1" width="550px" style="text-align:center;">
    <th> Student ID </th>
    <th> First Name </th>
    <th> Last Name </th>
    <th> Class ID </th>
    <th> Attended </th>
<?php
    $classid = $_GET['classid'];

    $mysql_host='localhost';
    $mysql_user='root';
    $mysql_password='';
    $con = @mysqli_connect($mysql_host,$mysql_user,$mysql_password);

    if(!$con){
        die('Failed to connect to the database');//if not successful
    }else{
        //echo "Successfully connected to MySQL!";//if successful
        if(@mysqli_select_db($con, 'application_database')){//selecting the database
            //echo '<br>'."Connected to the specified database!";
        }else{
            die('<br>'."Could not connect to the specified database!");
        }
    }

    $sql="SELECT * FROM `student` WHERE class = '$classid'";
    $records=mysqli_query($con,$sql);

    while($student=mysqli_fetch_assoc($records)){

        echo "<tr>";
        echo "<td>".$student['id']."</td>";
        echo "<td>".$student['first_name']."</td>";
        echo "<td>".$student['last_name']."</td>";
        echo "<td>".$student['class']."</td>";
        echo "<td>".'<input type="checkbox" name="attendedCB">'."</td>";
    }

    echo '<form>';
    echo 'Teacher ID: <input type="number" name=teacher_id>';
    echo '<button name="save" type="submit">Save Attendance</button>';
    echo '</form>';

?>
</table>
</code>```

I have a "student_attendance" table in the db, so I want to add each student along with his/her "attended" checkbox status. Cheers :D

答:
```<code>// loop per student
foreach ($_POST ['student'] as $student ) {
    extract($student) // extract array (lazy)
    // if they attended
    if ( !empty ($attendedCB )) {
        // add them
        $query = "INSERT INTO your_table id,first,last,class,attendedCB VALUES($id, $first, $last, $attendedCB)";
        // then run that query or aggregate them all into one big one and run it
    }
}
</code>```

Also, change the checkbox name to student['attendedCB'] and this should work.

Title: Loop over checkboxes in PHP

Body:
I have a checkbox in each table row, and I would like to press the "Save" which will loop over each checkbox:
(if checked)-> enter to database that this student has attended
else ->enter to database that this student has not attended.

My PHP code:

     Student ID
     First Name
     Last Name
     Class ID
     Attended
<?php
    $classid = $_GET['classid'];

    $mysql_host='localhost';
    $mysql_user='root';
    $mysql_password='';
    $con = @mysqli_connect($mysql_host,$mysql_user,$mysql_password);

    if(!$con){
        die('Failed to connect to the database');//if not successful
    }else{
        //echo "Successfully connected to MySQL!";//if successful
        if(@mysqli_select_db($con, 'application_database')){//selecting the database
            //echo '
'."Connected to the specified database!";
        }else{
            die('
'."Could not connect to the specified database!");
        }
    }

    $sql="SELECT * FROM `student` WHERE class = '$classid'";
    $records=mysqli_query($con,$sql);

    while($student=mysqli_fetch_assoc($records)){

        echo "
";
        echo "".$student['id']."	";
        echo "".$student['first_name']."	";
        echo "".$student['last_name']."	";
        echo "".$student['class']."	";
        echo "".'<input type="checkbox" name="attendedCB">'."	";
    }

    echo '<form>';
    echo 'Teacher ID: <input type="number" name=teacher_id>';
    echo '<button name="save" type="submit">Save Attendance</button>';
    echo '</form>';

?>

I have a "student_attendance" table in the db, so I want to add each student along with his/her "attended" checkbox status. Cheers :D

Body:
// loop per student
foreach ($_POST ['student'] as $student ) {
    extract($student) // extract array (lazy)
    // if they attended
    if ( !empty ($attendedCB )) {
        // add them
        $query = "INSERT INTO your_table id,first,last,class,attendedCB VALUES($id, $first, $last, $attendedCB)";
        // then run that query or aggregate them all into one big one and run it
    }
}

Also, change the checkbox name to student['attendedCB'] and this should work.


问:
brew install npm "npm: command not found"
I've installed node using brew install node and when I use the node -v I get following v5.0.0. However when I try to run the npm command I get npm: command not found.

I've tried to run brew install npm, however I just got following response node-5.0.0 already installed.

It happened with node also returning command not found, but that I fixed by running brew link node, however npm still does not seem to work.

How can I resolve this problem?

答:
Try the following:

$ brew update

$ brew uninstall node

$ brew install node

$ sudo chown -R YourLocalUserName /usr/local/lib/node_modules/

$ brew postinstall node

ContentLicense: CC BY-SA 4.0


问:
Can a rake task be triggered via a rails interface?
Or am I thinking about this wrong?  Basically, I want to be able to upload a zip file to a model, and after uploading I want to run a bunch of processes on it.  It would be nice to be able to do this from the back end/console, as well as have a way of triggering the actions via the rails front-end interface.

The idea here:

Gallery has collection.zip

Gallery has many children :item

collection.zip has information for each Item

I want to trigger a batch gallery.items.build process that will extract the information from the zip and use it to create the new items.  I thought about using a Paperclip::Processor for this task, but I have yet to find a lot of truly useful or comprehensive documentation on how that would work, and experimentation has only led to frustration and confusion.  I saw some people use rake tasks for this sort of thing, but I really don't want to have to use the console to do perform the task, and would really just like to have a button that says "Generate Gallery" that will run all the necessary tasks.

So, is there a way of doing this?  Would this be considered bad practice?  If so, is there another way that I should be approaching this problem?

答:
delayed_job or resque are considered to be the best practices for background processing, rather than running a rake task.

The central idea behind both:

Batch scripts or code that needs to be run in background is kept in lib.

Jobs are serialized and stored to DB (or any persistence layer or queue that is supported. eg. Redis or Starling) during the request cycle.

Daemon that runs in background, will look for jobs in the queue and process them in various orders (say, priority or fifo etc)

ContentLicense: CC BY-SA 2.5


答:
You can read more here.

It's method chaining.

See code below:

```<code>class T {
    public function test() {
        // do something

        return $this;
    }
}

$x = new T;
$x->test()->test();
</code>```

Title: PHP Classes function inside function?

Body:
You can read more here.

It's method chaining.

See code below:

class T {
    public function test() {
        // do something

        return $this;
    }
}

$x = new T;
$x->test()->test();


问:
Does page visibility API runs way before before anything else in script
The below code gives output as

should have been called first >>  false

hidden.. stop running expensive task

It seems first time its running in sequence for further page reload it somehow caching the eventlistener I guess.. and giving below output.

hidden.. stop running expensive task

should have been called first >>  false

```<code>console.warn("should have been called first >> "+ document.hidden);

/* event handlers */
document.addEventListener('visibilitychange', function () {
   if (document.hidden) {
    console.log("hidden.. stop running expensive task")
   } else {
    console.log("not hidden.. page has focus, begin running task")
   }
});
</code>```

2 questions:

So does this mean the eventlistener gets attached first before anything else.

Why first time document.hidden is false?

I am not able to find much about this behavior.

<!DOCTYPE html>

Just create a html page with this code.
Open browser console. You'll see the console statements in sequesnce.
Now if you reload this html page, the statements are out of sequence.
Somehow event callback is called first before console statement "should have been called first"

```

Just create a html page with above snippet code.
Open browser console. You'll see the console statements in sequesnce.
Now if you reload this html page, the statements are out of sequence.
Somehow event callback is called first before console statement "should have been called first"

答:
I was not able to really confirm this, but I strongly suspect this is caused by the interaction between the console and the page loading process. If you look closely, you will find that the navigation is executed before the new Document object is created. If you assume

the old document exists until it is replaced

the console is cleared when the page is navigated

then the logged message is a residue from the old document, displayed within the new console log.

Try to give document an arbitrary property:

```<code>console.log("should have been called first, extra >>", document.extra);
function toggleTask () {
   var msg;
   if (document.hidden) {
      msg = "hidden.. stop running expensive task";
   } else {
      msg = "not hidden.. page has focus, begin running task";
   }
   console.log(msg + ", extra >>", document.extra);
}
document.addEventListener('visibilitychange', toggleTask);
window.addEventListener("unload", function () {
  console.log("called last, extra >>", document.extra);
});
document.extra = true;
</code>```

The first navigation to the page logs

should have been called first, extra >> undefined

I could not reproduce the second line you get on the first page load.

The reload action adds

hidden.. stop running expensive task, extra >> true

  called last, extra >> true

  should have been called first, extra >> undefined

The first two lines are also shown for the next page if you navigate away from the page. (in Chrome also by a History:Back action, in FF only for a true fresh page load)

It becomes clear that the call to the visibilitychange event listener happens within the context of the old document, but that it is replaced only afterwards with a new Document object.

As a mitigation, you could remove the event listener before the page unload:

```<code>window.addEventListener("beforeunload", function () {
  document.removeEventListener('visibilitychange', toggleTask);
});
</code>```

Body:
The below code gives output as

should have been called first >>  false

hidden.. stop running expensive task

It seems first time its running in sequence for further page reload it somehow caching the eventlistener I guess.. and giving below output.

hidden.. stop running expensive task

should have been called first >>  false

console.warn("should have been called first >> "+ document.hidden);

/* event handlers */
document.addEventListener('visibilitychange', function () {
   if (document.hidden) {
    console.log("hidden.. stop running expensive task")
   } else {
    console.log("not hidden.. page has focus, begin running task")
   }
});

2 questions:

So does this mean the eventlistener gets attached first before anything else.

Why first time document.hidden is false?

I am not able to find much about this behavior.

<!DOCTYPE html>

Just create a html page with this code.
Open browser console. You'll see the console statements in sequesnce.
Now if you reload this html page, the statements are out of sequence.
Somehow event callback is called first before console statement "should have been called first"

Just create a html page with above snippet code.
Open browser console. You'll see the console statements in sequesnce.
Now if you reload this html page, the statements are out of sequence.
Somehow event callback is called first before console statement "should have been called first"

Body:
I was not able to really confirm this, but I strongly suspect this is caused by the interaction between the console and the page loading process. If you look closely, you will find that the navigation is executed before the new Document object is created. If you assume

the old document exists until it is replaced

the console is cleared when the page is navigated

then the logged message is a residue from the old document, displayed within the new console log.

Try to give document an arbitrary property:

console.log("should have been called first, extra >>", document.extra);
function toggleTask () {
   var msg;
   if (document.hidden) {
      msg = "hidden.. stop running expensive task";
   } else {
      msg = "not hidden.. page has focus, begin running task";
   }
   console.log(msg + ", extra >>", document.extra);
}
document.addEventListener('visibilitychange', toggleTask);
window.addEventListener("unload", function () {
  console.log("called last, extra >>", document.extra);
});
document.extra = true;

The first navigation to the page logs

should have been called first, extra >> undefined

I could not reproduce the second line you get on the first page load.

The reload action adds

hidden.. stop running expensive task, extra >> true

  called last, extra >> true

  should have been called first, extra >> undefined

The first two lines are also shown for the next page if you navigate away from the page. (in Chrome also by a History:Back action, in FF only for a true fresh page load)

It becomes clear that the call to the visibilitychange event listener happens within the context of the old document, but that it is replaced only afterwards with a new Document object.

As a mitigation, you could remove the event listener before the page unload:

window.addEventListener("beforeunload", function () {
  document.removeEventListener('visibilitychange', toggleTask);
});