问:
vercel deployment gives Error: Command "npm run build" exited with 1
I'm trying to deploy a github on vercel and get this error, (not sure what more details I should be giving), in this case I'm simply coping a working repo and loading it to vercel. here is the github. I tried building it on the computer and it worked fine, not sure what exactly I need to change for it to work on Vercel.</p>
```<code> Cloning github.com/gituser/git (Branch: main, Commit: f2fb480)
    Cloning completed: 1.530s
    Analyzing source code...
    Installing build runtime...
    Build runtime installed: 3.372s
    Looking up build cache...
    Build Cache not found
    Detected package.json
    Installing dependencies...
    npm WARN deprecated babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.
    npm WARN deprecated source-map-resolve@0.6.0: See https://github.com/lydell/source-map-resolve#deprecated
    npm WARN deprecated ethereumjs-tx@1.3.7: New package name format for new versions: @ethereumjs/tx. Please update.
    npm WARN deprecated eth-sig-util@1.4.2: Deprecated in favor of '@metamask/eth-sig-util'
    npm WARN deprecated ethereumjs-vm@2.6.0: New package name format for new versions: @ethereumjs/vm. Please update.
    npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
    npm WARN deprecated ethereumjs-block@1.7.1: New package name format for new versions: @ethereumjs/block. Please update.
    npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
    npm WARN deprecated @walletconnect/mobile-registry@1.4.0: Deprecated in favor of dynamic registry available from: https://github.com/walletconnect/walletconnect-registry
    npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
    npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
    npm WARN deprecated safe-event-emitter@1.0.1: Renamed to @metamask/safe-event-emitter
    npm WARN deprecated ethereumjs-block@2.2.2: New package name format for new versions: @ethereumjs/block. Please update.
    npm WARN deprecated ethereumjs-common@1.5.2: New package name format for new versions: @ethereumjs/common. Please update.
    npm WARN deprecated har-validator@5.1.5: this library is no longer supported
    npm WARN deprecated svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x.
    npm WARN deprecated querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
    npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
    npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
    npm WARN deprecated @hapi/joi@15.1.1: Switch to 'npm install joi'
    npm WARN deprecated rollup-plugin-babel@4.4.0: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-babel.
    npm WARN deprecated ethereumjs-tx@2.1.2: New package name format for new versions: @ethereumjs/tx. Please update.
    npm WARN deprecated mkdirp-promise@5.0.1: This package is broken and no longer maintained. 'mkdirp' itself supports promises now, please switch to that.
    npm WARN deprecated uuid@3.3.2: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
    npm WARN deprecated sane@4.1.0: some dependency vulnerabilities fixed, support for node < 10 dropped, and newer ECMAScript syntax/features added
    npm WARN deprecated flatten@1.0.3: flatten is deprecated in favor of utility frameworks such as lodash.
    npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
    npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
    npm WARN deprecated @hapi/address@2.1.4: Moved to 'npm install @sideway/address'
    npm WARN deprecated @hapi/topo@3.1.6: This version has been deprecated and is no longer supported or maintained
    npm WARN deprecated @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained
    npm WARN deprecated @hapi/bourne@1.3.2: This version has been deprecated and is no longer supported or maintained
    npm WARN deprecated multicodec@0.5.7: This module has been superseded by the multiformats module
    npm WARN deprecated cids@0.7.5: This module has been superseded by the multiformats module
    npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
    npm WARN deprecated multibase@0.7.0: This module has been superseded by the multiformats module
    npm WARN deprecated multibase@0.6.1: This module has been superseded by the multiformats module
    npm WARN deprecated multicodec@1.0.4: This module has been superseded by the multiformats module
    npm WARN deprecated core-js@2.6.12: core-js@<3.4 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual version of core-js.
    > yarn@1.22.17 preinstall /vercel/path0/node_modules/yarn
    > :; (node ./preinstall.js > /dev/null 2>&1 || true)
    > bufferutil@4.0.6 install /vercel/path0/node_modules/bufferutil
    > node-gyp-build
    > secp256k1@4.0.3 install /vercel/path0/node_modules/secp256k1
    > node-gyp-build || exit 0
    > utf-8-validate@5.0.8 install /vercel/path0/node_modules/utf-8-validate
    > node-gyp-build
    > node-gyp-build || exit 0
    > core-js@2.6.12 postinstall /vercel/path0/node_modules/babel-runtime/node_modules/core-js
    > node -e "try{require('./postinstall')}catch(e){}"
    > core-js@3.20.3 postinstall /vercel/path0/node_modules/core-js
    > node -e "try{require('./postinstall')}catch(e){}"
    > core-js-pure@3.20.3 postinstall /vercel/path0/node_modules/core-js-pure
    > node -e "try{require('./postinstall')}catch(e){}"
    > ejs@2.7.4 postinstall /vercel/path0/node_modules/ejs
    > node ./postinstall.js
    > web3-shh@1.7.0 postinstall /vercel/path0/node_modules/web3-shh
    > echo "WARNING: the web3-shh api will be deprecated in the next version"
    WARNING: the web3-shh api will be deprecated in the next version
    > web3-bzz@1.7.0 postinstall /vercel/path0/node_modules/web3-bzz
    > echo "WARNING: the web3-bzz api will be deprecated in the next version"
    WARNING: the web3-bzz api will be deprecated in the next version
    > web3@1.7.0 postinstall /vercel/path0/node_modules/web3
    > echo "WARNING: the web3-shh and web3-bzz api will be deprecated in the next version"
    WARNING: the web3-shh and web3-bzz api will be deprecated in the next version
    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^2.1.3 (node_modules/react-scripts/node_modules/fsevents):
    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules/watchpack-chokidar2/node_modules/chokidar/node_modules/fsevents):
    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules/webpack-dev-server/node_modules/chokidar/node_modules/fsevents):
    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
    npm WARN react-moralis@0.3.11 requires a peer of moralis@>=0.0.176 but none is installed. You must install peer dependencies yourself.
    npm WARN react-polls@1.2.0 requires a peer of react@^15.0.0 || ^16.0.0 but none is installed. You must install peer dependencies yourself.
    npm WARN react-polls@1.2.0 requires a peer of react-dom@^15.0.0 || ^16.0.0 but none is installed. You must install peer dependencies yourself.
    npm WARN @babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.16.7 requires a peer of @babel/core@^7.13.0 but none is installed. You must install peer dependencies yourself.
    npm WARN tsutils@3.21.0 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
    added 2289 packages from 1041 contributors in 92.876s
    195 packages are looking for funding
      run `npm fund` for details
    Running "npm run build"
    > ethereum-boilerplate@0.1.0 build /vercel/path0
    > react-scripts build
    Creating an optimized production build...
    Treating warnings as errors because process.env.CI = true.
    Most CI servers set it automatically.
    Failed to compile.
    src/components/Polls.js
      Line 36:5:   'getBalance' is assigned a value but never used                                                              no-unused-vars
      Line 38:5:   'nativeToken' is assigned a value but never used                                                             no-unused-vars
      Line 39:5:   'isLoading' is assigned a value but never used                                                               no-unused-vars
      Line 41:11:  'isSaving' is assigned a value but never used                                                                no-unused-vars
      Line 41:21:  'error' is assigned a value but never used                                                                   no-unused-vars
      Line 41:28:  'save' is assigned a value but never used                                                                    no-unused-vars
      Line 41:34:  'object' is assigned a value but never used                                                                  no-unused-vars
      Line 47:9:   'updatePoll' is assigned a value but never used                                                              no-unused-vars
      Line 98:6:   React Hook useEffect has a missing dependency: 'checkReg'. Either include it or remove the dependency array  react-hooks/exhaustive-deps
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! ethereum-boilerplate@0.1.0 build: `react-scripts build`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the ethereum-boilerplate@0.1.0 build script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /vercel/.npm/_logs/2022-01-24T17_19_29_533Z-debug.log
    Error: Command "npm run build" exited with 1
</code>```

答: Setting the value of CI environment variable to false solved my problem.</p>

