问:
IonReactRouter is not a constructor fuction for JSX elements
I'm using react with ionic. I have installed the @ionic/react and @ionic/react-router packages, in the same way as other project that I used to develop. In this project i'm trying to use rollup to generate reusable components for other projects, but in this case an error appears me in IonReactRouter, the following it's my code:

```<code>import * as React from 'react';
import { IonApp } from '@ionic/react';
import {
    Route,
    Switch,
} from 'react-router';
import { IonReactRouter } from '@ionic/react-router';

/*Some Props interfaces*/

export const Router:React.FC<RouterProps> = (props: RouterProps) => (
    <IonApp>
        <IonReactRouter>
            <Routes {...props}/>
        </IonReactRouter>
    </IonApp>
);

export default GalaxyRouter;
</code>```

with this code, the following error appears me.

```<code>(rpt2 plugin) Error: /home/ec2-user/environment/galaxy-components-lib/src/GalaxyRouter/index.tsx(35,9):
semantic error TS2605 JSX element type 'IonReactRouter' is not a constructor function for JSX elements.
</code>```

this is my package.json:

```<code>{
  "name": "a-lib",
  "version": "0.0.0",
  "description": "",
  "author": "",
  "license": "MIT",
  "repository": "",
  "main": "dist/index.js",
  "module": "dist/index.es.js",
  "jsnext:main": "dist/index.es.js",
  "engines": {
    "node": ">=8",
    "npm": ">=5"
  },
  "scripts": {
    "test": "cross-env CI=1 react-scripts-ts test --env=jsdom",
    "test:watch": "react-scripts-ts test --env=jsdom",
    "build": "rollup -c",
    "start": "rollup -c -w",
    "prepare": "npm run build",
    "predeploy": "cd example && npm install && npm run build",
    "deploy": "gh-pages -d example/build",
    "release": "standard-version"
  },
  "peerDependencies": {
    "prop-types": "^15.5.4",
    "react": "^15.0.0 || ^16.0.0",
    "react-dom": "^15.0.0 || ^16.0.0",
    "@ionic/react": "^5.0.4",
    "@ionic/react-router": "^5.0.4",
    "@material-ui/core": "^4.9.5",
    "@material-ui/icons": "^4.9.1"
  },
  "devDependencies": {
    "@ionic/react": "^5.0.5",
    "@ionic/react-router": "^5.0.5",
    "@material-ui/core": "^4.9.5",
    "@material-ui/icons": "^4.9.1",
    "@svgr/rollup": "^2.4.1",
    "@types/jest": "^23.1.5",
    "@types/react": "^16.9.23",
    "@types/react-dom": "^16.9.5",
    "@types/react-router-dom": "^5.1.3",
    "babel-core": "^6.26.3",
    "babel-runtime": "^6.26.0",
    "cross-env": "^5.1.4",
    "gh-pages": "^1.2.0",
    "react-router": "^5.1.2",
    "react-router-dom": "^5.1.2",
    "react-scripts-ts": "^2.16.0",
    "rollup": "^0.62.0",
    "rollup-plugin-babel": "^3.0.7",
    "rollup-plugin-commonjs": "^9.1.3",
    "rollup-plugin-node-resolve": "^3.3.0",
    "rollup-plugin-peer-deps-external": "^2.2.0",
    "rollup-plugin-postcss": "^1.6.2",
    "rollup-plugin-typescript2": "^0.17.0",
    "rollup-plugin-url": "^1.4.0",
    "standard-version": "^7.1.0",
    "typescript": "^2.8.3"
  },
  "files": [
    "dist"
  ],
  "dependencies": {
    "@types/classnames": "^2.2.10",
    "classnames": "^2.2.6"
  }
}

</code>```

and this is my rollup configuration:

```<code>import typescript from 'rollup-plugin-typescript2'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
import postcss from 'rollup-plugin-postcss'
import resolve from 'rollup-plugin-node-resolve'
import url from 'rollup-plugin-url'
import svgr from '@svgr/rollup'

import pkg from './package.json'

export default {
  input: 'src/index.tsx',
  output: [
    {
      file: pkg.main,
      format: 'cjs',
      exports: 'named',
      sourcemap: true
    },
    {
      file: pkg.module,
      format: 'es',
      exports: 'named',
      sourcemap: true
    }
  ],
  plugins: [
    external(),
    postcss({}),
    url(),
    svgr(),
    resolve(),
    typescript({
      rollupCommonJSResolveHack: true,
      clean: true
    }),
    commonjs({
      include: 'node_modules/**',
      namedExports: {
        'node_modules/react-is/index.js': ['isValidElementType']
      }
    })
  ]
}
</code>```

I don't undestand why it's happens with this code, and I have no idea how to debug or fix it.

答:
IonReactRouter has been moved to its own package, so add this to your imports:

import { IonReactRouter } from '@ionic/react-router';
```

link here:
https://github.com/ionic-team/ionic/issues/18964

Body:
I'm using react with ionic. I have installed the @ionic/react and @ionic/react-router packages, in the same way as other project that I used to develop. In this project i'm trying to use rollup to generate reusable components for other projects, but in this case an error appears me in IonReactRouter, the following it's my code:

import * as React from 'react';
import { IonApp } from '@ionic/react';
import {
    Route,
    Switch,
} from 'react-router';
import { IonReactRouter } from '@ionic/react-router';

/*Some Props interfaces*/

export const Router:React.FC<RouterProps> = (props: RouterProps) => (
    <IonApp>
        <IonReactRouter>
            <Routes {...props}/>
        </IonReactRouter>
    </IonApp>
);

export default GalaxyRouter;

with this code, the following error appears me.

(rpt2 plugin) Error: /home/ec2-user/environment/galaxy-components-lib/src/GalaxyRouter/index.tsx(35,9):
semantic error TS2605 JSX element type 'IonReactRouter' is not a constructor function for JSX elements.

this is my package.json:

{
  "name": "a-lib",
  "version": "0.0.0",
  "description": "",
  "author": "",
  "license": "MIT",
  "repository": "",
  "main": "dist/index.js",
  "module": "dist/index.es.js",
  "jsnext:main": "dist/index.es.js",
  "engines": {
    "node": ">=8",
    "npm": ">=5"
  },
  "scripts": {
    "test": "cross-env CI=1 react-scripts-ts test --env=jsdom",
    "test:watch": "react-scripts-ts test --env=jsdom",
    "build": "rollup -c",
    "start": "rollup -c -w",
    "prepare": "npm run build",
    "predeploy": "cd example && npm install && npm run build",
    "deploy": "gh-pages -d example/build",
    "release": "standard-version"
  },
  "peerDependencies": {
    "prop-types": "^15.5.4",
    "react": "^15.0.0 || ^16.0.0",
    "react-dom": "^15.0.0 || ^16.0.0",
    "@ionic/react": "^5.0.4",
    "@ionic/react-router": "^5.0.4",
    "@material-ui/core": "^4.9.5",
    "@material-ui/icons": "^4.9.1"
  },
  "devDependencies": {
    "@ionic/react": "^5.0.5",
    "@ionic/react-router": "^5.0.5",
    "@material-ui/core": "^4.9.5",
    "@material-ui/icons": "^4.9.1",
    "@svgr/rollup": "^2.4.1",
    "@types/jest": "^23.1.5",
    "@types/react": "^16.9.23",
    "@types/react-dom": "^16.9.5",
    "@types/react-router-dom": "^5.1.3",
    "babel-core": "^6.26.3",
    "babel-runtime": "^6.26.0",
    "cross-env": "^5.1.4",
    "gh-pages": "^1.2.0",
    "react-router": "^5.1.2",
    "react-router-dom": "^5.1.2",
    "react-scripts-ts": "^2.16.0",
    "rollup": "^0.62.0",
    "rollup-plugin-babel": "^3.0.7",
    "rollup-plugin-commonjs": "^9.1.3",
    "rollup-plugin-node-resolve": "^3.3.0",
    "rollup-plugin-peer-deps-external": "^2.2.0",
    "rollup-plugin-postcss": "^1.6.2",
    "rollup-plugin-typescript2": "^0.17.0",
    "rollup-plugin-url": "^1.4.0",
    "standard-version": "^7.1.0",
    "typescript": "^2.8.3"
  },
  "files": [
    "dist"
  ],
  "dependencies": {
    "@types/classnames": "^2.2.10",
    "classnames": "^2.2.6"
  }
}

and this is my rollup configuration:

import typescript from 'rollup-plugin-typescript2'
import commonjs from 'rollup-plugin-commonjs'
import external from 'rollup-plugin-peer-deps-external'
import postcss from 'rollup-plugin-postcss'
import resolve from 'rollup-plugin-node-resolve'
import url from 'rollup-plugin-url'
import svgr from '@svgr/rollup'

import pkg from './package.json'

export default {
  input: 'src/index.tsx',
  output: [
    {
      file: pkg.main,
      format: 'cjs',
      exports: 'named',
      sourcemap: true
    },
    {
      file: pkg.module,
      format: 'es',
      exports: 'named',
      sourcemap: true
    }
  ],
  plugins: [
    external(),
    postcss({}),
    url(),
    svgr(),
    resolve(),
    typescript({
      rollupCommonJSResolveHack: true,
      clean: true
    }),
    commonjs({
      include: 'node_modules/**',
      namedExports: {
        'node_modules/react-is/index.js': ['isValidElementType']
      }
    })
  ]
}

I don't undestand why it's happens with this code, and I have no idea how to debug or fix it.

Body:
IonReactRouter has been moved to its own package, so add this to your imports:

import { IonReactRouter } from '@ionic/react-router';

link here:
https://github.com/ionic-team/ionic/issues/18964


来源: stackexchange

问:
React Native + Firestore infinite loop, using hooks
just starting to learn hooks here.

I am getting data from firestore and trying to set it to state using hooks. when I uncomment the line doing so, I get stuck in an infinite loop. no error, but the console goes crazy with logging the state thousands of times.

Let me know if you need more info!

```<code>function Lists(props) {

    const [lists, setLists] = useState([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const subscriber =
            firestore().collection('users').doc(props.user).collection('lists')
              .onSnapshot(QuerySnapshot => {
                  const items = []
                  QuerySnapshot.forEach(documentSnapshot => {
                      items.push({
                          ...documentSnapshot.data(),
                          key: documentSnapshot.id,
                      });
                    //setLists(items)

                    setLoading(false)

                    console.log(lists)
                  })

            })
            // unsubscribe from firestore
            return () => subscriber();
    })

//rest of func..
</code>```

答:
this issue happens becauase useEffect gets called over and over again. useEffect is like componentDidMount and componentDidUpdate if you are familiar with React class components.

so whenever you set the state inside the useEffect, you trigger an update, and then, useEffect gets called again, and thus the infinite loop.

to fix this, useEffect accepts a extra argument, which is an array of dependancies, which indicates that this useEffect call should only re-executed whenever a change happens to one of its dependancies. in your case you can provide an empty array, telling react that this useEffect should only be called one time.

 useEffect(() => {
        const subscriber =
            firestore().collection('users').doc(props.user).collection('lists')
              .onSnapshot(QuerySnapshot => {
                  const items = []
                  QuerySnapshot.forEach(documentSnapshot => {
                      items.push({
                          ...documentSnapshot.data(),
                          key: documentSnapshot.id,
                      });
                    //setLists(items)

                    setLoading(false)

                    console.log(lists)
                  })

            })
            // unsubscribe from firestore
            return () => subscriber();
    }, []) // <------------ the second argument we talked about
```

ContentLicense: CC BY-SA 4.0

Body:
just starting to learn hooks here.

I am getting data from firestore and trying to set it to state using hooks. when I uncomment the line doing so, I get stuck in an infinite loop. no error, but the console goes crazy with logging the state thousands of times.

Let me know if you need more info!

function Lists(props) {

    const [lists, setLists] = useState([])
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const subscriber =
            firestore().collection('users').doc(props.user).collection('lists')
              .onSnapshot(QuerySnapshot => {
                  const items = []
                  QuerySnapshot.forEach(documentSnapshot => {
                      items.push({
                          ...documentSnapshot.data(),
                          key: documentSnapshot.id,
                      });
                    //setLists(items)

                    setLoading(false)

                    console.log(lists)
                  })

            })
            // unsubscribe from firestore
            return () => subscriber();
    })