Body:
I'm trying to deploy a github on vercel and get this error, (not sure what more details I should be giving), in this case I'm simply coping a working repo and loading it to vercel. here is the github. I tried building it on the computer and it worked fine, not sure what exactly I need to change for it to work on Vercel.

 Cloning github.com/gituser/git (Branch: main, Commit: f2fb480)
    Cloning completed: 1.530s
    Analyzing source code...
    Installing build runtime...
    Build runtime installed: 3.372s
    Looking up build cache...
    Build Cache not found
    Detected package.json
    Installing dependencies...
    npm WARN deprecated babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.
    npm WARN deprecated source-map-resolve@0.6.0: See https://github.com/lydell/source-map-resolve#deprecated
    npm WARN deprecated ethereumjs-tx@1.3.7: New package name format for new versions: @ethereumjs/tx. Please update.
    npm WARN deprecated eth-sig-util@1.4.2: Deprecated in favor of '@metamask/eth-sig-util'
    npm WARN deprecated ethereumjs-vm@2.6.0: New package name format for new versions: @ethereumjs/vm. Please update.
    npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
    npm WARN deprecated ethereumjs-block@1.7.1: New package name format for new versions: @ethereumjs/block. Please update.
    npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
    npm WARN deprecated @walletconnect/mobile-registry@1.4.0: Deprecated in favor of dynamic registry available from: https://github.com/walletconnect/walletconnect-registry
    npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
    npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
    npm WARN deprecated safe-event-emitter@1.0.1: Renamed to @metamask/safe-event-emitter
    npm WARN deprecated ethereumjs-block@2.2.2: New package name format for new versions: @ethereumjs/block. Please update.
    npm WARN deprecated ethereumjs-common@1.5.2: New package name format for new versions: @ethereumjs/common. Please update.
    npm WARN deprecated har-validator@5.1.5: this library is no longer supported
    npm WARN deprecated svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x.
    npm WARN deprecated querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
    npm WARN deprecated fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
    npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
    npm WARN deprecated @hapi/joi@15.1.1: Switch to 'npm install joi'
    npm WARN deprecated rollup-plugin-babel@4.4.0: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-babel.
    npm WARN deprecated ethereumjs-tx@2.1.2: New package name format for new versions: @ethereumjs/tx. Please update.
    npm WARN deprecated mkdirp-promise@5.0.1: This package is broken and no longer maintained. 'mkdirp' itself supports promises now, please switch to that.
    npm WARN deprecated uuid@3.3.2: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
    npm WARN deprecated sane@4.1.0: some dependency vulnerabilities fixed, support for node < 10 dropped, and newer ECMAScript syntax/features added
    npm WARN deprecated flatten@1.0.3: flatten is deprecated in favor of utility frameworks such as lodash.
    npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
    npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
    npm WARN deprecated @hapi/address@2.1.4: Moved to 'npm install @sideway/address'
    npm WARN deprecated @hapi/topo@3.1.6: This version has been deprecated and is no longer supported or maintained
    npm WARN deprecated @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained
    npm WARN deprecated @hapi/bourne@1.3.2: This version has been deprecated and is no longer supported or maintained
    npm WARN deprecated multicodec@0.5.7: This module has been superseded by the multiformats module
    npm WARN deprecated cids@0.7.5: This module has been superseded by the multiformats module
    npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
    npm WARN deprecated multibase@0.7.0: This module has been superseded by the multiformats module
    npm WARN deprecated multibase@0.6.1: This module has been superseded by the multiformats module
    npm WARN deprecated multicodec@1.0.4: This module has been superseded by the multiformats module
    npm WARN deprecated core-js@2.6.12: core-js@<3.4 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Please, upgrade your dependencies to the actual version of core-js.
    > yarn@1.22.17 preinstall /vercel/path0/node_modules/yarn
    > :; (node ./preinstall.js > /dev/null 2>&1 || true)
    > bufferutil@4.0.6 install /vercel/path0/node_modules/bufferutil
    > node-gyp-build
    > secp256k1@4.0.3 install /vercel/path0/node_modules/secp256k1
    > node-gyp-build || exit 0
    > utf-8-validate@5.0.8 install /vercel/path0/node_modules/utf-8-validate
    > node-gyp-build
    > node-gyp-build || exit 0
    > core-js@2.6.12 postinstall /vercel/path0/node_modules/babel-runtime/node_modules/core-js
    > node -e "try{require('./postinstall')}catch(e){}"
    > core-js@3.20.3 postinstall /vercel/path0/node_modules/core-js
    > node -e "try{require('./postinstall')}catch(e){}"
    > core-js-pure@3.20.3 postinstall /vercel/path0/node_modules/core-js-pure
    > node -e "try{require('./postinstall')}catch(e){}"
    > ejs@2.7.4 postinstall /vercel/path0/node_modules/ejs
    > node ./postinstall.js
    > web3-shh@1.7.0 postinstall /vercel/path0/node_modules/web3-shh
    > echo "WARNING: the web3-shh api will be deprecated in the next version"
    WARNING: the web3-shh api will be deprecated in the next version
    > web3-bzz@1.7.0 postinstall /vercel/path0/node_modules/web3-bzz
    > echo "WARNING: the web3-bzz api will be deprecated in the next version"
    WARNING: the web3-bzz api will be deprecated in the next version
    > web3@1.7.0 postinstall /vercel/path0/node_modules/web3
    > echo "WARNING: the web3-shh and web3-bzz api will be deprecated in the next version"
    WARNING: the web3-shh and web3-bzz api will be deprecated in the next version
    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^2.1.3 (node_modules/react-scripts/node_modules/fsevents):
    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules/watchpack-chokidar2/node_modules/chokidar/node_modules/fsevents):
    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.2.7 (node_modules/webpack-dev-server/node_modules/chokidar/node_modules/fsevents):
    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
    npm WARN react-moralis@0.3.11 requires a peer of moralis@>=0.0.176 but none is installed. You must install peer dependencies yourself.
    npm WARN react-polls@1.2.0 requires a peer of react@^15.0.0 || ^16.0.0 but none is installed. You must install peer dependencies yourself.
    npm WARN react-polls@1.2.0 requires a peer of react-dom@^15.0.0 || ^16.0.0 but none is installed. You must install peer dependencies yourself.
    npm WARN @babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.16.7 requires a peer of @babel/core@^7.13.0 but none is installed. You must install peer dependencies yourself.
    npm WARN tsutils@3.21.0 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
    added 2289 packages from 1041 contributors in 92.876s
    195 packages are looking for funding
      run `npm fund` for details
    Running "npm run build"
    > ethereum-boilerplate@0.1.0 build /vercel/path0
    > react-scripts build
    Creating an optimized production build...
    Treating warnings as errors because process.env.CI = true.
    Most CI servers set it automatically.
    Failed to compile.
    src/components/Polls.js
      Line 36:5:   'getBalance' is assigned a value but never used                                                              no-unused-vars
      Line 38:5:   'nativeToken' is assigned a value but never used                                                             no-unused-vars
      Line 39:5:   'isLoading' is assigned a value but never used                                                               no-unused-vars
      Line 41:11:  'isSaving' is assigned a value but never used                                                                no-unused-vars
      Line 41:21:  'error' is assigned a value but never used                                                                   no-unused-vars
      Line 41:28:  'save' is assigned a value but never used                                                                    no-unused-vars
      Line 41:34:  'object' is assigned a value but never used                                                                  no-unused-vars
      Line 47:9:   'updatePoll' is assigned a value but never used                                                              no-unused-vars
      Line 98:6:   React Hook useEffect has a missing dependency: 'checkReg'. Either include it or remove the dependency array  react-hooks/exhaustive-deps
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! ethereum-boilerplate@0.1.0 build: `react-scripts build`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the ethereum-boilerplate@0.1.0 build script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /vercel/.npm/_logs/2022-01-24T17_19_29_533Z-debug.log
    Error: Command "npm run build" exited with 1


来源: stackexchange

问:
How to inject a variable placeholder `${}` in the spring gateway filters configuration?
How to inject a variable placeholder ${} in the spring gateway filters configuration?

```<code>foo:
  bar:
    uri: /coucou

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=$\\{foo.bar.uri}
</code>```

NB:

I've tried $\{foo.bar.uri} and ${foo.bar.uri}

I know it's doable programmatically

答:
As @spencergibb highlighted, it's working by using args subproperty:

```<code>   filters:
    - name: PrefixPath
      args:
        prefix: ${foo.bar.uri}
</code>```

see gist.github.com/spencergibb/873f239529f79cb784d4eab3a9ddc4a6

ContentLicense: CC BY-SA 4.0

Body:
How to inject a variable placeholder ${} in the spring gateway filters configuration?

foo:
  bar:
    uri: /coucou

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - PrefixPath=$\\{foo.bar.uri}

NB:

I've tried $\{foo.bar.uri} and ${foo.bar.uri}

I know it's doable programmatically

Body:
As @spencergibb highlighted, it's working by using args subproperty:

   filters:
    - name: PrefixPath
      args:
        prefix: ${foo.bar.uri}

see gist.github.com/spencergibb/873f239529f79cb784d4eab3a9ddc4a6


问:
ERROR 2003 (HY000): Can't connect to MySQL server on localhost (10061)
I installed  MySQL on Microsoft Windows 8 Using a noinstall Zip Archive. But when I tested by executing the following commands on windows prompt, the above error showed up.</p>
```<code>C:\> "C:\MySQL\bin\mysqlshow"

C:\> "C:\MySQL\bin\mysql" test
</code>```

答:
Go and search Services in Windows

Now search Mysql. Right Click on it. By Default it's startup type will be 'Automatic'. Click on Properties on right clicked menu.
You will find startup type Switch it to -> Manual So that We can start and stop by our choice.

Now Get Back and Right Click to Mysql on Services and Click Start.

Now Mysql has started successfully

To get started
Start Mysql Shell
& type command

```<code>shell.connect({host: 'localhost',user: 'root'})
</code>```

Now type password

To type sql commands:-

```<code>/sql
</code>```

Body:
I installed  MySQL on Microsoft Windows 8 Using a noinstall Zip Archive. But when I tested by executing the following commands on windows prompt, the above error showed up.

C:\> "C:\MySQL\bin\mysqlshow"

C:\> "C:\MySQL\bin\mysql" test

Body:
Go and search Services in Windows

Now search Mysql. Right Click on it. By Default it's startup type will be 'Automatic'. Click on Properties on right clicked menu.
You will find startup type Switch it to -> Manual So that We can start and stop by our choice.

Now Get Back and Right Click to Mysql on Services and Click Start.

Now Mysql has started successfully

To get started
Start Mysql Shell
& type command

shell.connect({host: 'localhost',user: 'root'})

Now type password

To type sql commands:-

/sql


问:
can i add an extra public method in singleton class in java
I have a singleton class and I added the msg method but I'm not sure if is okay to add it to the singleton class or not</p>
```<code>public class Singleton {
    private static Singleton single_instance = null;
    private Singleton() {

    }

    public void msg(String msg){
        System.out.println(msg);
    }

    public static Singleton getInstance() {
        if (single_instance == null) {
            single_instance = new Singleton();
        }

        return single_instance;
    }
}
</code>```

答:
Singleton is a Creational Design Pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Aside from that, it is just an ordinary class that can have as many public methods as will need to satisfy the requirements for which it was designed.

Singleton objects can mutate (change the value of its internal attributes - variables), or can be immutable (for example, Java enums can be used to create Singleton instances).

Using your class as an example, you can do something like this and be perfectly legal:

```<code>public class Singleton {
    private static Singleton single_instance = null;
    private String message = "none";
    private Singleton() {

    }

    public void showCurrentMessage(){
        System.out.println(msg);
    }
    public void updateMessage(String msg) {
        this.msg = msg;
    }

    public static Singleton getInstance() {
        if (single_instance == null) {
            single_instance = new Singleton();
        }

        return single_instance;
    }
}
</code>```

Mind you that we are strictly speaking of the legality of this approach. Another discussion to be had is regarding the practicality of the approach where you need to consider many things like:

Testability of the code - one of the reasons why Singleton are not liked very much

Usability in multithreaded applications - Many safeguards are needed when objects mutate in multithreaded context.

There could be many others; albeit some of those (if not all) apply to non-Singleton objects as well.

Body:
I have a singleton class and I added the msg method but I'm not sure if is okay to add it to the singleton class or not

public class Singleton {
    private static Singleton single_instance = null;
    private Singleton() {

    }

    public void msg(String msg){
        System.out.println(msg);
    }

    public static Singleton getInstance() {
        if (single_instance == null) {
            single_instance = new Singleton();
        }

        return single_instance;
    }
}

Body:
Singleton is a Creational Design Pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Aside from that, it is just an ordinary class that can have as many public methods as will need to satisfy the requirements for which it was designed.

Singleton objects can mutate (change the value of its internal attributes - variables), or can be immutable (for example, Java enums can be used to create Singleton instances).