//rest of func..


问:
Python multiprocessing logging - why multiprocessing.get_logger
I've been struggled with multiprocessing logging for some time, and for many reasons.

One of my reason is, why another get_logger.

Of course I've seen this question and it seems the logger that multiprocessing.get_logger returns do some "process-shared locks" magic to make logging handling smooth.

So, today I looked into the multiprocessing code of Python 2.7 (/multiprocessing/util.py), and found that this logger is just a plain logging.Logger, and there's barely any magic around it.

Here's the description in Python documentation, right before the
get_logger function:

Some support for logging is available. Note, however, that the logging
  package does not use process shared locks so it is possible (depending
  on the handler type) for messages from different processes to get
  mixed up.

So when you use a wrong logging handler, even the get_logger logger may go wrong?
I've used a program uses get_logger for logging for some time.
It prints logs to StreamHandler and (seems) never gets mixed up.

Now My theory is:

multiprocessing.get_logger don't do process-shared locks at all

StreamHandler works for multiprocessing, but FileHandler doesn't

major purpose of this get_logger logger is for tracking processes'
life-cycle, and provide a easy-to-get and ready-to-use logger
that already logs process's name/id kinds of stuff

Here's the question:

Is my theory right?

How/Why/When do you use this get_logger?

答:
Yes, I believe you're right that multiprocessing.get_logger() doesn't do process-shared locks - as you say, the docs even state this. Despite all the upvotes, it looks like the question you link to is flawed in stating that it does (to give it the benefit of doubt, it was written over a decade ago - so perhaps that was the case at one point).

Why does multiprocessing.get_logger() exist then? The docs say that it:

Returns the logger used by multiprocessing. If necessary, a new one will be created.

When first created the logger has level logging.NOTSET and no default handler. Messages sent to this logger will not by default propagate to the root logger.

i.e. by default the multiprocessing module will not produce any log output since its logger's logging level is set to NOTSET so no log messages are produced.

If you were to have a problem with your code that you suspected to be an issue with multiprocessing, that lack of log output wouldn't be helpful for debugging, and that's what multiprocessing.get_logger() exists for - it returns the logger used by the multiprocessing module itself so that you can override the default logging configuration to get some logs from it and see what it's doing.

Since you asked for how to use multiprocessing.get_logger(), you'd call it like so and configure the logger in the usual fashion, for example:

```<code>logger = multiprocessing.get_logger()
formatter = logging.Formatter('[%(levelname)s/%(processName)s] %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

# now run your multiprocessing code
</code>```

That said, you may actually want to use multiprocessing.log_to_stderr() instead for convenience - as per the docs:

This function performs a call to get_logger() but in addition to returning the logger created by get_logger, it adds a handler which sends output to sys.stderr using format '[%(levelname)s/%(processName)s] %(message)s'

i.e. it saves you needing to set up quite so much logging config yourself, and you can instead start debugging your multiprocessing issue with just:

```<code>logger = multiprocessing.log_to_stderr()
logger.setLevel(logging.INFO)

# now run your multiprocessing code
</code>```

To reiterate though, that's just a normal module logger that's being configured and used, i.e. there's nothing special or process-safe about it. It just lets you see what's happening inside the multiprocessing module itself.

ContentLicense: CC BY-SA 3.0

Body:
Yes, I believe you're right that multiprocessing.get_logger() doesn't do process-shared locks - as you say, the docs even state this. Despite all the upvotes, it looks like the question you link to is flawed in stating that it does (to give it the benefit of doubt, it was written over a decade ago - so perhaps that was the case at one point).

Why does multiprocessing.get_logger() exist then? The docs say that it:

Returns the logger used by multiprocessing. If necessary, a new one will be created.

When first created the logger has level logging.NOTSET and no default handler. Messages sent to this logger will not by default propagate to the root logger.

i.e. by default the multiprocessing module will not produce any log output since its logger's logging level is set to NOTSET so no log messages are produced.

If you were to have a problem with your code that you suspected to be an issue with multiprocessing, that lack of log output wouldn't be helpful for debugging, and that's what multiprocessing.get_logger() exists for - it returns the logger used by the multiprocessing module itself so that you can override the default logging configuration to get some logs from it and see what it's doing.

Since you asked for how to use multiprocessing.get_logger(), you'd call it like so and configure the logger in the usual fashion, for example:

logger = multiprocessing.get_logger()
formatter = logging.Formatter('[%(levelname)s/%(processName)s] %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

# now run your multiprocessing code

That said, you may actually want to use multiprocessing.log_to_stderr() instead for convenience - as per the docs:

This function performs a call to get_logger() but in addition to returning the logger created by get_logger, it adds a handler which sends output to sys.stderr using format '[%(levelname)s/%(processName)s] %(message)s'

i.e. it saves you needing to set up quite so much logging config yourself, and you can instead start debugging your multiprocessing issue with just:

logger = multiprocessing.log_to_stderr()
logger.setLevel(logging.INFO)

# now run your multiprocessing code

To reiterate though, that's just a normal module logger that's being configured and used, i.e. there's nothing special or process-safe about it. It just lets you see what's happening inside the multiprocessing module itself.


问:
Suppress PHP warnings for expected Oracle exceptions
I have a PHP function that calls a PL/SQL package that can throw a number of known exceptions (i.e. user exceptions) that I can catch in PHP and act on. The problem is, despite catching the exception in PHP I get a warning in the PHP log file with a stack trace from the PL/SQL exception:

```<code>PHP Warning:  oci_execute(): ORA-20001: Something isn't valid
ORA-234565: at "MY.PACKAGE", line 234
ORA-923485: at "MY.PACKAGE", line 123
</code>```

How can I suppress these OCI warnings? I don't want to suppress all warnings as they can be helpful for other issues, but when it's an expected error from my PL/SQL I don't want it filling up my log file.

答:
If you only need to suppress the warning on oci_execute(), prepend it with @

```<code>@oci_execute()
</code>```

Using that kind of runtime error suppression is often not recommended since it covers up problems in the application, but you've handled the problem in the code by catching the exception already and understand the consequence of suppressing the warnings.

PHP docs on the @ operator...

Body:
I have a PHP function that calls a PL/SQL package that can throw a number of known exceptions (i.e. user exceptions) that I can catch in PHP and act on. The problem is, despite catching the exception in PHP I get a warning in the PHP log file with a stack trace from the PL/SQL exception:

PHP Warning:  oci_execute(): ORA-20001: Something isn't valid
ORA-234565: at "MY.PACKAGE", line 234
ORA-923485: at "MY.PACKAGE", line 123

How can I suppress these OCI warnings? I don't want to suppress all warnings as they can be helpful for other issues, but when it's an expected error from my PL/SQL I don't want it filling up my log file.

Body:
If you only need to suppress the warning on oci_execute(), prepend it with @

@oci_execute()

Using that kind of runtime error suppression is often not recommended since it covers up problems in the application, but you've handled the problem in the code by catching the exception already and understand the consequence of suppressing the warnings.

PHP docs on the @ operator...


问:
Can't Run H2o in R due to Java
I'm running Windows 10 64 bit.
I went to the command prompt and typed java -version to check the version.

The result told me java version "1.8.0_251" and 64-Bit Server VM (mixed mode)

However, when I'm trying to run H2o in R, error occurs:

```<code>You have a 32-bit version of Java. H2O works best with 64-bit Java.
Please download the latest Java SE JDK from the following URL: https://www.oracle.com/technetwork/java/javase/downloads/index.html
</code>```

I have tried downloading the recent Java SE 14 64 bit version and restarted R session, but the same error occurs. I have looked at my control panel and checked that my Java is 64 bit too.

So now I am completely lost in dealing with this Java problem. Anybody got some clue?

答:
You likely have 32-bit version of Java installed as well as your new 64-bit version.

H2O may find Java differently than what your terminal finds from Java -version. The order H2O finds Java is:

Searches in PATH

If not found, then checks JAVA_HOME

You have a few options to resolve your issue:

Uninstall your old 32-bit version of Java as @TomKraljevic mentioned

Add the new 64-bit Java to the beginning of your Windows PATH system variable under Windows settings

Add the new 64-bit Java to the beginning of PATH in your R environment. For example:

```<code>old_path <- Sys.getenv("PATH")
ys.setenv(PATH = paste("path/to/new_java", old_path, sep = ":"))
</code>```

Title: Can't Run H2o in R due to Java

Body:
I'm running Windows 10 64 bit.
I went to the command prompt and typed java -version to check the version.

The result told me java version "1.8.0_251" and 64-Bit Server VM (mixed mode)

However, when I'm trying to run H2o in R, error occurs:

You have a 32-bit version of Java. H2O works best with 64-bit Java.
Please download the latest Java SE JDK from the following URL: https://www.oracle.com/technetwork/java/javase/downloads/index.html

I have tried downloading the recent Java SE 14 64 bit version and restarted R session, but the same error occurs. I have looked at my control panel and checked that my Java is 64 bit too.

So now I am completely lost in dealing with this Java problem. Anybody got some clue?

Body:
You likely have 32-bit version of Java installed as well as your new 64-bit version.

H2O may find Java differently than what your terminal finds from Java -version. The order H2O finds Java is:

Searches in PATH

If not found, then checks JAVA_HOME

You have a few options to resolve your issue:

Uninstall your old 32-bit version of Java as @TomKraljevic mentioned

Add the new 64-bit Java to the beginning of your Windows PATH system variable under Windows settings

Add the new 64-bit Java to the beginning of PATH in your R environment. For example:

old_path <- Sys.getenv("PATH")
ys.setenv(PATH = paste("path/to/new_java", old_path, sep = ":"))


问:
AWS linux : ansible 2.9.7 using ec2.py and python 3.7 getting : ImportError: No module named boto , boto do installed
i installed python 3.7

```<code> python --version
Python 3.7.6
</code>```

i have python 2.7 installed also but i dont want to use it

so i set :

set alias python=python3

ansible :

```<code>ansible --version
ansible 2.9.7
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/ec2-user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/ec2-user/.local/lib/python3.7/site-packages/ansible
  executable location = /home/ec2-user/.local/bin/ansible
  python version = 3.7.6 (default, Feb 26 2020, 20:54:15) [GCC 7.3.1 20180712 (Red Hat 7.3.1-6)]
</code>```

in /etc/ansible/hosts i set the ec2.py from here :

https://raw.githubusercontent.com/ansible/ansible/stable-2.9/contrib/inventory/ec2.py

but when i run :

```<code>ansible localhost -m ping
</code>```

I'm getting :

```<code>[WARNING]:  * Failed to parse /etc/ansible/hosts with script plugin: Inventory script (/etc/ansible/hosts) had an execution error: Traceback (most recent call last):   File "/etc/ansible/hosts", line 164, in <module>     import boto
ImportError: No module named boto
[WARNING]:  * Failed to parse /etc/ansible/hosts with yaml plugin: Syntax Error while loading YAML.   expected '<document start>', but found '<scalar>'  The error appears to be in '/etc/ansible/hosts': line 12, column 31, but may be
elsewhere in the file depending on the exact syntax problem.  The offending line appears to be:  variables needed for Boto have already been set:     export AWS_ACCESS_KEY_ID='AK123'                               ^ here
[WARNING]:  * Failed to parse /etc/ansible/hosts with ini plugin: /etc/ansible/hosts:3: Error parsing host definition ''''': No closing quotation
[WARNING]: Unable to parse /etc/ansible/hosts as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available

PLAY [Ansible Ad-Hoc] ***********************************************************************************************************************************************************************************************************************

TASK [ping] *********************************************************************************************************************************************************************************************************************************
Saturday 02 May 2020  08:36:13 +0000 (0:00:00.089)       0:00:00.089 **********
ok: [localhost]

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Saturday 02 May 2020  08:36:14 +0000 (0:00:00.290)       0:00:00.380 **********
===============================================================================

boto and boto3 are installed in my server

    pip3 install boto
    Defaulting to user installation because normal site-packages is not writeable
    Requirement already satisfied: boto in ./.local/lib/python3.7/site-packages (2.49.0)

</code>```

```<code>pip3 install boto3
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: boto3 in ./.local/lib/python3.7/site-packages (1.13.0)
Requirement already satisfied: s3transfer<0.4.0,>=0.3.0 in ./.local/lib/python3.7/site-packages (from boto3) (0.3.3)
Requirement already satisfied: botocore<1.17.0,>=1.16.0 in ./.local/lib/python3.7/site-packages (from boto3) (1.16.0)
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in ./.local/lib/python3.7/site-packages (from boto3) (0.9.5)
Requirement already satisfied: docutils<0.16,>=0.10 in ./.local/lib/python3.7/site-packages (from botocore<1.17.0,>=1.16.0->boto3) (0.15.2)
Requirement already satisfied: urllib3<1.26,>=1.20; python_version != "3.4" in ./.local/lib/python3.7/site-packages (from botocore<1.17.0,>=1.16.0->boto3) (1.25.9)
Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in ./.local/lib/python3.7/site-packages (from botocore<1.17.0,>=1.16.0->boto3) (2.8.1)
Requirement already satisfied: six>=1.5 in ./.local/lib/python3.7/site-packages (from python-dateutil<3.0.0,>=2.1->botocore<1.17.0,>=1.16.0->boto3) (1.14.0)
</code>```

答:
It looks like an installation issue.

```<code>  configured module search path = ['/home/ec2-user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/ec2-user/.local/lib/python3.7/site-packages/ansible
  executable location = /home/ec2-user/.local/bin/ansible
</code>```

Ansible python module is /home/ec2-user/.local/lib/python3.7 which is in .local

try which python3
use that path for running the command
ansible localhost -m ping -e 'ansible_python_interpreter=<path  goes here>

Body:
i installed python 3.7

 python --version
Python 3.7.6

i have python 2.7 installed also but i dont want to use it

so i set :

set alias python=python3

ansible :

ansible --version
ansible 2.9.7
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/ec2-user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/ec2-user/.local/lib/python3.7/site-packages/ansible
  executable location = /home/ec2-user/.local/bin/ansible
  python version = 3.7.6 (default, Feb 26 2020, 20:54:15) [GCC 7.3.1 20180712 (Red Hat 7.3.1-6)]

in /etc/ansible/hosts i set the ec2.py from here :

https://raw.githubusercontent.com/ansible/ansible/stable-2.9/contrib/inventory/ec2.py

but when i run :

ansible localhost -m ping

I'm getting :

[WARNING]:  * Failed to parse /etc/ansible/hosts with script plugin: Inventory script (/etc/ansible/hosts) had an execution error: Traceback (most recent call last):   File "/etc/ansible/hosts", line 164, in <module>     import boto
ImportError: No module named boto
[WARNING]:  * Failed to parse /etc/ansible/hosts with yaml plugin: Syntax Error while loading YAML.   expected '<document start>', but found '<scalar>'  The error appears to be in '/etc/ansible/hosts': line 12, column 31, but may be
elsewhere in the file depending on the exact syntax problem.  The offending line appears to be:  variables needed for Boto have already been set:     export AWS_ACCESS_KEY_ID='AK123'                               ^ here
[WARNING]:  * Failed to parse /etc/ansible/hosts with ini plugin: /etc/ansible/hosts:3: Error parsing host definition ''''': No closing quotation
[WARNING]: Unable to parse /etc/ansible/hosts as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available

PLAY [Ansible Ad-Hoc] ***********************************************************************************************************************************************************************************************************************

TASK [ping] *********************************************************************************************************************************************************************************************************************************
Saturday 02 May 2020  08:36:13 +0000 (0:00:00.089)       0:00:00.089 **********
ok: [localhost]

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Saturday 02 May 2020  08:36:14 +0000 (0:00:00.290)       0:00:00.380 **********
===============================================================================

boto and boto3 are installed in my server

    pip3 install boto
    Defaulting to user installation because normal site-packages is not writeable
    Requirement already satisfied: boto in ./.local/lib/python3.7/site-packages (2.49.0)

pip3 install boto3
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: boto3 in ./.local/lib/python3.7/site-packages (1.13.0)
Requirement already satisfied: s3transfer<0.4.0,>=0.3.0 in ./.local/lib/python3.7/site-packages (from boto3) (0.3.3)
Requirement already satisfied: botocore<1.17.0,>=1.16.0 in ./.local/lib/python3.7/site-packages (from boto3) (1.16.0)
Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in ./.local/lib/python3.7/site-packages (from boto3) (0.9.5)
Requirement already satisfied: docutils<0.16,>=0.10 in ./.local/lib/python3.7/site-packages (from botocore<1.17.0,>=1.16.0->boto3) (0.15.2)
Requirement already satisfied: urllib3<1.26,>=1.20; python_version != "3.4" in ./.local/lib/python3.7/site-packages (from botocore<1.17.0,>=1.16.0->boto3) (1.25.9)
Requirement already satisfied: python-dateutil<3.0.0,>=2.1 in ./.local/lib/python3.7/site-packages (from botocore<1.17.0,>=1.16.0->boto3) (2.8.1)
Requirement already satisfied: six>=1.5 in ./.local/lib/python3.7/site-packages (from python-dateutil<3.0.0,>=2.1->botocore<1.17.0,>=1.16.0->boto3) (1.14.0)

Body:
It looks like an installation issue.

  configured module search path = ['/home/ec2-user/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/ec2-user/.local/lib/python3.7/site-packages/ansible
  executable location = /home/ec2-user/.local/bin/ansible

Ansible python module is /home/ec2-user/.local/lib/python3.7 which is in .local

try which python3
use that path for running the command
ansible localhost -m ping -e 'ansible_python_interpreter=<path  goes here>


问:
Jolt: concat Array values
Following my previous post
Jolt: split/ concat array values in Nifi

Now I'd like another value (ts) to be replicated into each split.
My input:

[
  {
    "value0": 0,
    "value1": 1,
    "value2": 2,
    "ts": 1
  },
  {
    "value0": 3,
    "value1": 4,
    "value2": 5,
    "ts": 2
  }
]
```
<p>Desired output:</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "value0": 0,
    "ts": 1
  },
  {
    "value1": 1,
    "ts": 1
  },
  {
    "value2": 2,
    "ts": 1
  },
  {
    "value0": 3,
    "ts": 2
  },
  {
    "value1": 4,
    "ts": 2
  },
  {
    "value2": 5,
    "ts": 2
  }
]
</code>```

The initial Jolt:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "value*": "[].&"
      }
    }
  }
]
```

Thanks !

答:
At the max you could do this, beyond this to achieve the above will be very tricky, using some chained spec it might be possible.

```<code>[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "value*": "[].&",
        "ts": "[].&"
      }
    }
  }
]
</code>```

Output for above spec:

```<code>[ {
  "ts" : 1
}, {
  "value0" : 0
}, {
  "value1" : 1
}, {
  "value2" : 2
}, {
  "ts" : 2
}, {
  "value0" : 3
}, {
  "value1" : 4
}, {
  "value2" : 5
} ]
</code>```

Title: Jolt: concat Array values

Body:
Following my previous post
Jolt: split/ concat array values in Nifi

Now I'd like another value (ts) to be replicated into each split.
My input:

[
  {
    "value0": 0,
    "value1": 1,
    "value2": 2,
    "ts": 1
  },
  {
    "value0": 3,
    "value1": 4,
    "value2": 5,
    "ts": 2
  }
]

Desired output:

[
  {
    "value0": 0,
    "ts": 1
  },
  {
    "value1": 1,
    "ts": 1
  },
  {
    "value2": 2,
    "ts": 1
  },
  {
    "value0": 3,
    "ts": 2
  },
  {
    "value1": 4,
    "ts": 2
  },
  {
    "value2": 5,
    "ts": 2
  }
]

The initial Jolt:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "value*": "[].&"
      }
    }
  }
]

Thanks !

Body:
At the max you could do this, beyond this to achieve the above will be very tricky, using some chained spec it might be possible.

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "value*": "[].&",
        "ts": "[].&"
      }
    }
  }
]

Output for above spec:

[ {
  "ts" : 1
}, {
  "value0" : 0
}, {
  "value1" : 1
}, {
  "value2" : 2
}, {
  "ts" : 2
}, {
  "value0" : 3
}, {
  "value1" : 4
}, {
  "value2" : 5
} ]


问:
How does enable_if help select specializations of a class template?
I have a basic grasp of SFINAE, and I think I understand many of the examples of how std::enable_if exploits it to select function template specializations, but I'm having a hard time wrapping my head around how it works for class templates.

The following example is from cppreference.com's explanation of std::enable_if:

template<class T, class Enable = void>
class A {}; // primary template

template<class T>
class A<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
}; // specialization for floating point types
```

I'm having trouble understanding how using std::enable_if in this way helps select the specialization.  (I don't doubt that it does.)

When the compiler sees a declaration like A<float> specialized;, it will see two possible template instantiations that fit:

The "primary template" A<T, Enable> where T is the type float and Enable is the type void (because of the default value).

The specialization A<T, void> where T is the type float and void is the result of the expression with the enable_if.

Aren't those ambiguous?  Both effectively result in A<T, void>, so why is the specialization chosen?

In a different case, like A<int> primary;, the options to the compiler seem to be:

The primary, A<T, Enable>, where T is the type int and Enable is the type void.

The specialization, A<T, ?>, where T is the type int and the ? represents where I'm completely lost.  In this case, the enable_if condition is false, so it doesn't define type, which leaves you with A<int, typename >.  Isn't that a syntax error?  Even in the face of SFINAE?

答:
From the reference on partial specialization of class templates:

When a class or variable (since C++14) template is instantiated, and there are partial specializations available, the compiler has to decide if the primary template is going to be used or one of its partial specializations.

If only one specialization matches the template arguments, that specialization is used

In this case, if the 2nd argument of the specialization is well-formed, it is chosen, precisely because it is a specialization, and not the primary template.

In case the 2nd template argument is not well-formed, then SFINAE kicks in. In particular:

When substituting the explicitly specified or deduced type for the template parameter fails, the specialization is discarded from the overload set instead of causing a compile error.

and

The following type errors are SFINAE errors:

attempting to use a member of a type, where
    the type does not contain the specified member

How this is done, i.e. how exactly the compiler discards the specialization, instead of giving an error, is not specified; the compiler is just required to do the right thing.

Body:
I have a basic grasp of SFINAE, and I think I understand many of the examples of how std::enable_if exploits it to select function template specializations, but I'm having a hard time wrapping my head around how it works for class templates.

The following example is from cppreference.com's explanation of std::enable_if:

template<class T, class Enable = void>
class A {}; // primary template

template<class T>
class A<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
}; // specialization for floating point types

I'm having trouble understanding how using std::enable_if in this way helps select the specialization.  (I don't doubt that it does.)

When the compiler sees a declaration like A<float> specialized;, it will see two possible template instantiations that fit:

The "primary template" A<T, Enable> where T is the type float and Enable is the type void (because of the default value).

The specialization A<T, void> where T is the type float and void is the result of the expression with the enable_if.

Aren't those ambiguous?  Both effectively result in A<T, void>, so why is the specialization chosen?

In a different case, like A<int> primary;, the options to the compiler seem to be:

The primary, A<T, Enable>, where T is the type int and Enable is the type void.

The specialization, A<T, ?>, where T is the type int and the ? represents where I'm completely lost.  In this case, the enable_if condition is false, so it doesn't define type, which leaves you with A<int, typename >.  Isn't that a syntax error?  Even in the face of SFINAE?


问:
TensorFlow 2 documentation for graph-mode
When I check the TensorFlow documentation (Python API docs or guides), it all seems exclusively for eager-mode. Almost all the examples don't even mention this.
For some specific operation/function like tf.nn.relu, this does not really make any difference.
However, for more complex things like tf.data (Dataset API, guide), it likely makes a difference. Esp all the examples would be different for graph mode.

Where can I find recent documentation (API references, guides, tutorials, examples) for graph mode?
(My current fallback is to check latest TF 1 documentation. But at some point, this will become more and more outdated.)

Or is graph mode deprecated so far that documentation for it seems not necessary anymore?

答:
Graph mode in TensorFlow 2 is different from graph mode in TensorFlow 1. Instead of using sessions and placeholders, TensorFlow 2 uses functions annotated with tf.function. The eager mode examples you see can be executed in graph mode by wrapping them within a tf.function.

If you prefer to use the TensorFlow 1 style of graph mode with sessions and placeholders, you can still do so in TensorFlow 2 by using the tf.compat.v1 module. The API docs in that module describe the TensorFlow 1 style of graph mode. You can find archived guides about TensorFlow 1 graph mode at https://github.com/tensorflow/docs/tree/master/site/en/r1/guide


问:
Switch to existing open tab in VSCode
I'm new to VSCode and don't understand the default tab functionality. If I have a class in the right split panel and select the same class from the package selection menu it opens a second copy of the class in preview or edit in the left split menu. How can I change this behavior so that it switches to the selected class regardless of which panel it's in? </p>

答: You can configure "workbench.editor.revealIfOpen": true in settings to always reveal a file if already opened in any other group.</p>

Title: Switch to existing open tab in VSCode


问:
From date to tuple Python
I have like input: 12/12/2019
and I want this output: (12,12,2019)
I tried this code but it doesn't work because they consider "/" as a division :

```<code>date= 12/12/2019
date=str(date).split("/")
print(tuple(date))
</code>```

答:
The problem in your code is that you created date variable as integer instead of string.

If you run

```<code>date = 12/12/2019
print(type(date))
</code>```

You will get <type 'int'>. It means date is an integer number, not string.

If you change date to string as shown below, you will get the output you are expecting.

```<code>date = "12/12/2019"
date=str(date).split("/")
print(tuple(date))
</code>```

Title: From date to tuple Python

Body:
I have like input: 12/12/2019
and I want this output: (12,12,2019)
I tried this code but it doesn't work because they consider "/" as a division :

date= 12/12/2019
date=str(date).split("/")
print(tuple(date))

Body:
The problem in your code is that you created date variable as integer instead of string.

If you run

date = 12/12/2019
print(type(date))

You will get <type 'int'>. It means date is an integer number, not string.

If you change date to string as shown below, you will get the output you are expecting.

date = "12/12/2019"
date=str(date).split("/")
print(tuple(date))


问:
Is it possible to pass parameters into a function using a switch statement in c++?
Is there any way to pass parameters into functions using switch statements in c++?  What I am trying to achieve is turning a series of if statements into one switch statement.

As an example, I'd like to turn this:

```<code>if (function(a)) {
  //code
}

if (function(b)) {
  //code
}

if (function(c)) {
  //code
}
</code>```

into this:

```<code>switch (function(a/b/c)) {
case a:
  //code
case b:
  //code
case c:
  //code
}
</code>```

The function returns true or false depending on whether or not a, b, or c is active.  It is important to note that a, b, and c would indeed be constants, but the function itself would determine whether or not they're currently active.  The problem I am working on is whether or not a key is currently pressed when the function is given the key code to check.  It looks something like this:

```<code>if (isKeyPressed(Key::A)) {
  //code
}
</code>```

Is this possible or does it break what a switch statement fundamentally is?

答:
That is not how a switch is used.  It would need to look more like this instead:

switch (someValue)
{
case value1:
  function(a);
  break;
case value2:
  function(b);
  break;
case value3:
  function(c);
  break;
}
```

<p>If that is not what you are looking for, then the <code>?:</code> operator <em>may</em> work for you, depending on what your inputs actually are, eg:</p>

<pre class="lang-cpp prettyprint-override"><code>function( condition1 ? a : (condition2 ? b : c) );
</code>```

Or, maybe you are trying to calling the function 1 time and get different kinds of output depending on the input, that you can then test for?  If so, then std::variant may be what you are looking for, eg:

std::variant function()
{
  return ...;
}

auto v = function(input);
if (std::holds_alternative(v)) {
  //code
}

else if (std::holds_alternative(v)) {
  //code
}

else if (std::holds_alternative<c>(v)) {
  //code
}
```

<p>Or:</p>

<pre class="lang-cpp prettyprint-override"><code>auto v = function(input);
switch (v.index()) {
  case 0: // a
    //code
    break;
  case 1: // b
    //code
    break;
  case 2: // c
    //code
    break;
}
</code>```

Or:

auto v = function(input);
std::visit([](auto&& arg) {
  using T = std::decay_t<decltype(arg)>;
  if constexpr (std::is_same_v<T, a>) {
    // code
  }
  else if constexpr (std::is_same_v<T, b>) {
    // code
  }
  else if constexpr (std::is_same_v<T, c>) {
    // code
  }
}, v);
```

<p>Or:</p>

<pre class="lang-cpp prettyprint-override"><code>template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

auto v = function(input);
std::visit(overloaded {
  [](a arg) { /* code */ },
  [](b arg) { /* code */ },
  [](c arg) { /* code */ },
}, v);
</code>```

Body:
Is there any way to pass parameters into functions using switch statements in c++?  What I am trying to achieve is turning a series of if statements into one switch statement.

As an example, I'd like to turn this:

if (function(a)) {
  //code
}

if (function(b)) {
  //code
}

if (function(c)) {
  //code
}

into this:

switch (function(a/b/c)) {
case a:
  //code
case b:
  //code
case c:
  //code
}

The function returns true or false depending on whether or not a, b, or c is active.  It is important to note that a, b, and c would indeed be constants, but the function itself would determine whether or not they're currently active.  The problem I am working on is whether or not a key is currently pressed when the function is given the key code to check.  It looks something like this:

if (isKeyPressed(Key::A)) {
  //code
}

Is this possible or does it break what a switch statement fundamentally is?

Body:
That is not how a switch is used.  It would need to look more like this instead:

switch (someValue)
{
case value1:
  function(a);
  break;
case value2:
  function(b);
  break;
case value3:
  function(c);
  break;
}

If that is not what you are looking for, then the ?: operator may work for you, depending on what your inputs actually are, eg:

function( condition1 ? a : (condition2 ? b : c) );

Or, maybe you are trying to calling the function 1 time and get different kinds of output depending on the input, that you can then test for?  If so, then std::variant may be what you are looking for, eg:

std::variant<a,b,c> function()
{
  return ...;
}

auto v = function(input);
if (std::holds_alternative<a>(v)) {
  //code
}

else if (std::holds_alternative<b>(v)) {
  //code
}

else if (std::holds_alternative<c>(v)) {
  //code
}

Or:

auto v = function(input);
switch (v.index()) {
  case 0: // a
    //code
    break;
  case 1: // b
    //code
    break;
  case 2: // c
    //code
    break;
}

Or:

auto v = function(input);
std::visit([](auto&& arg) {
  using T = std::decay_t<decltype(arg)>;
  if constexpr (std::is_same_v<T, a>) {
    // code
  }
  else if constexpr (std::is_same_v<T, b>) {
    // code
  }
  else if constexpr (std::is_same_v<T, c>) {
    // code
  }
}, v);

Or:

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

auto v = function(input);
std::visit(overloaded {
  [](a arg) { /* code */ },
  [](b arg) { /* code */ },
  [](c arg) { /* code */ },
}, v);


问:
Decouple update logic from useEffect in react+D3
I am trying to build a hierarchical tree visualization using React and D3.
My component receives the hierarchical data in a CSV format as props, which I pass through the stratify function of D3 to obtain a root node to my tree. The root node is set as state.

Currently, I am using a single useEffect(()=>{},[root]) to build the tree, which re-renders on any changes to root.

It is messy as all the action happens inside this useEffect(). I want to know how can I decouple the update() method and use it separately.

As I am a beginner is both React and D3, I welcome any other suggestion on how to handle the state , how to make it more declarative et al.

Here is the code:

useEffect(() => {
    if (root) {
      //Declare a tree layout
      //nodeSize ensure each node has it's own space and does not overlap
      const tree = d3
        .tree()
        .nodeSize([
          attributes.nodeWidth,
          attributes.nodeHeight + attributes.veritcalNodeGap,
        ]);

      root.x0 = 0;
      root.y0 = attributes.width / 2;

      //Set children of nodes deeper than 2 to null;
      root.descendants().forEach((d, i) => {
        d.id = i;
        d._children = d.children;
        if (d.depth && d.data.child.length !== 7) d.children = null;
      });

      // append the svg object to the body of the page
      // and define zoom behaviours

      const svg = d3
        .select(d3Ref.current)
        .call(
          d3
            .zoom()
            .scaleExtent([0.05, 3])
            .on("zoom", () => svg.attr("transform", d3.event.transform))
        )
        .on("dblclick.zoom", null)
        .append("svg")
        .attr("viewBox", [0, 0, attributes.width, attributes.height])
        .append("g")
        .attr("transform", (d) => `translate(${attributes.width / 2},120)`);

      //Group all links together
      const gLink = svg
        .append("g")
        .attr("fill", "none")
        .attr("stroke", "#555")
        .attr("stroke-opacity", 1)
        .attr("stroke-width", 1.5);
      // .attr("x", "200  ");

      //Group all nodes together
      const gNode = svg
        .append("g")
        .attr("cursor", "pointer")
        .attr("pointer-events", "all");

      const diagonal = linkVertical()
        .x((d) => d.x)
        .y((d) => d.y);

      update();

      function update() {
        const nodes = root.descendants().reverse();
        const links = root.links();

        tree(root);

        //Define group and join the data
        const node = gNode.selectAll("g").data(nodes, (d) => d.id);

        let nodeEnter = node
          .enter()
          .append("g")
          .attr("class", "node")
          .attr("transform", (d) => `translate(${root.x0},${root.y0})`)
          .on("click", (d) => {
            d.children = d.children ? null : d._children;
            update();
          });

        let nodeGroup = nodeEnter.append("g").attr("class", "node-group");

        nodeEnter
          .append("circle")
          .attr("r", 7)
          .attr("cursor", (d) => (d._children ? "pointer" : "none"))
          .attr("fill", (d) => (d._children ? "lightsteelblue" : "#999"))
          .attr("stroke", (d) => (d._children ? "steelblue" : "#999"))
          .attr("stroke-width", 2);
        //add text
        nodeEnter
          .append("text")
          .attr("dy", ".35em")
          .attr("x", 25)
          .text((d) => d.data.child);

        //Transition nodes to their new positions
        const nodeUpdate = node //SVG.data()
          .merge(nodeEnter)
          .transition()
          .duration(attributes.duration)
          .attr("transform", (d) => `translate(${d.x},${d.y})`)
          .attr("fill-opacity", 1)
          .attr("stroke-opacity", 1);

        //Transition exiting nodes to the parent's new position
        const nodeExit = node
          .exit()
          .transition()
          .duration(attributes.duration)
          .remove()
          .attr("transform", (d) => `translate(${root.x},${root.y})`);

        // // Update the links…
        const link = gLink.selectAll("path").data(links, (d) => d.target.id);
        // // Enter any new links at the parent's previous position.
        const linkEnter = link
          .enter()
          .append("path")
          .attr("class", "link")
          .attr("d", (d) => {
            const o = { x: root.x0, y: root.y0 };
            return diagonal({ source: o, target: o });
          });

        // //Transition links to their new position
        link
          .merge(linkEnter)
          .transition()
          .duration(attributes.duration)
          .attr("d", diagonal);

        // // Transition exiting nodes to the parent's new position.
        link
          .exit()
          .transition()
          .duration(attributes.duration)
          .remove()
          .attr("d", (d) => {
            const o = { x: root.x, y: root.y };
            return diagonal({ source: o, target: o });
          });

        root.eachBefore((d) => {
          d.x0 = d.x;
          d.y0 = d.y;
        });
      }
    }
  }, [root]);
```

答:
Here is one idea.
You can have the initial effect onMount once, then updates only when root change,
You can use two useEffect on your component.

// hook on onMount, you prepare root, tree etc
let tree;
useEffect(() => {
  if (root) {
    //Declare a tree layout
    //nodeSize ensure each node has it's own space and does not overlap
    tree = d3
      .tree()
      .nodeSize([
        attributes.nodeWidth,
        attributes.nodeHeight + attributes.veritcalNodeGap,
      ]);

    root.x0 = 0;
    root.y0 = attributes.width / 2;

    //Set children of nodes deeper than 2 to null;
    root.descendants().forEach((d, i) => {
      d.id = i;
      d._children = d.children;
      if (d.depth && d.data.child.length !== 7) d.children = null;
    });

    // append the svg object to the body of the page
    // and define zoom behaviours

    const svg = d3
      .select(d3Ref.current)
      .call(
        d3
          .zoom()
          .scaleExtent([0.05, 3])
          .on('zoom', () => svg.attr('transform', d3.event.transform))
      )
      .on('dblclick.zoom', null)
      .append('svg')
      .attr('viewBox', [0, 0, attributes.width, attributes.height])
      .append('g')
      .attr('transform', (d) => `translate(${attributes.width / 2},120)`);

    //Group all links together
    const gLink = svg
      .append('g')
      .attr('fill', 'none')
      .attr('stroke', '#555')
      .attr('stroke-opacity', 1)
      .attr('stroke-width', 1.5);
    // .attr("x", "200  ");

    //Group all nodes together
    const gNode = svg
      .append('g')
      .attr('cursor', 'pointer')
      .attr('pointer-events', 'all');

    const diagonal = linkVertical()
      .x((d) => d.x)
      .y((d) => d.y);
  }
}, []);

// here is the update only when [root] changes

useEffect(() => {
  const nodes = root.descendants().reverse();
  const links = root.links();

  tree(root);

  //Define group and join the data
  const node = gNode.selectAll('g').data(nodes, (d) => d.id);

  let nodeEnter = node
    .enter()
    .append('g')
    .attr('class', 'node')
    .attr('transform', (d) => `translate(${root.x0},${root.y0})`)
    .on('click', (d) => {
      d.children = d.children ? null : d._children;
      update();
    });

  let nodeGroup = nodeEnter.append('g').attr('class', 'node-group');

  nodeEnter
    .append('circle')
    .attr('r', 7)
    .attr('cursor', (d) => (d._children ? 'pointer' : 'none'))
    .attr('fill', (d) => (d._children ? 'lightsteelblue' : '#999'))
    .attr('stroke', (d) => (d._children ? 'steelblue' : '#999'))
    .attr('stroke-width', 2);
  //add text
  nodeEnter
    .append('text')
    .attr('dy', '.35em')
    .attr('x', 25)
    .text((d) => d.data.child);

  //Transition nodes to their new positions
  const nodeUpdate = node //SVG.data()
    .merge(nodeEnter)
    .transition()
    .duration(attributes.duration)
    .attr('transform', (d) => `translate(${d.x},${d.y})`)
    .attr('fill-opacity', 1)
    .attr('stroke-opacity', 1);

  //Transition exiting nodes to the parent's new position
  const nodeExit = node
    .exit()
    .transition()
    .duration(attributes.duration)
    .remove()
    .attr('transform', (d) => `translate(${root.x},${root.y})`);

  // // Update the links…
  const link = gLink.selectAll('path').data(links, (d) => d.target.id);
  // // Enter any new links at the parent's previous position.
  const linkEnter = link
    .enter()
    .append('path')
    .attr('class', 'link')
    .attr('d', (d) => {
      const o = { x: root.x0, y: root.y0 };
      return diagonal({ source: o, target: o });
    });

  // //Transition links to their new position
  link
    .merge(linkEnter)
    .transition()
    .duration(attributes.duration)
    .attr('d', diagonal);

  // // Transition exiting nodes to the parent's new position.
  link
    .exit()
    .transition()
    .duration(attributes.duration)
    .remove()
    .attr('d', (d) => {
      const o = { x: root.x, y: root.y };
      return diagonal({ source: o, target: o });
    });

  root.eachBefore((d) => {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}, [root]);
```


问:
Default message in botman
I'm testing botman in Laravel and it works very well. But I can not find how to put a message by default. Can someone give me an orientation ?</p>

```<code>$botman->hears('Hi', function ($bot) {
    $bot->reply('Hello!');
});
</code>```

答:
BotMan allows you to create a fallback method, that gets called if none of your "hears" patterns matches. You may use this feature to give your bot users guidance on how to use your bot.

```<code>$botman->fallback(function($bot) {
$bot->reply('Sorry, I did not understand these commands. Here is a list of commands I understand: ...');
</code>```

});

Title: Default message in botman

Body:
I'm testing botman in Laravel and it works very well. But I can not find how to put a message by default. Can someone give me an orientation ?

$botman->hears('Hi', function ($bot) {
    $bot->reply('Hello!');
});

Body:
BotMan allows you to create a fallback method, that gets called if none of your "hears" patterns matches. You may use this feature to give your bot users guidance on how to use your bot.

$botman->fallback(function($bot) {
$bot->reply('Sorry, I did not understand these commands. Here is a list of commands I understand: ...');

});


问:
MVC - Set selected value of SelectList
How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;

```<code>SelectList selectList = new SelectList(items, "ID", "Name");
</code>```

I need to set the selected value after this stage

答:
I ended up here because SelectListItem is no longer picking the selected value correctly. To fix it, I changed the usage of EditorFor for a "manual" approach:

```<code>        <select id="Role" class="form-control">
            @foreach (var role in ViewBag.Roles)
            {
                if (Model.Roles.First().RoleId == role.Value)
                {
                    <option value="@role.Value" selected>@role.Text</option>
                }
                else
                {
                    <option value="@role.Value">@role.Text</option>
                }
            }
        </select>
</code>```

Hope it helps someone.

ContentLicense: CC BY-SA 2.5

Title: MVC - Set selected value of SelectList

Body:
How can I set the selectedvalue property of a SelectList after it was instantiated without a selectedvalue;

SelectList selectList = new SelectList(items, "ID", "Name");

I need to set the selected value after this stage

Body:
I ended up here because SelectListItem is no longer picking the selected value correctly. To fix it, I changed the usage of EditorFor for a "manual" approach:

        <select id="Role" class="form-control">
            @foreach (var role in ViewBag.Roles)
            {
                if (Model.Roles.First().RoleId == role.Value)
                {
                    <option value="@role.Value" selected>@role.Text</option>
                }
                else
                {
                    <option value="@role.Value">@role.Text</option>
                }
            }
        </select>

Hope it helps someone.


问:
getResource on OpenJdk throws java.nio.file.NoSuchFileException
Application: Spring Boot,

Image: OpenJDK 8,

PaaS: Openshift,

Package: jar,

Error: No such file error. java.nio.file.NoSuchFileException

File Location: /servicename/src/main/resources/cert/trust.cer

Error Location: String certs = readFile((trustCertPath).getPath(), Charset.defaultCharset());

Error Location after Update 1: try (InputStream is = classloader.getResourceAsStream(resourcePath)) is null.

I have used cert/trust.cer as path. Since it did not work I gave it a try with /cert/trust.cer, trust.cer, ./cert/trust.cer. I was able to run this class on local using Windows (/cert/trust.cer) but fails from command line and also fails when deployed obviosly.

Update 1: I am using getResourceAsStream(cert/trust.cer). Inputstream is results to null.

```<code>public class CertsUtility implements InitializingBean {
public static final Logger logger = LoggerFactory.getLogger("CertsUtility");
private String keystorePaaS;
private String keystorePass;
private String CertPath = "cert/trust.cer";

public void setKeystorePaaS(String keystorePaaS) {
    this.keystorePaaS = keystorePaaS;
}

public void setKeystorePass(String keystorePass) {
    this.keystorePass = keystorePass;
}

static File getPath(String path) {
    URL url = CertsUtility.class.getClass().getResource(path);
    if (url != null) {
        File file = new File(url.getPath());
        return file;
    } else {
        File file = new File(path);
        return file;
    }
}

static String getResourceFileAsString(String resourcePath) throws IOException {
    ClassLoader classloader = ClassLoader.getSystemClassLoader();
    try (InputStream is = classloader.getResourceAsStream(resourcePath)) {
        if (is == null)
            return null;
        try (InputStreamReader isr = new InputStreamReader(is)) {
            BufferedReader reader = new BufferedReader(isr);
            String targetString = reader.lines().collect(Collectors.joining());
            return targetString;
        }
    }

}

void genIndividualandLoad() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException,
        CertificateException, IOException, InterruptedException {
    try {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream fileInputStream = new FileInputStream(keystorePaaS);
        keyStore.load(fileInputStream, keystorePass.toCharArray());
        fileInputStream.close();
        String certs = readFile((trustCertPath).getPath(), Charset.defaultCharset());
        String[] certificates = certs.split("(?<=-----END CERTIFICATE-----\n)");

        for (int i = 0; i < certificates.length - 1; i++) {
            String individualName = getPath(CertPath).getParent() + i + ".cer";
            try (FileOutputStream outputStream = new FileOutputStream(individualName)) {
                byte[] strToBytes = certificates[i].getBytes();
                outputStream.write(strToBytes);
                try (InputStream inStream = new FileInputStream(individualName)) {
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
                    keyStore.setCertificateEntry("" + i, cert);
                }
                FileOutputStream fileOutputStream = new FileOutputStream(getPath(keystorePaaS));
                keyStore.store(fileOutputStream, keystorePass.toCharArray());
                fileOutputStream.close();
                outputStream.close();
            }
        }
    } catch (KeyStoreException e) {
        logger.error("| genIndividualandLoad() | Keystore exception occurred", e);
    } catch (FileNotFoundException e) {
        logger.error("| genIndividualandLoad() | File not found exception occurred", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("| genIndividualandLoad() | Algorithm related exception occurred", e);
    } catch (CertificateException e) {
        logger.error("| genIndividualandLoad() | X.509 Certificate exception occurred", e);
    } catch (IOException e) {
        logger.error("| genIndividualandLoad() | I/O exception occured", e);
    }
}

public void afterPropertiesSet() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException,
        CertificateException, IOException, InterruptedException {
    genIndividualandLoad();
}
</code>```

}

答:
You're trying to load the cert as a file, which will work if it actually is a file in your file system (i. e. in your local workspace), but not when the cert is nested inside your JAR file.

Rather you need to do something akin to

```<code>getClass().getClassLoader().getResourceAsStream("cert/trust.cer");
</code>```

and then read from the resulting stream.

Body:
Application: Spring Boot,

Image: OpenJDK 8,

PaaS: Openshift,

Package: jar,

Error: No such file error. java.nio.file.NoSuchFileException

File Location: /servicename/src/main/resources/cert/trust.cer

Error Location: String certs = readFile((trustCertPath).getPath(), Charset.defaultCharset());

Error Location after Update 1: try (InputStream is = classloader.getResourceAsStream(resourcePath)) is null.

I have used cert/trust.cer as path. Since it did not work I gave it a try with /cert/trust.cer, trust.cer, ./cert/trust.cer. I was able to run this class on local using Windows (/cert/trust.cer) but fails from command line and also fails when deployed obviosly.

Update 1: I am using getResourceAsStream(cert/trust.cer). Inputstream is results to null.

public class CertsUtility implements InitializingBean {
public static final Logger logger = LoggerFactory.getLogger("CertsUtility");
private String keystorePaaS;
private String keystorePass;
private String CertPath = "cert/trust.cer";

public void setKeystorePaaS(String keystorePaaS) {
    this.keystorePaaS = keystorePaaS;
}

public void setKeystorePass(String keystorePass) {
    this.keystorePass = keystorePass;
}

static File getPath(String path) {
    URL url = CertsUtility.class.getClass().getResource(path);
    if (url != null) {
        File file = new File(url.getPath());
        return file;
    } else {
        File file = new File(path);
        return file;
    }
}

static String getResourceFileAsString(String resourcePath) throws IOException {
    ClassLoader classloader = ClassLoader.getSystemClassLoader();
    try (InputStream is = classloader.getResourceAsStream(resourcePath)) {
        if (is == null)
            return null;
        try (InputStreamReader isr = new InputStreamReader(is)) {
            BufferedReader reader = new BufferedReader(isr);
            String targetString = reader.lines().collect(Collectors.joining());
            return targetString;
        }
    }

}

void genIndividualandLoad() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException,
        CertificateException, IOException, InterruptedException {
    try {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream fileInputStream = new FileInputStream(keystorePaaS);
        keyStore.load(fileInputStream, keystorePass.toCharArray());
        fileInputStream.close();
        String certs = readFile((trustCertPath).getPath(), Charset.defaultCharset());
        String[] certificates = certs.split("(?<=-----END CERTIFICATE-----\n)");

        for (int i = 0; i < certificates.length - 1; i++) {
            String individualName = getPath(CertPath).getParent() + i + ".cer";
            try (FileOutputStream outputStream = new FileOutputStream(individualName)) {
                byte[] strToBytes = certificates[i].getBytes();
                outputStream.write(strToBytes);
                try (InputStream inStream = new FileInputStream(individualName)) {
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
                    keyStore.setCertificateEntry("" + i, cert);
                }
                FileOutputStream fileOutputStream = new FileOutputStream(getPath(keystorePaaS));
                keyStore.store(fileOutputStream, keystorePass.toCharArray());
                fileOutputStream.close();
                outputStream.close();
            }
        }
    } catch (KeyStoreException e) {
        logger.error("| genIndividualandLoad() | Keystore exception occurred", e);
    } catch (FileNotFoundException e) {
        logger.error("| genIndividualandLoad() | File not found exception occurred", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("| genIndividualandLoad() | Algorithm related exception occurred", e);
    } catch (CertificateException e) {
        logger.error("| genIndividualandLoad() | X.509 Certificate exception occurred", e);
    } catch (IOException e) {
        logger.error("| genIndividualandLoad() | I/O exception occured", e);
    }
}

public void afterPropertiesSet() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException,
        CertificateException, IOException, InterruptedException {
    genIndividualandLoad();
}

}

Body:
You're trying to load the cert as a file, which will work if it actually is a file in your file system (i. e. in your local workspace), but not when the cert is nested inside your JAR file.

Rather you need to do something akin to

getClass().getClassLoader().getResourceAsStream("cert/trust.cer");

and then read from the resulting stream.


问:
jquery file upload plugin
i have to use the jquery file upload plugin from this link. What I am looking for is some basic syntax to call this plugin, perform start, upload, delete etc. operations. The wiki is not very helpful which is why i am posting this question here. Please help.</p>

答: Have you looked at their documentation page? Yes the jquery page is light on details, but you can find much more information here.</p>

Title: jquery file upload plugin


问:
Chrome 83: Change colors of new form styling
With the new Chrome update Chrome is displaying improved default form styling.
According to the post I would say it should be possible to change this form theme to match the color set of a website.

We were going for beautiful, webby, and neutral. We hope that every design system would see a bit of themselves in the new designs and easily imagine how they might be adapted for their own branding.

I have spend the last few hours searching and trying to get rid of the default blue color that has a very bad contrast with rest of my website. Aside from using '-webkit-appearance: none;' and restyling things like checkboxes myself I'm not sure if it's possible.

Does anyone experience this issue as well or have a solution or documentation I'm missing?

答:
It's so ugly one cannot just update the style of checkboxes :( So you need to really hide native checkbox and insert your custom element using :before

Here is the snippet using Font Awesome (free icon for checkmark \f00c)

input[type="checkbox"] {
  font-family: 'Font Awesome 5 Free';
  font-weight: 900;
  /* Show the border to simulate the square */
  border: 1px solid #ccc;
  /* Hide the native checkbox */
  -webkit-appearance: none;
  width: 15px;
  height: 15px;
}

input[type="checkbox"]:before {
  /* Show some fake element to keep the space for empty "square" */
  content: "\f0c8";
  color: transparent;
}

input[type="checkbox"]:checked:before {
  /* Show actual checkmark */
  content: "\f00c";
  color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://kit.fontawesome.com/59ba4e0c1b.js"></script>
<input type="checkbox" checked="">I'm checked
<br>
<input type="checkbox">I'm unchecked</code>```

And here is the one with pure Unicode (which still requires some polishing to avoid jumping)

input[type="checkbox"] {
  /* Show the border to simulate the square */
  border: 1px solid #ccc;
  /* Hide the native checkbox */
  -webkit-appearance: none;
  width: 15px;
  height: 15px;
}

input[type="checkbox"]:before {
  /* Show some fake element to keep the space for empty "square" */
  content: "w";
  color: transparent;
}

input[type="checkbox"]:checked:before {
  /* Show actual checkmark */
  content: "✓";
  color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" checked="">I'm checked
<br>
<input type="checkbox">I'm unchecked</code>```

Body:
It's so ugly one cannot just update the style of checkboxes :( So you need to really hide native checkbox and insert your custom element using :before

Here is the snippet using Font Awesome (free icon for checkmark \f00c)

input[type="checkbox"] {
  font-family: 'Font Awesome 5 Free';
  font-weight: 900;
  /* Show the border to simulate the square */
  border: 1px solid #ccc;
  /* Hide the native checkbox */
  -webkit-appearance: none;
  width: 15px;
  height: 15px;
}

input[type="checkbox"]:before {
  /* Show some fake element to keep the space for empty "square" */
  content: "\f0c8";
  color: transparent;
}

input[type="checkbox"]:checked:before {
  /* Show actual checkmark */
  content: "\f00c";
  color: black;
}

<script src="https://kit.fontawesome.com/59ba4e0c1b.js"></script>
<input type="checkbox" checked="">I'm checked
<br>
<input type="checkbox">I'm unchecked

And here is the one with pure Unicode (which still requires some polishing to avoid jumping)

input[type="checkbox"] {
  /* Show the border to simulate the square */
  border: 1px solid #ccc;
  /* Hide the native checkbox */
  -webkit-appearance: none;
  width: 15px;
  height: 15px;
}

input[type="checkbox"]:before {
  /* Show some fake element to keep the space for empty "square" */
  content: "w";
  color: transparent;
}

input[type="checkbox"]:checked:before {
  /* Show actual checkmark */
  content: "✓";
  color: black;
}

<input type="checkbox" checked="">I'm checked
<br>
<input type="checkbox">I'm unchecked


问:
Matplotlib : How to plot two bar plots with the same x/y axes but one start over the other along y axis
I'm trying to plot two bar plots int the same figure. In the code below the plots are one behind the other because they laid along y axis at 0.

```<code>import matplotlib.pyplot as plt
import numpy as np

y1=np.array([1,2,3,4,5])
x1=np.array([1,2,3,2,1])

x2=np.array([1,2,3,2,1])
y2=np.array([6,7,8,9,10])
plt.bar(y1,x1)
plt.bar(y2,x2)
</code>```

I would the orange bar plot starts from coordinates: (x=6, y=3). So orange bar plot should be over the blue  plot and in the same figure.

答:
Just provide the value of the bottom for the second bar plot using bottom=3

```<code>plt.bar(y2,x2, bottom=3)
</code>```

You can also make it more general using bottom=max(x2)

For horizontal bar chart Use left=3

```<code>plt.barh(y2,x2,left=3)
</code>```

Body:
I'm trying to plot two bar plots int the same figure. In the code below the plots are one behind the other because they laid along y axis at 0.

import matplotlib.pyplot as plt
import numpy as np

y1=np.array([1,2,3,4,5])
x1=np.array([1,2,3,2,1])

x2=np.array([1,2,3,2,1])
y2=np.array([6,7,8,9,10])
plt.bar(y1,x1)
plt.bar(y2,x2)

I would the orange bar plot starts from coordinates: (x=6, y=3). So orange bar plot should be over the blue  plot and in the same figure.

Body:
Just provide the value of the bottom for the second bar plot using bottom=3

plt.bar(y2,x2, bottom=3)

You can also make it more general using bottom=max(x2)

For horizontal bar chart Use left=3

plt.barh(y2,x2,left=3)


问:
Understanding Array.isArray Polyfill
I was going through the polyfill of Array.isArray method on MDN, and this is what I found:

```<code>if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}
</code>```

While this works, I wonder why MDN hasn't listed the following as the polyfill for isArray?

```<code>if (!Array.isArray) {
  Array.isArray = function(arg) {
    return arg.constructor === Array;
  };
}
</code>```

Above code is a bit short and simpler. I wonder if there is any advantage of using MDN's implementation as compared to above one?

答:
The most important reason that makes the MDN polyfill a safe one to use is that an array is an exotic object. The best way to differentiate an exotic object would be through the use of an exotic feature related to that object – that is to say, an exotic property of the exotic object.

If you look at the specification of the Object.prototype.toString method, you will find that it uses the abstract operation isArray, which checks for exotic array objects.

On the other hand look at the specification of the constructor property. It is not an exotic property of the array, and so javascript code can change it easily.

```<code>const x = [];
x.constructor = Object
</code>```

In fact, the constructor property is more intended for meta programming. You could – in es5 – create subclasses without touching the constructor property.

Now, here are things that can go wrong with your implementation:

```<code>const customIsArray = function(arg) {
    return arg.constructor === Array;
};

// 1) won't work with subclasses of Array

class CustomArray extends Array {
    // ...
}

const customArray = new CustomArray()
customIsArray(customArray) // false
Array.isArray(customArray) // true

// 2) won't work across different realms (iframes, web workers, service workers ... if we are speaking about the browser environment)

const iframe = document.createElement('iframe')
document.body.appendChild(iframe)
const IframeArray = iframe.contentWindow.Array;
const iframeArray = new IframeArray();
customIsArray(iframeArray) // false
Array.isArray(iframeArray) // true

// 3) won't work with few edge cases like (customIsArray will return true, while Array.isArray will return false)

const fakeArray1 = { __proto__: Array.prototype }
const fakeArray2 = { constructor: Array }

customIsArray(fakeArray1) // true
Array.isArray(fakeArray1) // false

customIsArray(fakeArray2) // true
Array.isArray(fakeArray2) // false

</code>```

Title: Understanding Array.isArray Polyfill

Body:
I was going through the polyfill of Array.isArray method on MDN, and this is what I found:

if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}

While this works, I wonder why MDN hasn't listed the following as the polyfill for isArray?

if (!Array.isArray) {
  Array.isArray = function(arg) {
    return arg.constructor === Array;
  };
}

Above code is a bit short and simpler. I wonder if there is any advantage of using MDN's implementation as compared to above one?

Body:
The most important reason that makes the MDN polyfill a safe one to use is that an array is an exotic object. The best way to differentiate an exotic object would be through the use of an exotic feature related to that object – that is to say, an exotic property of the exotic object.

If you look at the specification of the Object.prototype.toString method, you will find that it uses the abstract operation isArray, which checks for exotic array objects.

On the other hand look at the specification of the constructor property. It is not an exotic property of the array, and so javascript code can change it easily.

const x = [];
x.constructor = Object

In fact, the constructor property is more intended for meta programming. You could – in es5 – create subclasses without touching the constructor property.

Now, here are things that can go wrong with your implementation:

const customIsArray = function(arg) {
    return arg.constructor === Array;
};

// 1) won't work with subclasses of Array

class CustomArray extends Array {
    // ...
}

const customArray = new CustomArray()
customIsArray(customArray) // false
Array.isArray(customArray) // true

// 2) won't work across different realms (iframes, web workers, service workers ... if we are speaking about the browser environment)

const iframe = document.createElement('iframe')
document.body.appendChild(iframe)
const IframeArray = iframe.contentWindow.Array;
const iframeArray = new IframeArray();
customIsArray(iframeArray) // false
Array.isArray(iframeArray) // true

// 3) won't work with few edge cases like (customIsArray will return true, while Array.isArray will return false)

const fakeArray1 = { __proto__: Array.prototype }
const fakeArray2 = { constructor: Array }

customIsArray(fakeArray1) // true
Array.isArray(fakeArray1) // false

customIsArray(fakeArray2) // true
Array.isArray(fakeArray2) // false


问:
Alternative to xamarin method GetOrCreateRenderer()
Trying to use method GetOrCreateRenderer() but visual studios says it doesn't contains a definition for that. Maybe it was removed on newer versions or I'm not using the right namespace?

```<code>loadingIndicatorPage.Parent = Xamarin.Forms.Application.Current.MainPage;
loadingIndicatorPage.Layout(new Rectangle(0, 0,Xamarin.Forms.Application.Current.MainPage.Width,
Xamarin.Forms.Application.Current.MainPage.Height));
var renderer = loadingIndicatorPage.GetOrCreateRenderer(); //not recognized
_nativeView = renderer.View;
</code>```

答:
GetOrCreateRenderer() is deprecated, now use:

Platform.CreateRendererWithContext(view,context);

Body:
Trying to use method GetOrCreateRenderer() but visual studios says it doesn't contains a definition for that. Maybe it was removed on newer versions or I'm not using the right namespace?

loadingIndicatorPage.Parent = Xamarin.Forms.Application.Current.MainPage;
loadingIndicatorPage.Layout(new Rectangle(0, 0,Xamarin.Forms.Application.Current.MainPage.Width,
Xamarin.Forms.Application.Current.MainPage.Height));
var renderer = loadingIndicatorPage.GetOrCreateRenderer(); //not recognized
_nativeView = renderer.View;


问:
Does Mysql2 for Node.Js require running connect() on mysql.CreateConnection before executing queires
I recently migrated a node.js project from mysqljs to mysql2 (https://www.npmjs.com/package/mysql2) because it had some additional feature that I need. For my database calls, I am exporting a connection that was created by running mysql.createConnection({CONFIG}) that is then imported by other files and then queries are executed using the execute command.

Previous to my transition, in the file where I set up my database connection I had this:

```<code>const mysql = require("mysql2");
const dbConfig = require("../config/db.config");

const connection = mysql.createConnection({
    host: dbConfig.HOST,
    user: dbConfig.USER,
    password: dbConfig.PASSWORD,
    database: dbConfig.DB,
    port: dbConfig.PORT
});

connection.connect(error => {
    if (error) throw error;
    console.log("DB connect")
});

module.exports = connection;
</code>```

My code runs fun without the connection.connect function. Does removing it have any impact on performance, or does mysql2 maintain an open connection regardless or is the creation of the connection negligible? Is it better to keep this line prior to the export or remove it?

答: If you look into the source here, you will see that calling createConnection already performs a handshake with the DB and the connect method is used just to pass any errors that might have occurred when you tried to create the connection. The createConnection method doesn't throw or accepts an error calback. So I would suggest it is safer to keep calling it when creating your connection.

Body:
I recently migrated a node.js project from mysqljs to mysql2 (https://www.npmjs.com/package/mysql2) because it had some additional feature that I need. For my database calls, I am exporting a connection that was created by running mysql.createConnection({CONFIG}) that is then imported by other files and then queries are executed using the execute command.

Previous to my transition, in the file where I set up my database connection I had this:

const mysql = require("mysql2");
const dbConfig = require("../config/db.config");

const connection = mysql.createConnection({
    host: dbConfig.HOST,
    user: dbConfig.USER,
    password: dbConfig.PASSWORD,
    database: dbConfig.DB,
    port: dbConfig.PORT
});

connection.connect(error => {
    if (error) throw error;
    console.log("DB connect")
});

module.exports = connection;

My code runs fun without the connection.connect function. Does removing it have any impact on performance, or does mysql2 maintain an open connection regardless or is the creation of the connection negligible? Is it better to keep this line prior to the export or remove it?


问:
Draw shapes with delay
I know there are already hundreds of threads but I just cant understand it..
I have this very simple class thats drawing a grid. I would like to add like a 0.2 second delay after each square. Thread.sleep doesnt work. What is the simplest way?</p>

```<code>    public Screen() {
        repaint();
    }
    public void paint(Graphics g) {

        for(int i = 0; i < 9; i++) {
            for(int j = 0; j < 9; j++) {
                g.drawRect(50 * i, 50 * j, 50, 50);
                //Add delay
            }
        }
    }
</code>```

答:
The simplest way to achieve delayed drawing is by using a Swing Timer, which is a class that won't block the EDT when executed. This will allow you to create a delay without blocking your UI (and making everything appear at once).

You'll have a single JPanel that's going to handle the painting in the paintComponent(...) method and not paint(...) as you did in your code above. This JPanel will repaint every Rectangle shape from the Shape API.

```<code>import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class DelayedDrawing {
    private JFrame frame;
    private JPanel pane;
    private Timer timer;
    private int xCoord = 0;
    private int yCoord = 0;
    private static final int GAP = 10;
    private static final int WIDTH_HEIGHT = 10;
    private static final int ROWS = 5;
    private static final int COLS = 5;

    private List<Rectangle> rectangles;

    @SuppressWarnings("serial")
    private void createAndShowGUI() {
        //We create the JFrame
        frame = new JFrame(this.getClass().getSimpleName());
        //We create a list of Rectangles from the Shape API
        rectangles = new ArrayList<>();
        createRectangle();

        //Creates our JPanel that's going to draw every rectangle
        pane = new JPanel() {
            //Specifies the size of our JPanel
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(150, 150);
            }

            //This is where the "magic" happens, it iterates over our list and repaints every single Rectangle in it
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                for (Rectangle r : rectangles) {
                    System.out.println(r.x + " " + r.y);
                    g2d.draw(r);
                }
            }
        };

        //This starts our Timer
        timer = new Timer(200, listener);
        timer.setInitialDelay(1000);
        timer.start();

        //We add everything to the frame
        frame.add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    //Creates a new Rectangle and adds it to the List
    private void createRectangle() {
        Rectangle r = new Rectangle(xCoord * WIDTH_HEIGHT + GAP, yCoord * WIDTH_HEIGHT + GAP, WIDTH_HEIGHT, WIDTH_HEIGHT);
        rectangles.add(r);
    }

    //This will be executed everytime the Timer is fired
    private ActionListener listener = e -> {
        if (xCoord < ROWS) {
            if (yCoord < COLS) {
                yCoord++;
            } else {
                yCoord = 0;
                xCoord++;
                if (xCoord == ROWS) {
                    timer.stop();
                    return;
                }
            }
        }
        createRectangle();
        pane.repaint();
    };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new DelayedDrawing()::createAndShowGUI);
    }
}
</code>```

Title: Draw shapes with delay

Body:
I know there are already hundreds of threads but I just cant understand it..
I have this very simple class thats drawing a grid. I would like to add like a 0.2 second delay after each square. Thread.sleep doesnt work. What is the simplest way?

    public Screen() {
        repaint();
    }
    public void paint(Graphics g) {

        for(int i = 0; i < 9; i++) {
            for(int j = 0; j < 9; j++) {
                g.drawRect(50 * i, 50 * j, 50, 50);
                //Add delay
            }
        }
    }

Body:
The simplest way to achieve delayed drawing is by using a Swing Timer, which is a class that won't block the EDT when executed. This will allow you to create a delay without blocking your UI (and making everything appear at once).

You'll have a single JPanel that's going to handle the painting in the paintComponent(...) method and not paint(...) as you did in your code above. This JPanel will repaint every Rectangle shape from the Shape API.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class DelayedDrawing {
    private JFrame frame;
    private JPanel pane;
    private Timer timer;
    private int xCoord = 0;
    private int yCoord = 0;
    private static final int GAP = 10;
    private static final int WIDTH_HEIGHT = 10;
    private static final int ROWS = 5;
    private static final int COLS = 5;

    private List<Rectangle> rectangles;

    @SuppressWarnings("serial")
    private void createAndShowGUI() {
        //We create the JFrame
        frame = new JFrame(this.getClass().getSimpleName());
        //We create a list of Rectangles from the Shape API
        rectangles = new ArrayList<>();
        createRectangle();

        //Creates our JPanel that's going to draw every rectangle
        pane = new JPanel() {
            //Specifies the size of our JPanel
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(150, 150);
            }

            //This is where the "magic" happens, it iterates over our list and repaints every single Rectangle in it
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                for (Rectangle r : rectangles) {
                    System.out.println(r.x + " " + r.y);
                    g2d.draw(r);
                }
            }
        };

        //This starts our Timer
        timer = new Timer(200, listener);
        timer.setInitialDelay(1000);
        timer.start();

        //We add everything to the frame
        frame.add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    //Creates a new Rectangle and adds it to the List
    private void createRectangle() {
        Rectangle r = new Rectangle(xCoord * WIDTH_HEIGHT + GAP, yCoord * WIDTH_HEIGHT + GAP, WIDTH_HEIGHT, WIDTH_HEIGHT);
        rectangles.add(r);
    }

    //This will be executed everytime the Timer is fired
    private ActionListener listener = e -> {
        if (xCoord < ROWS) {
            if (yCoord < COLS) {
                yCoord++;
            } else {
                yCoord = 0;
                xCoord++;
                if (xCoord == ROWS) {
                    timer.stop();
                    return;
                }
            }
        }
        createRectangle();
        pane.repaint();
    };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new DelayedDrawing()::createAndShowGUI);
    }
}