Using your class as an example, you can do something like this and be perfectly legal:

public class Singleton {
    private static Singleton single_instance = null;
    private String message = "none";
    private Singleton() {

    }

    public void showCurrentMessage(){
        System.out.println(msg);
    }
    public void updateMessage(String msg) {
        this.msg = msg;
    }

    public static Singleton getInstance() {
        if (single_instance == null) {
            single_instance = new Singleton();
        }

        return single_instance;
    }
}

Mind you that we are strictly speaking of the legality of this approach. Another discussion to be had is regarding the practicality of the approach where you need to consider many things like:

Testability of the code - one of the reasons why Singleton are not liked very much

Usability in multithreaded applications - Many safeguards are needed when objects mutate in multithreaded context.

There could be many others; albeit some of those (if not all) apply to non-Singleton objects as well.


问:
Smarty - foreach stops while reaching a limit
i have a smarty foreach loop over a list of elements. this loop must stop when it complete 10 iteration, ie foreach must end at the 10th element of list.</p>
```<code>{foreach $b_list as $list}
     <label>{$list['firstname']}</label>
{/foreach}
</code>```

答:
```<code>{foreach $b_list as $list name=list10}
    {if $smarty.foreach.list10.index == 10}
        {break}
    {/if}
    <label>{$list['firstname']}</label>
{/foreach}
</code>```

Body:
i have a smarty foreach loop over a list of elements. this loop must stop when it complete 10 iteration, ie foreach must end at the 10th element of list.

{foreach $b_list as $list}
     {$list['firstname']}
{/foreach}


问:
Unexpected Token - Java Enum
Is there any option in java to Create an enum with true and false like below,

```<code>public enum options {
true,
false,
both
}
</code>```

Now getting unexpected token error as I am using true and false. thank you

Regards
haru

答:
No. From JLS 8.9.1, an enum constant is defined in the syntax to be

```<code>EnumConstant:
    {EnumConstantModifier} Identifier [( [ArgumentList] )] [ClassBody]
</code>```

So it's an Identifier. And from JLS 3.8, and Identifier is defined to be

```<code>Identifier:
    IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral
</code>```

Hence, an identifier is any valid string of identifier characters (basically letters and numbers, but with Unicode support thrown in) that is not a keyword (like if) or the words true, false, or null.

Realistically, you should be capitalizing your enum names anyway, so it would look more like

```<code>public enum Options {
  TRUE, FALSE, BOTH
}
</code>```

which poses no issues as TRUE and FALSE aren't Boolean literals in Java.

Title: Unexpected Token - Java Enum

Body:
Is there any option in java to Create an enum with true and false like below,

public enum options {
true,
false,
both
}

Now getting unexpected token error as I am using true and false. thank you

Regards
haru

Body:
No. From JLS 8.9.1, an enum constant is defined in the syntax to be

EnumConstant:
    {EnumConstantModifier} Identifier [( [ArgumentList] )] [ClassBody]

So it's an Identifier. And from JLS 3.8, and Identifier is defined to be

Identifier:
    IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral

Hence, an identifier is any valid string of identifier characters (basically letters and numbers, but with Unicode support thrown in) that is not a keyword (like if) or the words true, false, or null.

Realistically, you should be capitalizing your enum names anyway, so it would look more like

public enum Options {
  TRUE, FALSE, BOTH
}

which poses no issues as TRUE and FALSE aren't Boolean literals in Java.


问:
Cypress how to use api key in put/post request?
I am trying to use AWS API and its API-key in POST/PUT call in Cypress, couldn't find enough details, can someone please help?</p>

答: I was able to resovle it syntax is: authorization : key + value no quotes –</p>


问:
Unable to upload file from react to laravel using react hook form and ajax
Up to this point a file can be viewed on input:

```<code>export async function store(input) {
    console.log("input", input);
    return httpClient.post(`${apiEndpoint}`, input);
}
</code>```

On above console.log, it shows data as:

But, on the serverside laravel, if I print_r($request->all()) it shows data as:

My http client looks like this:

```<code>import axios from "axios";

const apiURL = process.env.MIX_SPA_URL;

axios.defaults.headers.common["Content-Type"] = "application/json";
axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";

axios.defaults.withCredentials = true;

let client = axios.create({
    baseURL: apiURL,
});

axios.interceptors.response.use(null, (error) => {
    const expectedError =
        error.response &&
        error.response.status >= 400 &&
        error.response.status < 500;

    if (!expectedError) {
        console.log("error from httpClient >>", error);
    }

    return Promise.reject(error);
});

function setJwt(token) {
    client.defaults.headers.common["Authorization"] = "Bearer " + token;
}

const httpClient = {
    get: client.get,
    post: client.post,
    put: client.put,
    delete: client.delete,
    setJwt,
};

export default httpClient;
</code>```

Also, in case if you want to look how I have created input file using react-hook-form as:

```<code><input
    className={`form-control w-full ${
        errors["cover_image"] ? "border-red-500" : ""
    }`}
    type="file"
    {...register("cover_image")}
/>
</code>```

Why are the images not being sent to the server?

In case of laravel, I am using laravel sanctum in combination with fortify. And, the middleware added for this route are auth:sanctum and verified.

Also, I have tried by adding headers as:  "Content-Type": "multipart/form-data",

```<code>export async function store(input) {
    console.log("input", input);
    return httpClient.post(`${apiEndpoint}`, input, {
        headers: {
            "Content-Type": "multipart/form-data",
        },
    });
}

</code>```

But, with this header, not a single data got send to the server. Here, is the screenshot:

答:
I think you must put your file in formData and then pass it as your post request data

```<code>export async function store(input) {
    const formData = new FormData();
    formData.append("cover_image", input.cover_image[0]);
    formData.append("blockchain", input.blockchain);
    formData.append("description", input.description);
    formData.append("name", input.name);

    return await httpClient.post(`${apiEndpoint}`, formData, {
        headers: {
            "Content-Type": "multipart/form-data",
        },
    });
}

</code>```

Body:
Up to this point a file can be viewed on input:

export async function store(input) {
    console.log("input", input);
    return httpClient.post(`${apiEndpoint}`, input);
}

On above console.log, it shows data as:

But, on the serverside laravel, if I print_r($request->all()) it shows data as:

My http client looks like this:

import axios from "axios";

const apiURL = process.env.MIX_SPA_URL;

axios.defaults.headers.common["Content-Type"] = "application/json";
axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";

axios.defaults.withCredentials = true;

let client = axios.create({
    baseURL: apiURL,
});

axios.interceptors.response.use(null, (error) => {
    const expectedError =
        error.response &&
        error.response.status >= 400 &&
        error.response.status < 500;

    if (!expectedError) {
        console.log("error from httpClient >>", error);
    }

    return Promise.reject(error);
});

function setJwt(token) {
    client.defaults.headers.common["Authorization"] = "Bearer " + token;
}

const httpClient = {
    get: client.get,
    post: client.post,
    put: client.put,
    delete: client.delete,
    setJwt,
};

export default httpClient;

Also, in case if you want to look how I have created input file using react-hook-form as:

<input
    className={`form-control w-full ${
        errors["cover_image"] ? "border-red-500" : ""
    }`}
    type="file"
    {...register("cover_image")}
/>

Why are the images not being sent to the server?

In case of laravel, I am using laravel sanctum in combination with fortify. And, the middleware added for this route are auth:sanctum and verified.

Also, I have tried by adding headers as:  "Content-Type": "multipart/form-data",

export async function store(input) {
    console.log("input", input);
    return httpClient.post(`${apiEndpoint}`, input, {
        headers: {
            "Content-Type": "multipart/form-data",
        },
    });
}

But, with this header, not a single data got send to the server. Here, is the screenshot:

Body:
I think you must put your file in formData and then pass it as your post request data

export async function store(input) {
    const formData = new FormData();
    formData.append("cover_image", input.cover_image[0]);
    formData.append("blockchain", input.blockchain);
    formData.append("description", input.description);
    formData.append("name", input.name);

    return await httpClient.post(`${apiEndpoint}`, formData, {
        headers: {
            "Content-Type": "multipart/form-data",
        },
    });
}


问:
Interfaces vs Types in TypeScript
What is the difference between these statements (interface vs type) in TypeScript?

```<code>interface X {
    a: number
    b: string
}

type X = {
    a: number
    b: string
};
</code>```

答:
Interface was designed specifically to describe object shapes; however Types are somehow like interfaces that can be used to create new name for any type.

We might say that an Interface can be extended by declaring it more than one time; while types are closed.

https://itnext.io/interfaces-vs-types-in-typescript-cf5758211910

Title: Interfaces vs Types in TypeScript

Body:
What is the difference between these statements (interface vs type) in TypeScript?

interface X {
    a: number
    b: string
}

type X = {
    a: number
    b: string
};


问:
Can every recursive process be transformed into an iterative process?
I was reading the book, Structure and Interpretation of Computer Programs, where in it tells about the distinction between a recursive procedure and recursive process, and similarly between iterative procedure and iterative process. So, a recursive procedure could still generate an iterative process.

My question is: given a procedure which generates a recursive process, can you always write another procedure that achieves the same result but generates an iterative process?

The specific problem that I was trying to solve was to write a procedure which does an in-order traversal of a binary search tree but generates an iterative process. I know how you can use a stack to get an iterative procedure for this problem. However, that still generates a recursive process (correct me if I am wrong here).

Thanks,

Abhinav.

答:
Any tail recursive process can be transformed into an iterative one.

But not all recursive processes can be transformed into an iterative one.

ContentLicense: CC BY-SA 3.0


问:
Save user input from a switch-case that is stored in a list (beginner) C#
For each switch loop that is performed, all information that the user has entered is deleted.
The user provides information via case 1 which has the methods: läsPoäng (readPoints) and omvandlaBetyg (convertRate).

How can I proceed to make the loop remember the user's input?

I have different lists that consist of different variables used for my methods.
Comments have been added to give a better explanation.

I appreciate all help I can get.

```<code>    static void Main(string[] args)
    {
        List<string> ämnen = new List<string> { "Matematik", "Svenska", "Engelska", "Historia", "Fysik" };
        List<int> poäng = new List<int>(); // Declaration of list with points
        List<char> betyg = new List<char>(); // Declaration of list with grades

        bool repetera = true;

        do
        {
            Console.WriteLine(" \n========Räkna betyg========");
            Console.WriteLine("1. Skriv in dina poäng");
            Console.WriteLine("2. Skriv ut dina betyg");
            Console.WriteLine("3. Poäng & betyg statistik");
            Console.WriteLine("4. Avsluta");
            Console.WriteLine("==========================");
            Console.Write("Ange ditt alternativ: ");
            int alternativ = Convert.ToInt32(Console.ReadLine());

            switch (alternativ)
            {
                // I want to be able to save the input from the user in case 1
                // so that it can be used in other cases.
                case 1:
                    läsPoäng(ämnen);        // Method that asks for the user to input points for specific courses
                    omvandlaBetyg(poäng);   // Method that converts user input to char "grades"
                    Console.Clear();
                    break;

                case 2:
                    skrivUtBetyg(betyg, ämnen); // Method that show grades for each course
                    break;

                case 3:
                    Statistik(betyg, poäng); // Method that show statistics for the points and grades
                    break;

                case 4:
                    Console.WriteLine("Tack för att du använt programmet 'Räkna betyg'");
                    repetera = false;
                    break;

                default:
                    Console.WriteLine("\nVänligen ange ett alternativ mellan 1-4.\n");
                    break;
            }
        }
        while (true);

    }
    // Method that asks for the user to input points for specific courses
    static List<int> läsPoäng(List<string> ämnen)
    {
        var poäng = new List<int>();

        Console.Write("Ange totalpoäng för matematik:");
        poäng.Add(Convert.ToInt32(Console.ReadLine()));

        Console.Write("Ange totalpoäng för svenska:");
        poäng.Add(Convert.ToInt32(Console.ReadLine()));

        Console.Write("Ange totalpoäng för engelska:");
        poäng.Add(Convert.ToInt32(Console.ReadLine()));

        Console.Write("Ange totalpoäng för historia:");
        poäng.Add(Convert.ToInt32(Console.ReadLine()));

        Console.Write("Ange totalpoäng för fysik:");
        poäng.Add(Convert.ToInt32(Console.ReadLine()));

        return poäng;
    }
    // Method that converts user input to char "grades"
    static List<char> omvandlaBetyg(List<int> poäng)
    {
        List<char> betyg = new List<char>();

        foreach (int i in poäng)
        {
            if (i < 50)
            {
                betyg.Add('F');
            }
            else if (i <= 60)
            {
                betyg.Add('E');
            }
            else if (i < 75)
            {
                betyg.Add('D');
            }
            else if (i < 90)
            {
                betyg.Add('C');
            }
            else if (i < 100)
            {
                betyg.Add('B');
            }
            else
            {
                betyg.Add('A');
            }
        }
        return betyg;
    }
    // Method that show grades for each course
    static void skrivUtBetyg(List<char> betyg, List<string> ämnen)
    {
        // Använder mig utav metoden .Zip för att slå ihop betyget med
        // sitt motsvarande ämne. För att sedan kunna presentera allt
        // i samma linje som visar betyget och ämnet "zippat" till en linje.
        // (Utan denna .Zip lösning så hade man fått göra två separate foreach-loopar
        // som då visar ämnena och betygen separat.
        // Denna lösning fungerar utmärkt för att iterera igenom två listor samtidigt.

        var betygOchÄmnen = betyg.Zip(ämnen, (first, second) => first + "         |" + second);

        Console.WriteLine(" \n_________________________");
        Console.WriteLine("|  Betyg    |   Ämne     ");

        foreach (var item in betygOchÄmnen)
        {
             Console.WriteLine("| " + item);
        }
        Console.WriteLine("_________________________");
    }
    // Method for showing grade and points statistics
    static void Statistik(List<char> betyg, List<int> poäng)
    {
        int betygA = 0;
        int betygC = 0;
        int betygF = 0;
        int totalPoäng = poäng.Sum();

        foreach (var c in betyg)
        {
            if (c == 'A')
            {
                betygA++;
            }
            else if (c == 'C')
            {
                betygC++;
            }
            else if (c == 'F')
            {
                betygF++;
            }
        }

        Console.WriteLine(" \n========================");
        Console.WriteLine("|Antal A betyg: " + betygA + "      |");
        Console.WriteLine("|Antal C betyg: " + betygC + "      |");
        Console.WriteLine("|Antal F betyg: " + betygF + "      |");
        Console.WriteLine("|Antal betygspoäng: " + totalPoäng + "|");
        Console.WriteLine("========================");
    }
}
</code>```

}

答:
The solution has been found.
I had to add a list for the input to be stored into.

As you can see below:

```<code>poäng = läsPoäng(ämnen);
betyg = omvandlaBetyg(poäng);
</code>```

Body:
For each switch loop that is performed, all information that the user has entered is deleted.
The user provides information via case 1 which has the methods: läsPoäng (readPoints) and omvandlaBetyg (convertRate).

How can I proceed to make the loop remember the user's input?

I have different lists that consist of different variables used for my methods.
Comments have been added to give a better explanation.

I appreciate all help I can get.

    static void Main(string[] args)
    {
        List<string> ämnen = new List<string> { "Matematik", "Svenska", "Engelska", "Historia", "Fysik" };
        List<int> poäng = new List<int>(); // Declaration of list with points
        List<char> betyg = new List<char>(); // Declaration of list with grades

        bool repetera = true;

        do
        {
            Console.WriteLine(" \n========Räkna betyg========");
            Console.WriteLine("1. Skriv in dina poäng");
            Console.WriteLine("2. Skriv ut dina betyg");
            Console.WriteLine("3. Poäng & betyg statistik");
            Console.WriteLine("4. Avsluta");
            Console.WriteLine("==========================");
            Console.Write("Ange ditt alternativ: ");
            int alternativ = Convert.ToInt32(Console.ReadLine());

            switch (alternativ)
            {
                // I want to be able to save the input from the user in case 1
                // so that it can be used in other cases.
                case 1:
                    läsPoäng(ämnen);        // Method that asks for the user to input points for specific courses
                    omvandlaBetyg(poäng);   // Method that converts user input to char "grades"
                    Console.Clear();
                    break;

                case 2:
                    skrivUtBetyg(betyg, ämnen); // Method that show grades for each course
                    break;

                case 3:
                    Statistik(betyg, poäng); // Method that show statistics for the points and grades
                    break;

                case 4:
                    Console.WriteLine("Tack för att du använt programmet 'Räkna betyg'");
                    repetera = false;
                    break;

                default:
                    Console.WriteLine("\nVänligen ange ett alternativ mellan 1-4.\n");
                    break;
            }
        }
        while (true);

    }
    // Method that asks for the user to input points for specific courses
    static List<int> läsPoäng(List<string> ämnen)
    {
        var poäng = new List<int>();

        Console.Write("Ange totalpoäng för matematik:");
        poäng.Add(Convert.ToInt32(Console.ReadLine()));

        Console.Write("Ange totalpoäng för svenska:");
        poäng.Add(Convert.ToInt32(Console.ReadLine()));

        Console.Write("Ange totalpoäng för engelska:");
        poäng.Add(Convert.ToInt32(Console.ReadLine()));

        Console.Write("Ange totalpoäng för historia:");
        poäng.Add(Convert.ToInt32(Console.ReadLine()));

        Console.Write("Ange totalpoäng för fysik:");
        poäng.Add(Convert.ToInt32(Console.ReadLine()));

        return poäng;
    }
    // Method that converts user input to char "grades"
    static List<char> omvandlaBetyg(List<int> poäng)
    {
        List<char> betyg = new List<char>();

        foreach (int i in poäng)
        {
            if (i < 50)
            {
                betyg.Add('F');
            }
            else if (i <= 60)
            {
                betyg.Add('E');
            }
            else if (i < 75)
            {
                betyg.Add('D');
            }
            else if (i < 90)
            {
                betyg.Add('C');
            }
            else if (i < 100)
            {
                betyg.Add('B');
            }
            else
            {
                betyg.Add('A');
            }
        }
        return betyg;
    }
    // Method that show grades for each course
    static void skrivUtBetyg(List<char> betyg, List<string> ämnen)
    {
        // Använder mig utav metoden .Zip för att slå ihop betyget med
        // sitt motsvarande ämne. För att sedan kunna presentera allt
        // i samma linje som visar betyget och ämnet "zippat" till en linje.
        // (Utan denna .Zip lösning så hade man fått göra två separate foreach-loopar
        // som då visar ämnena och betygen separat.
        // Denna lösning fungerar utmärkt för att iterera igenom två listor samtidigt.

        var betygOchÄmnen = betyg.Zip(ämnen, (first, second) => first + "         |" + second);

        Console.WriteLine(" \n_________________________");
        Console.WriteLine("|  Betyg    |   Ämne     ");

        foreach (var item in betygOchÄmnen)
        {
             Console.WriteLine("| " + item);
        }
        Console.WriteLine("_________________________");
    }
    // Method for showing grade and points statistics
    static void Statistik(List<char> betyg, List<int> poäng)
    {
        int betygA = 0;
        int betygC = 0;
        int betygF = 0;
        int totalPoäng = poäng.Sum();

        foreach (var c in betyg)
        {
            if (c == 'A')
            {
                betygA++;
            }
            else if (c == 'C')
            {
                betygC++;
            }
            else if (c == 'F')
            {
                betygF++;
            }
        }

        Console.WriteLine(" \n========================");
        Console.WriteLine("|Antal A betyg: " + betygA + "      |");
        Console.WriteLine("|Antal C betyg: " + betygC + "      |");
        Console.WriteLine("|Antal F betyg: " + betygF + "      |");
        Console.WriteLine("|Antal betygspoäng: " + totalPoäng + "|");
        Console.WriteLine("========================");
    }
}

}

Body:
The solution has been found.
I had to add a list for the input to be stored into.

As you can see below:

poäng = läsPoäng(ämnen);
betyg = omvandlaBetyg(poäng);


问:
How to use custom material color palettes in Angular?
I am using material buttons in my page as such:

```<code><button mat-stroked-button color="primary">Learn</button>
</code>```

This "primary" color is useful, however, I want to be able to use different color palettes with my material components. I have created another color palette in my .scss file as such:

```<code>$teal: (
  50 : #e5f4f3,
  100 : #bee4e1,
  200 : #93d3cd,
  300 : #67c1b8,
  400 : #47b3a9,
  500 : #26a69a,
  600 : #229e92,
  700 : #1c9588,
  800 : #178b7e,
  900 : #0d7b6c,
  A100 : #adfff3,
  A200 : #7affec,
  A400 : #47ffe4,
  A700 : #2dffe0,
  contrast: (
    50 : #000000,
    100 : #000000,
    200 : #000000,
    300 : #000000,
    400 : #000000,
    500 : #ffffff,
    600 : #ffffff,
    700 : #ffffff,
    800 : #ffffff,
    900 : #ffffff,
    A100 : #000000,
    A200 : #000000,
    A400 : #000000,
    A700 : #000000,
  )
);
</code>```

and I am trying to use it as such:

```<code><button mat-stroked-button color="teal">Learn</button>
</code>```

However, my IDE warns me that

```<code>teal is not a valid value for color. Expected: primary, accent, or warn
</code>```

What am I supposed to do?

答:
Angular Material themes are based on defining your primary, warn and accent colors.
The Documentation on Angular Material Theming are very helpful here

You can define these colors in your main scss file.
(below is copied straight from the docs)

```<code>@use '@angular/material' as mat;

@include mat.core();

$my-primary: mat.define-palette(mat.$indigo-palette, 500);
$my-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);

$my-theme: mat.define-light-theme((
 color: (
   primary: $my-primary,
   accent: $my-accent,
 )
));

@include mat.core-theme($my-theme);

@include mat.button-theme($my-theme);
</code>```

Once you define your theme, you can then use the primary|accent|warn based on your theme.

If you don't want to do this, then you need to change the button's style directly, i.e. the background-color

Body:
I am using material buttons in my page as such:

<button mat-stroked-button color="primary">Learn</button>

This "primary" color is useful, however, I want to be able to use different color palettes with my material components. I have created another color palette in my .scss file as such:

$teal: (
  50 : #e5f4f3,
  100 : #bee4e1,
  200 : #93d3cd,
  300 : #67c1b8,
  400 : #47b3a9,
  500 : #26a69a,
  600 : #229e92,
  700 : #1c9588,
  800 : #178b7e,
  900 : #0d7b6c,
  A100 : #adfff3,
  A200 : #7affec,
  A400 : #47ffe4,
  A700 : #2dffe0,
  contrast: (
    50 : #000000,
    100 : #000000,
    200 : #000000,
    300 : #000000,
    400 : #000000,
    500 : #ffffff,
    600 : #ffffff,
    700 : #ffffff,
    800 : #ffffff,
    900 : #ffffff,
    A100 : #000000,
    A200 : #000000,
    A400 : #000000,
    A700 : #000000,
  )
);

and I am trying to use it as such:

<button mat-stroked-button color="teal">Learn</button>

However, my IDE warns me that

teal is not a valid value for color. Expected: primary, accent, or warn

What am I supposed to do?

Body:
Angular Material themes are based on defining your primary, warn and accent colors.
The Documentation on Angular Material Theming are very helpful here

You can define these colors in your main scss file.
(below is copied straight from the docs)

@use '@angular/material' as mat;

@include mat.core();

$my-primary: mat.define-palette(mat.$indigo-palette, 500);
$my-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);

$my-theme: mat.define-light-theme((
 color: (
   primary: $my-primary,
   accent: $my-accent,
 )
));

@include mat.core-theme($my-theme);

@include mat.button-theme($my-theme);

Once you define your theme, you can then use the primary|accent|warn based on your theme.

If you don't want to do this, then you need to change the button's style directly, i.e. the background-color


问:
Recursive function to calculate the children of a parent
I have a set of data that looks like this:

Person1 is the parent of Person2

Person2 is the parent of Person3 and Person4

Person3 is the parent of Person1

If I try to calculate the whole tree for Person1, the max recurssion will be exceeded and the program will terminate in an error. The expected result would be Person1 -> [Person2, Person3, Person4], so basically in the case the the calculation has to be repeated for an element that is already in the list, this has to be ignored. Do you have an idea, how could I solve this problem? My function looks something like this:

```<code>def compute_children(self):
    children = []
    children.extend(self.child)
    for child in children:
        temp = child.compute_children()
        if 0 < len(temp):
            children.extend(temp)
    return children
</code>```

答:
A very simple solution would be to create a collection containing your starting node when you call compute_children for the first time and before the loop that you have, add all the children to the collection, ignoring any child that has already found its way into the collection.

In graph-theory this kind of approach is usually referred to as coloring, that is, you store what nodes were already visited somehow, so in the future you will not revisit the same nodes if a cycle is present.

Body:
I have a set of data that looks like this:

Person1 is the parent of Person2

Person2 is the parent of Person3 and Person4

Person3 is the parent of Person1

If I try to calculate the whole tree for Person1, the max recurssion will be exceeded and the program will terminate in an error. The expected result would be Person1 -> [Person2, Person3, Person4], so basically in the case the the calculation has to be repeated for an element that is already in the list, this has to be ignored. Do you have an idea, how could I solve this problem? My function looks something like this:

def compute_children(self):
    children = []
    children.extend(self.child)
    for child in children:
        temp = child.compute_children()
        if 0 < len(temp):
            children.extend(temp)
    return children


问:
Disable a text edit field in flutter
I need to disable TextFormField occasionally. I couldn't find a flag in the widget, or the controller to simply make it read-only or disable.
What is the best way to do it?</p>

答:
For that... TextField has two properties:

```<code>TextField(
          readOnly: true,
          enabled: false,
        )
</code>```

1- If you desire to disable the TextField typing and taping set [enabled: false]

2- If you desire to disable only TextField typing set [readOnly: true]

Title: Disable a text edit field in flutter

Body:
For that... TextField has two properties:

TextField(
          readOnly: true,
          enabled: false,
        )

1- If you desire to disable the TextField typing and taping set [enabled: false]

2- If you desire to disable only TextField typing set [readOnly: true]


问:
Query for a view to get list of dates in a date range and divide amount
I have a table with the following fields:

LineId
FromDate
ToDate
Amount

1
01.01.2021
10.01.2021
100

2
05.07.2021
07.07.2021
300

and so on, I have 91M rows

I want a query which will help me create a view with following data:

Lineid
FromDate
Amount

1
01.01.2021
10

1
02.01.2021
10

1
03.01.2021
10

1
04.01.2021
10

1
05.01.2021
10

1
06.01.2021
10

1
07.01.2021
10

1
08.01.2021
10

1
09.01.2021
10

1
10.01.2021
10

2
05.07.2021
100

2
06.07.2021
100

2
07.07.2021
100

I cant write a stored procedure. It has to be done using a view only.

Appreciate your help in this
Thanks in advance.

答:
So first you need a tally table (AKA numbers table.)

```<code>;--==== Tally Table
DECLARE @Rows INT = 10;

WITH E1(N)     AS (SELECT 1 FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS x(x)),
     iTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E1, E1 AS b)
SELECT t.N
FROM iTally AS t
WHERE t.N <= @Rows;
</code>```

This gets you as many rows as you need (up to 100 for this example.)

```<code>N
------
1
2
3
4
5
6
7
8
9
10
</code>```

Next, lets determine the correct amounts and number of rows required:

```<code>;--==== 1. Sample Data
DECLARE @t TABLE (
  LineId   INT,
  FromDate DATE,
  ToDate   DATE,
  Amount   INT);

INSERT @t VALUES
(1, '01.01.2021', '10.01.2021', 100),
(2, '05.07.2021', '07.07.2021', 300);

;--==== 2. Calculate # of months and divide amount by months for "Amount"
SELECT
  LineID = t.LineId,
  Months = mo.Months,
  Amount = t.Amount/mo.Months
FROM   @t AS t
CROSS APPLY (VALUES(DATEDIFF(MONTH,t.FromDate,t.ToDate)+1)) AS mo(Months)
</code>```

This returns:

```<code>LineID      Months      Amount
----------- ----------- -----------
1           10          10
2           3           100
</code>```

Now we will use the number of months to determine how many rows to generate:

```<code>;--==== 3. Solution
WITH E1(N)     AS (SELECT 1 FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS x(x)),
     iTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E1, E1 AS b)
SELECT
  LineId   = t.LineId,
  FromDate = DATEADD(MONTH,tally.N-1,t.FromDate),
  Amount   = t.Amount/mo.Months
FROM        @t                                              AS t
CROSS APPLY iTally                                          AS tally
CROSS APPLY (VALUES(DATEDIFF(MONTH,t.FromDate,t.ToDate)+1)) AS mo(Months)
WHERE       tally.N <= mo.Months
ORDER BY    t.LineId -- Not required;
</code>```

Results:

```<code>LineId      FromDate   Amount
----------- ---------- -----------
1           2021-01-01 10
1           2021-02-01 10
1           2021-04-01 10
1           2021-05-01 10
1           2021-06-01 10
1           2021-07-01 10
1           2021-08-01 10
1           2021-09-01 10
1           2021-10-01 10
1           2021-03-01 10
2           2021-07-07 100
2           2021-06-07 100
2           2021-05-07 100
</code>```

As a view you would replace my sample temp table with the real one.

```<code>CREATE VIEW dbo.YOUR_VIEW AS
WITH E1(N)     AS (SELECT 1 FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS x(x)),
     iTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E1, E1 AS b)
SELECT
  LineId   = t.LineId,
  FromDate = DATEADD(MONTH,tally.N-1,t.FromDate),
  Amount   = t.Amount/mo.Months
FROM        @t                                              AS t
CROSS APPLY iTally                                          AS tally
CROSS APPLY (VALUES(DATEDIFF(MONTH,t.FromDate,t.ToDate)+1)) AS mo(Months)
WHERE       tally.N <= mo.Months
ORDER BY    t.LineId -- Not required;
</code>```

Body:
So first you need a tally table (AKA numbers table.)

;--==== Tally Table
DECLARE @Rows INT = 10;

WITH E1(N)     AS (SELECT 1 FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS x(x)),
     iTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E1, E1 AS b)
SELECT t.N
FROM iTally AS t
WHERE t.N <= @Rows;

This gets you as many rows as you need (up to 100 for this example.)

N
------
1
2
3
4
5
6
7
8
9
10

Next, lets determine the correct amounts and number of rows required:

;--==== 1. Sample Data
DECLARE @t TABLE (
  LineId   INT,
  FromDate DATE,
  ToDate   DATE,
  Amount   INT);

INSERT @t VALUES
(1, '01.01.2021', '10.01.2021', 100),
(2, '05.07.2021', '07.07.2021', 300);

;--==== 2. Calculate # of months and divide amount by months for "Amount"
SELECT
  LineID = t.LineId,
  Months = mo.Months,
  Amount = t.Amount/mo.Months
FROM   @t AS t
CROSS APPLY (VALUES(DATEDIFF(MONTH,t.FromDate,t.ToDate)+1)) AS mo(Months)

This returns:

LineID      Months      Amount
----------- ----------- -----------
1           10          10
2           3           100

Now we will use the number of months to determine how many rows to generate:

;--==== 3. Solution
WITH E1(N)     AS (SELECT 1 FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS x(x)),
     iTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E1, E1 AS b)
SELECT
  LineId   = t.LineId,
  FromDate = DATEADD(MONTH,tally.N-1,t.FromDate),
  Amount   = t.Amount/mo.Months
FROM        @t                                              AS t
CROSS APPLY iTally                                          AS tally
CROSS APPLY (VALUES(DATEDIFF(MONTH,t.FromDate,t.ToDate)+1)) AS mo(Months)
WHERE       tally.N <= mo.Months
ORDER BY    t.LineId -- Not required;

Results:

LineId      FromDate   Amount
----------- ---------- -----------
1           2021-01-01 10
1           2021-02-01 10
1           2021-04-01 10
1           2021-05-01 10
1           2021-06-01 10
1           2021-07-01 10
1           2021-08-01 10
1           2021-09-01 10
1           2021-10-01 10
1           2021-03-01 10
2           2021-07-07 100
2           2021-06-07 100
2           2021-05-07 100

As a view you would replace my sample temp table with the real one.

CREATE VIEW dbo.YOUR_VIEW AS
WITH E1(N)     AS (SELECT 1 FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS x(x)),
     iTally(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E1, E1 AS b)
SELECT
  LineId   = t.LineId,
  FromDate = DATEADD(MONTH,tally.N-1,t.FromDate),
  Amount   = t.Amount/mo.Months
FROM        @t                                              AS t
CROSS APPLY iTally                                          AS tally
CROSS APPLY (VALUES(DATEDIFF(MONTH,t.FromDate,t.ToDate)+1)) AS mo(Months)
WHERE       tally.N <= mo.Months
ORDER BY    t.LineId -- Not required;


问:
MKDOCS Material theme Search capability not working
I set up an MKDOCS site with the 'material' theme and am hosting it using an Azure Web App.  The site works perfectly on the local host, but on Azure web app, the search bar doesn't work.  It shows 'Initializing search' when you put the cursor in the search field.  I tried adding this to the .yaml file, and it did not fix the issue:

```<code>plugins:
    - search:
        lang: en
</code>```

I am using MKDOCS 1.1.2 and material 6.2.8

答: For IIS server by adding MimeType has resolved the issue.</p>

Body:
I set up an MKDOCS site with the 'material' theme and am hosting it using an Azure Web App.  The site works perfectly on the local host, but on Azure web app, the search bar doesn't work.  It shows 'Initializing search' when you put the cursor in the search field.  I tried adding this to the .yaml file, and it did not fix the issue:

plugins:
    - search:
        lang: en

I am using MKDOCS 1.1.2 and material 6.2.8


问:
How to remove repetitive operations in a separate method?
My code has to guess the hidden number from 0 to 100 in 7 attempts. And every time I need to call the same operations again. How can I move these operations into a separate method and call them from there?</p>
```<code>public class Main {
  public static void main(String[] args) throws IOException {
    int min = 0;
    int max = 100;
    int midrange = Math.round((min + max)/2);
    String strInput = "";
    Scanner scan = new Scanner(System.in);

    while (!strInput.equals("1")){
        System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
        strInput = scan.nextLine();
    }

    while (!strInput.equals("+") && !strInput.equals("-") && !strInput.equals("=")){
        System.out.println("Is this number greater than, less than or equal to " + midrange + "? " +
                "Enter '+', if it's greater, '-' if it's less and '=' if it's equal:");
        strInput = scan.nextLine();
    }

    if (strInput.equals("=")) System.out.println("Great! Thank you for the game.");
    else if (strInput.equals("+")){
        // reduce the range
        min = midrange;

        // find a new midrange
        midrange = Math.round((min + max)/2);
    } else if (strInput.equals("-")){
        max = midrange;
        midrange = Math.round((min + max)/2);
    }

    strInput = "";

    while (!strInput.equals("+") && !strInput.equals("-") && !strInput.equals("=")){
        System.out.println("Is this number greater than, less than or equal to " + midrange + "? ");
        strInput = scan.nextLine();
    }

    // ... and so on until the correct number is found.

  }
}
</code>```

答:
You don't need multiple while loops. Just check for equality and put your if-else-block into the while loop. If you guessed the number correct just break out of the loop.</p>
```<code>public static void main(String[] args) throws IOException {

    int min = 0;
    int max = 100;
    int midrange = Math.round((min + max) / 2);
    String strInput = "";
    Scanner scan = new Scanner(System.in);

    System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
    strInput = scan.nextLine();

    while (!strInput.equals("=")) {
        System.out.println("Is this number greater than, less than or equal to " + midrange + "? " +
                "Enter '+', if it's greater, '-' if it's less and '=' if it's equal:");
        strInput = scan.nextLine();
        if (strInput.equals("=")) {
            System.out.println("Great! Thank you for the game.");
            break;
        } else if (strInput.equals("+")) {
            min = midrange;
            midrange = Math.round((min + max) / 2);
        } else if (strInput.equals("-")) {
            max = midrange;
            midrange = Math.round((min + max) / 2);
        }
    }
}
</code>```

Body:
My code has to guess the hidden number from 0 to 100 in 7 attempts. And every time I need to call the same operations again. How can I move these operations into a separate method and call them from there?

public class Main {
  public static void main(String[] args) throws IOException {
    int min = 0;
    int max = 100;
    int midrange = Math.round((min + max)/2);
    String strInput = "";
    Scanner scan = new Scanner(System.in);

    while (!strInput.equals("1")){
        System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
        strInput = scan.nextLine();
    }

    while (!strInput.equals("+") && !strInput.equals("-") && !strInput.equals("=")){
        System.out.println("Is this number greater than, less than or equal to " + midrange + "? " +
                "Enter '+', if it's greater, '-' if it's less and '=' if it's equal:");
        strInput = scan.nextLine();
    }

    if (strInput.equals("=")) System.out.println("Great! Thank you for the game.");
    else if (strInput.equals("+")){
        // reduce the range
        min = midrange;

        // find a new midrange
        midrange = Math.round((min + max)/2);
    } else if (strInput.equals("-")){
        max = midrange;
        midrange = Math.round((min + max)/2);
    }

    strInput = "";

    while (!strInput.equals("+") && !strInput.equals("-") && !strInput.equals("=")){
        System.out.println("Is this number greater than, less than or equal to " + midrange + "? ");
        strInput = scan.nextLine();
    }

    // ... and so on until the correct number is found.

  }
}

Body:
You don't need multiple while loops. Just check for equality and put your if-else-block into the while loop. If you guessed the number correct just break out of the loop.

public static void main(String[] args) throws IOException {

    int min = 0;
    int max = 100;
    int midrange = Math.round((min + max) / 2);
    String strInput = "";
    Scanner scan = new Scanner(System.in);

    System.out.println("Guess a number from 0 to 100: I'll guess it in 7 attempts! Enter 1 to continue:");
    strInput = scan.nextLine();

    while (!strInput.equals("=")) {
        System.out.println("Is this number greater than, less than or equal to " + midrange + "? " +
                "Enter '+', if it's greater, '-' if it's less and '=' if it's equal:");
        strInput = scan.nextLine();
        if (strInput.equals("=")) {
            System.out.println("Great! Thank you for the game.");
            break;
        } else if (strInput.equals("+")) {
            min = midrange;
            midrange = Math.round((min + max) / 2);
        } else if (strInput.equals("-")) {
            max = midrange;
            midrange = Math.round((min + max) / 2);
        }
    }
}


问:
How Does An Operating System Introduces The C Language To Write The Kernel
Does this introduction occurs at the NTLDR stage because it must be introduce, I mean isn't the Kernel written in C? I thought a computers only "known-before" programming language was Assembly Language that is hard coded at the Microcode of the Processor?</p>

答:
The first operating systems were all written in assembly. The C Language was created because its first use case was the creation of UNIX. A C compiler was written to handle this code and produce the assembly that the system understands (compiler was written in assembly of course). The effect snowballs from there. We now have a more powerful system to write code so we can of course write better compilers and better software with a more high level approach and let the compiler do the work for us.

As far as Windows is concerned it was a rewrite of an operating system called QDOS which was written in C.

Sidenote: Operating systems still require assembly code to function as there are many hardware independent pieces of information required (for example CR2 read on page fault on x86). Bootloaders and BIOS (older ones) are written in assembly because they are very specific to the hardware and are required to setup things such as interrupts and the stack pointer.


问:
Solve having more than one copy of React in the same app
I'm developing a React module locally. For that, I'm linking my module using npm link.
The module is imported successfully but hooks are failing inside the module. It's throwing the following error:

Invalid hook call. Hooks can only be called inside of the body of a
function component. This could happen for one of the following
reasons: 1. You might have mismatching versions of React and the
renderer (such as React DOM) 2. You might be breaking the Rules of
Hooks 3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to
debug and fix this problem.

Checking the suggestions at React docs, I can confirm my app is using duplicate versions of React since the following code returns false:

// node_modules/mymodule/src/index.js
export { default as ReactFromModule } from 'react'
```
<pre class="lang-js prettyprint-override"><code>// src/index.js
import React from 'react'
import { ReactFromModule } from 'mymodule'
console.log(React === ReactFromModule) //false
</code>```

This issue is full of suggestions but they are confusing. How can I solve it?

Note: Im not breaking rules of hooks, the error appears only when importing the module from an application.

答:
I was attempting to use the peerDependencies and removal of the devDependencies and it was failing.

It turned out I had a node_modules folder in one of the parent folders of the library I was working on and the duplicate version of React was being loaded from there instead of the tool that was trying to use the React library.

Rather than editing the devDependencies to remove react I just wrote a small script to delete anything that's in the peerDependencies from the node_modules folder.

```<code>npm view --json=true . peerDependencies | jq -r 'keys | .[] |  @text' | while read dep; do  rm -r ./node_modules/${dep} && echo Removed ${dep}; done
</code>```

Body:
I'm developing a React module locally. For that, I'm linking my module using npm link.
The module is imported successfully but hooks are failing inside the module. It's throwing the following error:

Invalid hook call. Hooks can only be called inside of the body of a
function component. This could happen for one of the following
reasons: 1. You might have mismatching versions of React and the
renderer (such as React DOM) 2. You might be breaking the Rules of
Hooks 3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to
debug and fix this problem.

Checking the suggestions at React docs, I can confirm my app is using duplicate versions of React since the following code returns false:

// node_modules/mymodule/src/index.js
export { default as ReactFromModule } from 'react'

// src/index.js
import React from 'react'
import { ReactFromModule } from 'mymodule'
console.log(React === ReactFromModule) //false

This issue is full of suggestions but they are confusing. How can I solve it?

Note: Im not breaking rules of hooks, the error appears only when importing the module from an application.

Body:
I was attempting to use the peerDependencies and removal of the devDependencies and it was failing.

It turned out I had a node_modules folder in one of the parent folders of the library I was working on and the duplicate version of React was being loaded from there instead of the tool that was trying to use the React library.

Rather than editing the devDependencies to remove react I just wrote a small script to delete anything that's in the peerDependencies from the node_modules folder.

npm view --json=true . peerDependencies | jq -r 'keys | .[] |  @text' | while read dep; do  rm -r ./node_modules/${dep} && echo Removed ${dep}; done


问:
How to hide a DIV element using RegEx and Jquery
I would like to hide all other element except class="imagebrowser" in following,

```<code><div class="entry">
    <p>Heading 1</p>
    <p>Heading 2</p>
        ...
    <p>Heading n</p>
    <b>This is abold text</b>
    <div>This is a div element</div>

    <div class="imagebrowser">
        Hello world
    </div>
</div>
</code>```

Expected result,

```<code><div class="entry">

    <div class="imagebrowser">
        Hello world
    </div>
</div>
</code>```

Any help please

答:
Try this</p>

```<code>$(".entry").children(":not(.imagebrowser)").hide();
</code>```

Body:
I would like to hide all other element except class="imagebrowser" in following,

Heading 1

Heading 2

        ...

Heading n

    This is abold text

This is a div element

        Hello world

Expected result,

        Hello world

Any help please

Body:
Try this

$(".entry").children(":not(.imagebrowser)").hide();


问:
react-chartjs-2 mixed type chart doesn't work with type in datasets
```<code>    labels: ['2021-10-29', '2021-10-30', '2021-10-31', '2021-11-01', '2021-11-02', '2021-11-03', '2021-11-04'],
    datasets: [
      {
        label: 'Coaching',
        data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
        backgroundColor: `rgb(98.100.24)`,
      },
      {
        label: 'Away',
        data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
        backgroundColor: `rgb(202,214,219)`,
      },
      {
        label: 'Total Call Count',
        data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
        backgroundColor: `rgb(${rand()},${rand()},${rand()})`,
        type: 'line',
      },

<Bar data={chartData}/>
</code>```

When I run this on react, this gives me the error like the below

```<code>  Type '{ labels: string[]; datasets: ({ label: string; data: number[]; backgroundColor: string; type?: undefined; } | { label: string; data: number[]; backgroundColor: string; type: string; })[]; }' is not assignable to type 'ChartData<"bar", number[], string>'.
    Types of property 'datasets' are incompatible.
      Type '({ label: string; data: number[]; backgroundColor: string; type?: undefined; } | { label: string; data: number[]; backgroundColor: string; type: string; })[]' is not assignable to type 'ChartDataset<"bar", number[]>[]'.
        Type '{ label: string; data: number[]; backgroundColor: string; type?: undefined; } | { label: string; data: number[]; backgroundColor: string; type: string; }' is not assignable to type 'ChartDataset<"bar", number[]>'.
          Type '{ label: string; data: number[]; backgroundColor: string; type: string; }' is not assignable to type 'ChartDataset<"bar", number[]>'.
            Type '{ label: string; data: number[]; backgroundColor: string; type: string; }' is not assignable to type '_DeepPartialObject<{ type: "bar"; } & BarControllerDatasetOptions>'.
              Types of property 'type' are incompatible.
                Type 'string' is not assignable to type '"bar" | undefined'.
    276 |           </Box>
    277 |           <Box className={classes.historyChart}>
  > 278 |             <Bar data={chartData} options={chartOptions} />
        |                  ^^^^
    279 |           </Box>
    280 |         </>
    281 |       )}
</code>```

Can anyone help me to make this work? I can't seem to find any solution on internet

答:
The type definitions are overly restrictive. You can work around this by casting to any.

```<code>type: 'line' as any,
</code>```

Body:
    labels: ['2021-10-29', '2021-10-30', '2021-10-31', '2021-11-01', '2021-11-02', '2021-11-03', '2021-11-04'],
    datasets: [
      {
        label: 'Coaching',
        data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
        backgroundColor: `rgb(98.100.24)`,
      },
      {
        label: 'Away',
        data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
        backgroundColor: `rgb(202,214,219)`,
      },
      {
        label: 'Total Call Count',
        data: [rand(), rand(), rand(), rand(), rand(), rand(), rand()],
        backgroundColor: `rgb(${rand()},${rand()},${rand()})`,
        type: 'line',
      },

<Bar data={chartData}/>

When I run this on react, this gives me the error like the below

  Type '{ labels: string[]; datasets: ({ label: string; data: number[]; backgroundColor: string; type?: undefined; } | { label: string; data: number[]; backgroundColor: string; type: string; })[]; }' is not assignable to type 'ChartData<"bar", number[], string>'.
    Types of property 'datasets' are incompatible.
      Type '({ label: string; data: number[]; backgroundColor: string; type?: undefined; } | { label: string; data: number[]; backgroundColor: string; type: string; })[]' is not assignable to type 'ChartDataset<"bar", number[]>[]'.
        Type '{ label: string; data: number[]; backgroundColor: string; type?: undefined; } | { label: string; data: number[]; backgroundColor: string; type: string; }' is not assignable to type 'ChartDataset<"bar", number[]>'.
          Type '{ label: string; data: number[]; backgroundColor: string; type: string; }' is not assignable to type 'ChartDataset<"bar", number[]>'.
            Type '{ label: string; data: number[]; backgroundColor: string; type: string; }' is not assignable to type '_DeepPartialObject<{ type: "bar"; } & BarControllerDatasetOptions>'.
              Types of property 'type' are incompatible.
                Type 'string' is not assignable to type '"bar" | undefined'.
    276 |           </Box>
    277 |           <Box className={classes.historyChart}>
  > 278 |             <Bar data={chartData} options={chartOptions} />
        |                  ^^^^
    279 |           </Box>
    280 |         </>
    281 |       )}

Can anyone help me to make this work? I can't seem to find any solution on internet

Body:
The type definitions are overly restrictive. You can work around this by casting to any.

type: 'line' as any,


问:
How do you do custom events on a JavaScript (ES6) class?
When I search for custom events on JavaScript classes, I get a lot of old or incomplete results. MDN shows a custom event off of a dom element. Stackoverflow's top result is almost ten years old and it uses the pre-ES6 syntax.

Is there a way of doing something like:

class Dog
{
  constructor(name)
  {
    this.name = name;
  }

  //something to expose bark event

}

const buddy = new Dog('buddy');
buddy.addEventListener("bark", function(e) {
  console.log(`${this.name} barked!`);
});```

答:
Extend EventTarget class to get all event functions:

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/EventTarget


问:
Combining/aggregating data in R
I feel like this is a really simple question, and I've looked a lot of places to try to find an answer to it, but everything seems to be looking to do a lot more than what I want--

I have a dataset that has multiple observations from multiple participants. One of the factors is where they're from (e.g. Buckinghamshire, Sussex, London). I want to combine everything that isn't London so I have two categories that are London and notLondon. How would I do this? I'd them want to be able to run a lm on these two, so how would I edit my dataset so that I could do lm(fom ~ [other factor]) where it would be the combined category?

Also, how would I combine all observations from each respective participant for a category? e.g. I have a category that's birth year, but currently when I do a summary of my data it will say, for example, 1996:265, because there are 265 observations from people born in '96. But I just want it to tell me how many participants were born in 1996.

Thanks!

答:
There are multiple parts to your question so let's take it step by step.

1.

For the first part this is a great use of tidyr::fct_collapse(). See example here:

library(tidyverse)

set.seed(1)
d <- sample(letters[1:5], 20, T) %>% factor()

# original distribution
table(d)
#> d
#> a b c d e
#> 6 4 3 1 6

# lumped distribution
fct_collapse(d, a = "a", other_level = "other") %>% table()
#> .
#>     a other
#>     6    14
```
<p><sup>Created on 2022-02-10 by the reprex package (v2.0.1)</sup></p>
<hr />
<h2>2.</h2>
<p>For the second part, you will have to clarify and share some data to get more help.</p>
<hr />
<h2>3.</h2>
<p>Here you can use <code>dplyr::summarize(n = n())</code> but you need to share some data to get an answer with your specific case.</p>
<p>However something like:</p>
<pre class="lang-r prettyprint-override"><code>df %>% group_by(birth_year) %>% summarize(n = n())
</code>```

will give you number of people with that birth year listed.

Title: Combining/aggregating data in R

Body:
There are multiple parts to your question so let's take it step by step.

1.

For the first part this is a great use of tidyr::fct_collapse(). See example here:

library(tidyverse)

set.seed(1)
d <- sample(letters[1:5], 20, T) %>% factor()

# original distribution
table(d)
#> d
#> a b c d e
#> 6 4 3 1 6

# lumped distribution
fct_collapse(d, a = "a", other_level = "other") %>% table()
#> .
#>     a other
#>     6    14

Created on 2022-02-10 by the reprex package (v2.0.1)

2.

For the second part, you will have to clarify and share some data to get more help.

3.

Here you can use dplyr::summarize(n = n()) but you need to share some data to get an answer with your specific case.

However something like:

df %>% group_by(birth_year) %>% summarize(n = n())

will give you number of people with that birth year listed.


问:
Does the Laravel Horizon replace the standard Laravel queues?
I use Laravel Horizon. And I really didn't understand from the documentation.

Should I not use the config/queue.php now?

On a production server, can I delete the supervisor settings for standart Laravel queue because I am now using the Horizon supervisor settings?

答:
You still need queue.php. Horizon is still based on Queue. Horizon augments Laravel's queue with additional features [1]. It comes with a dashboard and requires Redis as your queue driver.

In terms of configuring of your supervisor, yes, it is a replacement. queue:work and horizon:work basically does the same thing. So you should delete queue:work supervisor configuration and continue using Horizon supervisor.

Some references you might be interested in:

What is the difference between artisan queue:work and artisan horizon:work?

Relationship between Laravel Horizon and queue:work

Do I need run queue:work when I'm using horizon?


问:
Expo-react-native :Couldn't adb reverse: device 'adb' not found
I am using react-native-expo for mobile app development.
I use an android emulator for the app, vscode editor for development.
It started showing me this error from  few days.

```<code>› Opening on Android...
Couldn't adb reverse: device 'adb' not found
› Opening exp://10.0.46.81:19000 on Device adb
Couldn't start project on Android: Error running adb: device 'adb' not found
› Press ? │ show all commands
</code>```

I tried wiping the emulator, tapping on the build number in the emulator, but nothing worked out.

I've deleted the virtual devices and created new one. It worked for one time and again this process isn't working.
there isn't much about this on the internet.
need help.

答:
Just try this. It is work for me.

make sure you already add android sdk path in setting > appearance & behavior > system settings > android SDK > android SDK location
(Common path is C:\Users(name)\AppData\Local\Android\Sdk)

create new variable name and value in Environment Variables (User Variables)
(ANDROID_HOME  C:\Users(name)\AppData\Local\Android\Sdk)

add new Path in Environment Variables (User Variables)
(C:\Users(name)\AppData\Local\Android\Sdk\platform-tools)

It is work for me after I have solved it for 3 hours.
At first, I don't face the problem like this in flutter but in react-native.

Body:
I am using react-native-expo for mobile app development.
I use an android emulator for the app, vscode editor for development.
It started showing me this error from  few days.

› Opening on Android...
Couldn't adb reverse: device 'adb' not found
› Opening exp://10.0.46.81:19000 on Device adb
Couldn't start project on Android: Error running adb: device 'adb' not found
› Press ? │ show all commands

I tried wiping the emulator, tapping on the build number in the emulator, but nothing worked out.

I've deleted the virtual devices and created new one. It worked for one time and again this process isn't working.
there isn't much about this on the internet.
need help.


问:
How to transform table data to dataframe in R
I have csv file containing 3 columns: name, position and plays (plays has value 1 if player plays at that position, otherwise has value 0). One player can play more than one position. There are no two players with the same name. Sample data:

```<code>Brian,goalkeeper,0
Brian,fullback,1
Brian,playmaker,1
Brian,centerback,0
Brian,striker,0
Teddy,goalkeeper,0
Teddy,fullback,0
Teddy,playmaker,1
Teddy,centerback,1
Teddy,striker,1
Alan,goalkeeper,1
Alan,fullback,0
Alan,playmaker,0
Alan,centerback,1
Alan,striker,0
</code>```

I want to transform this data to data frame, to have names in rows, positions as column names, and values 0/1 as data in cells.

```<code>players <-read.csv("players.csv", sep=",", stringsAsFactors = FALSE)
</code>```

command

```<code>table1 <-    table(players$name,players$position,players$plays)
</code>```

gives me two tables

```<code>        centerback fullback goalkeeper playmaker striker
  Alan           0        1          0         1       1
  Brian          1        0          1         0       1
  Teddy          0        1          1         0       0

and
        centerback fullback goalkeeper playmaker striker
  Alan           1        0          1         0       0
  Brian          0        1          0         1       0
  Teddy          1        0          0         1       1
</code>```

(Why is table function doing this?, second one is correct for me). How is it possible to transform table1 to data frame, to have player names in rows, positions as column names, and values 0/1 as data in cells?

答:
I would use pivot_wider from tidyr for this.

```<code>library(tidyr)
players %>%
  pivot_wider(names_from = position, values_from = plays)

# A tibble: 3 x 6
  name  goalkeeper fullback playmaker centerback striker
  <chr>      <int>    <int>     <int>      <int>   <int>
1 Brian          0        1         1          0       0
2 Teddy          0        0         1          1       1
3 Alan           1        0         0          1       0
</code>```

Body:
I have csv file containing 3 columns: name, position and plays (plays has value 1 if player plays at that position, otherwise has value 0). One player can play more than one position. There are no two players with the same name. Sample data:

Brian,goalkeeper,0
Brian,fullback,1
Brian,playmaker,1
Brian,centerback,0
Brian,striker,0
Teddy,goalkeeper,0
Teddy,fullback,0
Teddy,playmaker,1
Teddy,centerback,1
Teddy,striker,1
Alan,goalkeeper,1
Alan,fullback,0
Alan,playmaker,0
Alan,centerback,1
Alan,striker,0

I want to transform this data to data frame, to have names in rows, positions as column names, and values 0/1 as data in cells.

players <-read.csv("players.csv", sep=",", stringsAsFactors = FALSE)

command

table1 <-    table(players$name,players$position,players$plays)

gives me two tables

        centerback fullback goalkeeper playmaker striker
  Alan           0        1          0         1       1
  Brian          1        0          1         0       1
  Teddy          0        1          1         0       0

and
        centerback fullback goalkeeper playmaker striker
  Alan           1        0          1         0       0
  Brian          0        1          0         1       0
  Teddy          1        0          0         1       1

(Why is table function doing this?, second one is correct for me). How is it possible to transform table1 to data frame, to have player names in rows, positions as column names, and values 0/1 as data in cells?

Body:
I would use pivot_wider from tidyr for this.

library(tidyr)
players %>%
  pivot_wider(names_from = position, values_from = plays)

# A tibble: 3 x 6
  name  goalkeeper fullback playmaker centerback striker
  <chr>      <int>    <int>     <int>      <int>   <int>
1 Brian          0        1         1          0       0
2 Teddy          0        0         1          1       1
3 Alan           1        0         0          1       0


问:
How to measure and display time taken for tasks when running ansible-playbook?
I have one playbook and in this playbook, there are so many tasks. I need to know which task has taken how much time?

Is there any solution?

答:
if you want to access that time within a playbook you can do something like this:

```<code>- name: Start
  set_fact:
    start_time: "{{ ansible_date_time.iso8601[:19] }}"

... do a bunch of stuff

- name: force update of current timestamp
  setup: filter='ansible_date_time'
- name: Get runtime
  set_fact:
    runtime: "{{ ((ansible_date_time.iso8601[:19] | to_datetime('%Y-%m-%dT%H:%M:%S')) - (start_time | to_datetime('%Y-%m-%dT%H:%M:%S'))).seconds }}"
</code>```

That fact will then be accessible to you as "{{ runtime }}"

You have to force the update of ansible_date_time because it's gathered as a fact initially, and otherwise not refreshed.

Body:
if you want to access that time within a playbook you can do something like this:

- name: Start
  set_fact:
    start_time: "{{ ansible_date_time.iso8601[:19] }}"

... do a bunch of stuff

- name: force update of current timestamp
  setup: filter='ansible_date_time'
- name: Get runtime
  set_fact:
    runtime: "{{ ((ansible_date_time.iso8601[:19] | to_datetime('%Y-%m-%dT%H:%M:%S')) - (start_time | to_datetime('%Y-%m-%dT%H:%M:%S'))).seconds }}"

That fact will then be accessible to you as "{{ runtime }}"

You have to force the update of ansible_date_time because it's gathered as a fact initially, and otherwise not refreshed.


问:
C# Permutation of an array of arraylists?
I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

```<code>myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };
</code>```

The count of myList can be varied so its length is not known beforehand.

I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).

```<code>1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93
</code>```

Does this make sense of what I am trying to accomplish?  I can't seem to come up with a good method for doing this, (if any).

Edit:

I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.

I want to end up building a string[] array of all the combinations that follows the format like below:

for the "1 2 93" permutation

I want the output to be "val0=1;val1=2;val2=93;"

I will experiment with recursion for now. Thank you DrJokepu

答:
Non-recursive solution:

```<code>foreach (String s1 in array1) {
    foreach (String s2 in array2) {
        foreach (String s3 in array3) {
            String result = s1 + " " + s2 + " " + s3;
            //do something with the result
        }
    }
}
</code>```

Recursive solution:

```<code>private ArrayList<String> permute(ArrayList<ArrayList<String>> ar, int startIndex) {
    if (ar.Count == 1) {
        foreach(String s in ar.Value(0)) {
            ar.Value(0) = "val" + startIndex + "=" + ar.Value(0);
        return ar.Value(0);
    }
    ArrayList<String> ret = new ArrayList<String>();
    ArrayList<String> tmp1 ar.Value(0);
    ar.remove(0);
    ArrayList<String> tmp2 = permute(ar, startIndex+1);
    foreach (String s in tmp1) {
        foreach (String s2 in tmp2) {
            ret.Add("val" + startIndex + "=" + s + " " + s2);
        }
    }
    return ret;
}
</code>```

OwnerDisplayName: TaRDy

LastEditorDisplayName: Quintin Robinson

ContentLicense: CC BY-SA 2.5

Body:
I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };

The count of myList can be varied so its length is not known beforehand.

I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).

1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93

Does this make sense of what I am trying to accomplish?  I can't seem to come up with a good method for doing this, (if any).

Edit:

I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.

I want to end up building a string[] array of all the combinations that follows the format like below:

for the "1 2 93" permutation

I want the output to be "val0=1;val1=2;val2=93;"

I will experiment with recursion for now. Thank you DrJokepu

Body:
Non-recursive solution:

foreach (String s1 in array1) {
    foreach (String s2 in array2) {
        foreach (String s3 in array3) {
            String result = s1 + " " + s2 + " " + s3;
            //do something with the result
        }
    }
}

Recursive solution:

private ArrayList<String> permute(ArrayList<ArrayList<String>> ar, int startIndex) {
    if (ar.Count == 1) {
        foreach(String s in ar.Value(0)) {
            ar.Value(0) = "val" + startIndex + "=" + ar.Value(0);
        return ar.Value(0);
    }
    ArrayList<String> ret = new ArrayList<String>();
    ArrayList<String> tmp1 ar.Value(0);
    ar.remove(0);
    ArrayList<String> tmp2 = permute(ar, startIndex+1);
    foreach (String s in tmp1) {
        foreach (String s2 in tmp2) {
            ret.Add("val" + startIndex + "=" + s + " " + s2);
        }
    }
    return ret;
}

OwnerDisplayName: Elie

LastEditorDisplayName: Elie


问:
Facebook API for getting all the wall posts
Is there any facebook API to get all the wall post of a particular user

or

a limited (say 10) number of wall posts

答: there is the Facebook Graph API for querying this data http://developers.facebook.com/docs/reference/api/ but I have no idea from your question what technology you want to integrate with </p>