问:
Javascript Import Don't Work In Visual Studio Code
I can't import anything in my javascript files of my website, I've tried many things but it doesn't work.

So I want to import a .json file to a .js file using the import key word but it doesn't work. Another problem is that Visual Studio Code doesn't show me an error but the console does...

main.js import part

```<code>import dropDownList from "./navigationList.json"; //This is line number 1

console.log(dropDownList.shop.kits);
</code>```

navigationList.json file

```<code>{
    "shop": {
        "kits": "DIY Physics Kits",
        "merch": "Merchendise"
    },

    "learn": {
        "first-sub": "Mechanics",
        "second-sub": "Miscellaneous"
    }
}
</code>```

Error the console is showing:

mainJS.js:1 Uncaught SyntaxError: Unexpected identifier

The console says there is an Uncaught SyntaxError with my import and this causing me to make my code long and without import which sucks.
Please help me

答:
The import syntax is part of ES6 modules. It looks like you are using Node.js, which does not include support for ES6 modules by default. However, Node.js has experimental support for ES6 modules.

Rename the file to have an .mjs extension:

```<code>mv mainJS.js mainJS.mjs
</code>```

Run it with the --experimental-modules flag:

```<code>node --experimental-modules mainJS.mjs
</code>```

I tested this with your code, and it works:

```<code>% node --experimental-modules main.mjs
(node:73044) ExperimentalWarning: The ESM module loader is experimental.
DIY Physics Kits
</code>```

At the time of this writing, I am using Node.js v12.3.1:

```<code>% node --version
v12.3.1
</code>```

Alternatively, you can transpile your code with a tool like Babel, which changes imports to requires.

Body:
I can't import anything in my javascript files of my website, I've tried many things but it doesn't work.

So I want to import a .json file to a .js file using the import key word but it doesn't work. Another problem is that Visual Studio Code doesn't show me an error but the console does...

main.js import part

import dropDownList from "./navigationList.json"; //This is line number 1

console.log(dropDownList.shop.kits);

navigationList.json file

{
    "shop": {
        "kits": "DIY Physics Kits",
        "merch": "Merchendise"
    },

    "learn": {
        "first-sub": "Mechanics",
        "second-sub": "Miscellaneous"
    }
}

Error the console is showing:

mainJS.js:1 Uncaught SyntaxError: Unexpected identifier

The console says there is an Uncaught SyntaxError with my import and this causing me to make my code long and without import which sucks.
Please help me

Body:
The import syntax is part of ES6 modules. It looks like you are using Node.js, which does not include support for ES6 modules by default. However, Node.js has experimental support for ES6 modules.

Rename the file to have an .mjs extension:

mv mainJS.js mainJS.mjs

Run it with the --experimental-modules flag:

node --experimental-modules mainJS.mjs

I tested this with your code, and it works:

% node --experimental-modules main.mjs
(node:73044) ExperimentalWarning: The ESM module loader is experimental.
DIY Physics Kits

At the time of this writing, I am using Node.js v12.3.1:

% node --version
v12.3.1

Alternatively, you can transpile your code with a tool like Babel, which changes imports to requires.


来源: stackexchange

问:
SSH from gitlab-ci docker fails on "SSH2_MSG_KEX_ECDH_REPLY"
I'm trying to SSH from a Docker deployment container running in GitLab CI, to a remote webserver. It did successfully connect, once, the first time I tried. Now it's continually failing: the last two lines of the debug output (the full output is below) are:

```<code>debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
Connection closed by ********** port 22
</code>```

The deploy task first copies the SSH private key from a GitLab CI 'secret variable' (the pubkey is of course in ~/.ssh/authorized_keys on the remote). The full deploy task is defined in gitlab-ci.yml as:

```<code>.deploy: &import_deploy
    stage: deploy
    image: **********
    tags: [ek-docker]
    before_script:
        # install openssh & rsync
        - apk update && apk --no-cache add rsync openssh
        # copy private key from GitLab secret variable to container
        - mkdir -p ~/.ssh
        - chmod 700 ~/.ssh
        - eval $(ssh-agent -s)
        - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
        - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
    script:
        - ssh -vvv **********@********** 'bash -s' < ./conf/$MY_ENV_NAME/start.sh

    deploy staging:
    <<: *import_deploy
    variables:
        MY_ENV_NAME: "staging"
    only:
        - staging
    environment:
        name: staging
</code>```

The output logged from SSH is:

```<code>OpenSSH_7.7p1, LibreSSL 2.7.4
debug1: Reading configuration data /root/.ssh/config
debug1: /root/.ssh/config line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug2: resolve_canonicalize: hostname ********** is address
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to ********** [**********] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_xmss type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.7
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.6
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.6 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to **********:22 as '**********'
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
Connection closed by ********** port 22
ERROR: Job failed: exit code 1
</code>```

I am way out of my depth here, and Googling suggests two possible causes. The first is something network-based, with changing the... MTU? as the potential fix. That sounds scary, so I'm focussing on the second, a mismatch in key exchange algorithms. It seems plausible: there doesn't seem to be a common value between "KEX algorithms" and "host key algorithms" in the output above. When it did connect that first time, the output was

"Warning: Permanently added '**********' (ECDSA) to the list of known
  hosts."

I tried specifying the algorithm via ssh -o KexAlgorithms=ecdh-sha2-nistp521 (and a couple other likely-looking candidates) but that just raised an error that the algorithm wasn't supported.

As is now clear, I have NO idea what I'm doing. Can anyone even suggest what might be the cause of the issue, from the SSH output above?

答:
I had the same issue I have added this option to ssh and then problem solved:</p>

```<code>ssh -o KexAlgorithms=ecdh-sha2-nistp521 192.168.1.100
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to SSH from a Docker deployment container running in GitLab CI, to a remote webserver. It did successfully connect, once, the first time I tried. Now it's continually failing: the last two lines of the debug output (the full output is below) are:

debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
Connection closed by ********** port 22

The deploy task first copies the SSH private key from a GitLab CI 'secret variable' (the pubkey is of course in ~/.ssh/authorized_keys on the remote). The full deploy task is defined in gitlab-ci.yml as:

.deploy: &import_deploy
    stage: deploy
    image: **********
    tags: [ek-docker]
    before_script:
        # install openssh & rsync
        - apk update && apk --no-cache add rsync openssh
        # copy private key from GitLab secret variable to container
        - mkdir -p ~/.ssh
        - chmod 700 ~/.ssh
        - eval $(ssh-agent -s)
        - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config
        - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
    script:
        - ssh -vvv **********@********** 'bash -s' < ./conf/$MY_ENV_NAME/start.sh

    deploy staging:
    <<: *import_deploy
    variables:
        MY_ENV_NAME: "staging"
    only:
        - staging
    environment:
        name: staging

The output logged from SSH is:

OpenSSH_7.7p1, LibreSSL 2.7.4
debug1: Reading configuration data /root/.ssh/config
debug1: /root/.ssh/config line 1: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug2: resolve_canonicalize: hostname ********** is address
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to ********** [**********] port 22.
debug1: Connection established.
debug1: permanently_set_uid: 0/0
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_xmss type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_xmss-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.7
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.6
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.6 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to **********:22 as '**********'
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
Connection closed by ********** port 22
ERROR: Job failed: exit code 1

I am way out of my depth here, and Googling suggests two possible causes. The first is something network-based, with changing the... MTU? as the potential fix. That sounds scary, so I'm focussing on the second, a mismatch in key exchange algorithms. It seems plausible: there doesn't seem to be a common value between "KEX algorithms" and "host key algorithms" in the output above. When it did connect that first time, the output was

"Warning: Permanently added '**********' (ECDSA) to the list of known
  hosts."

I tried specifying the algorithm via ssh -o KexAlgorithms=ecdh-sha2-nistp521 (and a couple other likely-looking candidates) but that just raised an error that the algorithm wasn't supported.

As is now clear, I have NO idea what I'm doing. Can anyone even suggest what might be the cause of the issue, from the SSH output above?

Body:
I had the same issue I have added this option to ssh and then problem solved:

ssh -o KexAlgorithms=ecdh-sha2-nistp521 192.168.1.100


问:
object returning old state
I want to return current state in function, which is returning object.

```<code>
myFunction = () => {
        return (
            myObject = {
                object: this.state.variable
            }
        )
    }
</code>```

```<code>render() {
   return (

    <TouchableOpacity
       onPress={() => {this.setState({ variable: 2 }),  () => console.log(myFunction())}>

    </TouchableOpacity> )
}

</code>```

Function is returning state, which was default. I want to return new state, which was setted.

答:
Try this one:</p>

```<code>render() {
  return (
    <TouchableOpacity onPress={() => {
        this.setState({ variable: 2 },
        ()=>console.log(this.myFunction()));
    }>

    </TouchableOpacity> )
}
</code>```

Title: object returning old state

Body:
I want to return current state in function, which is returning object.

myFunction = () => {
        return (
            myObject = {
                object: this.state.variable
            }
        )
    }

render() {
   return (

    <TouchableOpacity
       onPress={() => {this.setState({ variable: 2 }),  () => console.log(myFunction())}>

    </TouchableOpacity> )
}

Function is returning state, which was default. I want to return new state, which was setted.

Body:
Try this one:

render() {
  return (
    <TouchableOpacity onPress={() => {
        this.setState({ variable: 2 },
        ()=>console.log(this.myFunction()));
    }>

    </TouchableOpacity> )
}


问:
GhostScript PDF to PCL Black and White with No Grayscale
I have a process to convert PDFs to PCL for automatic printing, but the quality is not good. Here's the test code that I have to show the poor quality:

```<code>gs -dBATCH -dNOPAUSE -q -sDEVICE=ljetplus -sOutputFile=grayscaletest.pcl -f grayscaletest.pdf
</code>```

Here's what grayscaletest.pdf looks like before:  And what grayscaletest.pcl looks like after:

I realize that it's doing this because of the device ljetplus, but that's the only device that I have found that will work for what I need. So, I want to convert all grays to black. I have tried the solution found here (GitHub) and here (superuser), but it did nothing. I can't even get this solution to work from PDF to PDF, it just stays the same.

GhostScript version is 9.06. Any help either improving the quality using ljetplus, or just converting everything to black and white without grayscale would be appreciated.

答:
Well that's a black and white output, its been halftoned to produce 1-bit output from 8-bit input. No matter what you do, if your device only supports 1-bit output then you're always going to have to apply some kind of screening to represent grayscale or colour.

You don't give any clues as to why ljetplus is the only device you can use. Without knowing why its going to be hard to offer any concrete advice.

However....

First thing is to update your version of Ghostscript. The current version is 9.27, the one you are using is > 6 years old.

The screen looks coarse, the default resolution of the ljetplus is 300 dpi, is that correct for your printer ? If not you will want to set a higher resolution, it'll give you a finer screen. Most PCL devices are 600 dpi or better these days.

Assuming that your PDF file doesn't contain a halftone, the next thing to do is to experiment with the screening options available in Ghostscript. You could try the switches described here:

https://www.ghostscript.com/doc/9.27/Use.htm#Rendering_parameters

You can also use PostScript screening, but that's harder to implement unless you understand PostScript already. There are also stochastic screens available in Ghostscript but not knowing how comfortable you are with PostScript I don't want to go down that route.

Yyou could of course use Ghostscript to render to a high resolution bitmap, dither that to monochrome with image manipulation too of your choice and then output it back to PDF or PostScript, or an image format that Ghostscript has a program to read (eg viewpbm.ps in the ghostpdl/lib directory).

ImageMagick can probably do all the steps above for you, then once you have a monochrome input file you can simply run it through Ghostscript to get a PCL output file.

Body:
I have a process to convert PDFs to PCL for automatic printing, but the quality is not good. Here's the test code that I have to show the poor quality:

gs -dBATCH -dNOPAUSE -q -sDEVICE=ljetplus -sOutputFile=grayscaletest.pcl -f grayscaletest.pdf

Here's what grayscaletest.pdf looks like before:  And what grayscaletest.pcl looks like after:

I realize that it's doing this because of the device ljetplus, but that's the only device that I have found that will work for what I need. So, I want to convert all grays to black. I have tried the solution found here (GitHub) and here (superuser), but it did nothing. I can't even get this solution to work from PDF to PDF, it just stays the same.

GhostScript version is 9.06. Any help either improving the quality using ljetplus, or just converting everything to black and white without grayscale would be appreciated.


问:
tf.keras.metrics.SpecificityAtSensitivity num_thresholds interpretation
I'm trying to get my head around tf.keras.metrics.SensitivityAtSpecificity. I'm fine with the concept of sensity and specificity in isolation, but I'm unsure how the two are related in this single metric.

More specifically, I'm unsure how to interpret the num_thresholds argument. The example in documentation has num_thresholds=1. Setting num_thresholds greater than 1 with the same input data seems to always return a metric value of 1.0.

def print_metric_value(num_thresholds):
    # other values based on docs example
    m = tf.keras.metrics.SensitivityAtSpecificity(
        0.4, num_thresholds=num_thresholds)
    m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9])
    print('Result with num_thresholds = %d: %.1f' %
          (num_thresholds, m.result().numpy()))

print_metric_value(1)    # 0.5 - same as docs
print_metric_value(2)    # 1.0
print_metric_value(200)  # 1.0
```

答:
The num_thresholds refers to the number of thresholds. But you might ask: what is a threshold (in this context)? And the answer is that the threshold, which is in the range [0,1], is actually the value which all the predictions greater than that will be considered as positive (i.e. 1) and all the prediction lower than that will be considered as negative (i.e. 0).

For example, consider the prediction vector as [0, 0.5, 0.3, 0.9] which are actually confidences scores (e.g. probabilities). Now if we apply the threshold value of 0.1, we get [0, 1, 1, 1]; or if we apply threshold value of 0.6 we get [0, 0, 0, 1] (i.e. only the confidence of last prediction is higher than 0.6).

Now suppose you want to monitor the changes to specificity at a fixed sensitivity. What SensitivityAtSpecificity metric does is that, to compute the value of sensitivity, it would first compute the specificity at different thresholds and then chooses the threshold which has the closest specificity to the specificity value you have provided (for example, in your question you have given 0.4 as the specificity value). Then the sensitivity is computed at that threshold and will be returned as the value of this metric. The same thing applies to SpecificityAtSensitivity metric, just swap "specificity" and "sensitivity" in this paragraph.

You might also ask: what are the threshold values? The answer is if num_thresholds=1 then the only threshold is 0.5. If num_thresholds > 1 then, besides 0 and 1 as thresholds, the interval (0,1) will be split into num_thresholds - 1 equal sub-intervals and the split points are chosen as additional threshold values. For example:

```<code>num_threshold  |  thresholds
=============================
1              | [0.5]
2              | [0, 1]
3              | [0, 0.5, 1]
4              | [0, 0.33, 0.66, 1]
5              | [0, 0.25, 0.5, 0.75, 1]
...
</code>```

Body:
The num_thresholds refers to the number of thresholds. But you might ask: what is a threshold (in this context)? And the answer is that the threshold, which is in the range [0,1], is actually the value which all the predictions greater than that will be considered as positive (i.e. 1) and all the prediction lower than that will be considered as negative (i.e. 0).

For example, consider the prediction vector as [0, 0.5, 0.3, 0.9] which are actually confidences scores (e.g. probabilities). Now if we apply the threshold value of 0.1, we get [0, 1, 1, 1]; or if we apply threshold value of 0.6 we get [0, 0, 0, 1] (i.e. only the confidence of last prediction is higher than 0.6).

Now suppose you want to monitor the changes to specificity at a fixed sensitivity. What SensitivityAtSpecificity metric does is that, to compute the value of sensitivity, it would first compute the specificity at different thresholds and then chooses the threshold which has the closest specificity to the specificity value you have provided (for example, in your question you have given 0.4 as the specificity value). Then the sensitivity is computed at that threshold and will be returned as the value of this metric. The same thing applies to SpecificityAtSensitivity metric, just swap "specificity" and "sensitivity" in this paragraph.

You might also ask: what are the threshold values? The answer is if num_thresholds=1 then the only threshold is 0.5. If num_thresholds > 1 then, besides 0 and 1 as thresholds, the interval (0,1) will be split into num_thresholds - 1 equal sub-intervals and the split points are chosen as additional threshold values. For example:

num_threshold  |  thresholds
=============================
1              | [0.5]
2              | [0, 1]
3              | [0, 0.5, 1]
4              | [0, 0.33, 0.66, 1]
5              | [0, 0.25, 0.5, 0.75, 1]
...


问:
Convert Text with date column to display Month and Year in Power BI
I am just getting my hands on PowerBI, i am trying to get the date column which is in text to display Month and Year and i am not able to. Any directions. The column type is text which has value like this "2010-09-09T14:46:41+0000" i am trying to display "2010 September". </p>

答:
Tested the below in Power Query for Excel, but hopefully it should still work for you in Power BI. You could create a simple function like:

```<code>ParseYearAndMonth = (someText as text) as text => DateTimeZone.ToText(DateTimeZone.From(someText), "yyyy MMMM")
</code>```

(In the function above, we convert the text to type DateTimeZone, and then just the year and month components of the DateTimeZone back to text. However, there is no error handling implemented.)

Below is an example of invoking/using the function.

```<code>let
    someText = "2010-09-09T14:46:41+0000",
    ParseYearAndMonth = (textToParse as text) as text => DateTimeZone.ToText(DateTimeZone.From(textToParse), "yyyy MMMM"),
    someAttempt = ParseYearAndMonth(someText)
in
    someAttempt
</code>```

Edit:

Your query might look something like this (although I can't be sure without testing):

```<code>let
    Source = Facebook.Graph("graph.facebook.com/v2.8/Me/posts"),
    #"Removed Other Columns" = Table.SelectColumns(Source,{"message", "created_time", "id", "story"}),
    ParseYearAndMonth = (someText as text) as text => DateTimeZone.ToText(DateTimeZone.From(someText), "yyyy MMMM"),
    invokedFunction = Table.AddColumn(#"Removed Other Columns", "yearAndMonth", each ParseYearAndMonth([created_time]), type text)
in
    invokedFunction
</code>```

Body:
Tested the below in Power Query for Excel, but hopefully it should still work for you in Power BI. You could create a simple function like:

ParseYearAndMonth = (someText as text) as text => DateTimeZone.ToText(DateTimeZone.From(someText), "yyyy MMMM")

(In the function above, we convert the text to type DateTimeZone, and then just the year and month components of the DateTimeZone back to text. However, there is no error handling implemented.)

Below is an example of invoking/using the function.

let
    someText = "2010-09-09T14:46:41+0000",
    ParseYearAndMonth = (textToParse as text) as text => DateTimeZone.ToText(DateTimeZone.From(textToParse), "yyyy MMMM"),
    someAttempt = ParseYearAndMonth(someText)
in
    someAttempt

Edit:

Your query might look something like this (although I can't be sure without testing):

let
    Source = Facebook.Graph("graph.facebook.com/v2.8/Me/posts"),
    #"Removed Other Columns" = Table.SelectColumns(Source,{"message", "created_time", "id", "story"}),
    ParseYearAndMonth = (someText as text) as text => DateTimeZone.ToText(DateTimeZone.From(someText), "yyyy MMMM"),
    invokedFunction = Table.AddColumn(#"Removed Other Columns", "yearAndMonth", each ParseYearAndMonth([created_time]), type text)
in
    invokedFunction


问:
SonarLint best practice for "hard coded password" false positives
SonarLint flags as blockers some variables in my code base. Ones like public static final String INVALID_PASSWORD = "Your password is invalid.";

SonarLint thinks that the variable might contain a hard coded password, which is a security risk. But in this case, the variable does not contain a password, it contains a message about a password.

I also have some like public static final String INVALID_PASSWORD = "INVALID_PASSWORD";, that are codes rather than strings, which SonarLint also flags.

What's the best practice for "fixing" this type of issue? Two solutions that come to mind are renaming the variable, and using a @SupressWarnings("code here") annotation.

Does SonarLint itself have a recommendation for this issue? Is an there an industry best practice?

答:
You should be able to mute the Sonar issue with something like:

```<code>@SuppressWarnings("squid:S2068") // This is not an hard coded password.
</code>```

Annotated over the culprit.

ContentLicense: CC BY-SA 3.0

Body:
You should be able to mute the Sonar issue with something like:

@SuppressWarnings("squid:S2068") // This is not an hard coded password.

Annotated over the culprit.


问:
copying and pasting information between datasets
How to copy data fully from one dataset to another dataset when one of the dataset consists of dots as shown bllow ?

答:
The dots you are seeing are most likely undisplayable data so a utility is the best bet.

There are many ways to move data around on z/OS.  If you are simply trying to copy an existing dataset to another to make a copy you could use a batch utility like IEBGENER.  Here is some sample JCL

```<code>//IEBGENER JOB (CCCCCCCC),'HOGSTROM',
//             MSGLEVEL=(1,1),
//             MSGCLASS=O,
//             CLASS=A,
//             NOTIFY=&SYSUID
//*
//*----------------------------------------------------------
//*       IEBGENER
//*----------------------------------------------------------
//GENER02  EXEC PGM=IEBGENER
//SYSPRINT DD  SYSOUT=*
//SYSUT1   DD  DSN=USER1.TEST.DATA,DISP=SHR
//SYSUT2   DD  DSN=USER1.TEST.ODATA,DISP=(,CATLG,DELETE),
//             UNIT=SYSDA,SPACE=(CYL,5,RLSE),DCB=USER1.TEST.DATA
//SYSIN    DD  DUMMY
//
</code>```

You could also use online tools like ISPF Option 3.2 to create the new dataset

and 3.3 to move / copy it.

Body:
The dots you are seeing are most likely undisplayable data so a utility is the best bet.

There are many ways to move data around on z/OS.  If you are simply trying to copy an existing dataset to another to make a copy you could use a batch utility like IEBGENER.  Here is some sample JCL

//IEBGENER JOB (CCCCCCCC),'HOGSTROM',
//             MSGLEVEL=(1,1),
//             MSGCLASS=O,
//             CLASS=A,
//             NOTIFY=&SYSUID
//*
//*----------------------------------------------------------
//*       IEBGENER
//*----------------------------------------------------------
//GENER02  EXEC PGM=IEBGENER
//SYSPRINT DD  SYSOUT=*
//SYSUT1   DD  DSN=USER1.TEST.DATA,DISP=SHR
//SYSUT2   DD  DSN=USER1.TEST.ODATA,DISP=(,CATLG,DELETE),
//             UNIT=SYSDA,SPACE=(CYL,5,RLSE),DCB=USER1.TEST.DATA
//SYSIN    DD  DUMMY
//

You could also use online tools like ISPF Option 3.2 to create the new dataset

and 3.3 to move / copy it.


问:
how to send mail from .net?
i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me</p>

```<code>SendMail("xyz@gmail.com","hi","heloo");

public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
    {

         string smtphost ="smtp.gmail.com";
            int smtpport = 100;
            string smtpuser ="xyz";
            string smtppwd = "xyz";
            SmtpClient client = null;

            string MessageBody = string.Empty;
            try
            {

                message = new MailMessage();
                message.From = new MailAddress(smtpuser);
                message.To.Add(toMailAddress);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = mailSubject;
                message.Body = mailMessage.ToString();

                message.IsBodyHtml = true;

                client = new SmtpClient();
                client.Host = smtphost;

                client.Port = smtpport;
                client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
                client.Send(message);
            }
            catch (Exception ex)
            {
                string x = ex.Message;
            }
            return true;
        }
</code>```

答: Try, with port as 25 and IsSSLEnabled as true since gmail server is SSL enabled</p>

Title: how to send mail from .net?

Body:
i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me

SendMail("xyz@gmail.com","hi","heloo");

public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
    {

         string smtphost ="smtp.gmail.com";
            int smtpport = 100;
            string smtpuser ="xyz";
            string smtppwd = "xyz";
            SmtpClient client = null;

            string MessageBody = string.Empty;
            try
            {

                message = new MailMessage();
                message.From = new MailAddress(smtpuser);
                message.To.Add(toMailAddress);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Subject = mailSubject;
                message.Body = mailMessage.ToString();

                message.IsBodyHtml = true;

                client = new SmtpClient();
                client.Host = smtphost;

                client.Port = smtpport;
                client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
                client.Send(message);
            }
            catch (Exception ex)
            {
                string x = ex.Message;
            }
            return true;
        }


问:
What is the space complexity of this code
What is the space complexity of the code:</p>

```<code>function double(n) {         //Here n is an array
   newArr = [];
   for (i = 0; i < n.length; i++) {
     newArr.push(2 * n[i]);
   }
  return newArr;
}
</code>```

答:
Since it has two variables newArr and i on which the space of this code depends.

Not only are there two variables named, newArr and i, there are also n variables named newArr[0], newArr[1], newArr[2], all the way to newArr[n-1]. Space complexity refers to the way the storage of your algorithm grows with respect to the number of inputs. Since you're pushing at most n elements into newArr, the space complexity is O(n).

Body:
What is the space complexity of the code:

function double(n) {         //Here n is an array
   newArr = [];
   for (i = 0; i < n.length; i++) {
     newArr.push(2 * n[i]);
   }
  return newArr;
}


问:
NumberFormatException: For input string "\N" when reading from file
I'm trying to read from a large data file movies.dat and then populate my database table with certain columns of that data.

The data in the movies file has the following data fields/columns:

id  title   imdbID  spanishTitle    imdbPictureURL  year    rtID    rtAllCriticsRating  rtAllCriticsNumReviews  rtAllCriticsNumFresh    rtAllCriticsNumRotten   rtAllCriticsScore   rtTopCriticsRating  rtTopCriticsNumReviews  rtTopCriticsNumFresh    rtTopCriticsNumRotten   rtTopCriticsScore   rtAudienceRating    rtAudienceNumRatings    rtAudienceScore rtPictureURL

The data values are separated by tabs.

```<code>    String line;

    // open movies file
    BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\Michael\\IdeaProjects\\hw3\\data\\movies.dat"));
    System.out.println("Movies.dat successfully opened.");

    // read the first line (header) of file
    line = reader.readLine();

    // create PreparedStatement for inserting movie data into db
    try {
        PreparedStatement s = conn.prepareStatement(
                "INSERT INTO Movie(mID, movieTitle, releaseYear, "
                        + "allCriticsRating, allCriticsNumReviews, "
                        + "topCriticsRating, topCriticsNumReviews, "
                        + "audienceRating, audienceNumRatings) "
                        + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)");

        // read remaining lines of data in the file
        while ((line = reader.readLine()) != null) {
            // separate each data field value and store into tmp array
            String[] tmp = line.split("\\t");

            s.setInt(1, Integer.parseInt(tmp[0]));
            s.setString(2, tmp[1]);
            s.setInt(3, Integer.parseInt(tmp[5]));
            s.setFloat(4, Float.parseFloat(tmp[7]));
            s.setInt(5, Integer.parseInt(tmp[8]));
            s.setFloat(6, Float.parseFloat(tmp[12]));
            s.setInt(7, Integer.parseInt(tmp[13]));
            s.setFloat(8, Float.parseFloat(tmp[17]));
            s.setInt(9, Integer.parseInt(tmp[18]));

            s.addBatch();
        }
        s.executeBatch();
        s.close();
        System.out.println("Movie table successfully populated!");
    }
    catch(SQLException e) {
        System.out.println("Movie table population failed.");
        e.printStackTrace();
    }
</code>```

However, when I run this code, I'm getting a numberformatexception for input string "\N" on the first parseFloat. I don't understand where the "\n" could be coming from though. I've used this same code (adjusted for some different data fields) to populate my other tables with data from another file and it worked fine so I'm not sure why it's just this file that's giving me issues.

Thank you in advance for the help!

答:
You can update this line:

String[] tmp = line.split("\t");

to look like this

String[] tmp = line.strip().split("\t");

and the excess whitespace before and after the tokens will be removed (including the new line character)

Body:
I'm trying to read from a large data file movies.dat and then populate my database table with certain columns of that data.

The data in the movies file has the following data fields/columns:

id  title   imdbID  spanishTitle    imdbPictureURL  year    rtID    rtAllCriticsRating  rtAllCriticsNumReviews  rtAllCriticsNumFresh    rtAllCriticsNumRotten   rtAllCriticsScore   rtTopCriticsRating  rtTopCriticsNumReviews  rtTopCriticsNumFresh    rtTopCriticsNumRotten   rtTopCriticsScore   rtAudienceRating    rtAudienceNumRatings    rtAudienceScore rtPictureURL

The data values are separated by tabs.

    String line;

    // open movies file
    BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\Michael\\IdeaProjects\\hw3\\data\\movies.dat"));
    System.out.println("Movies.dat successfully opened.");

    // read the first line (header) of file
    line = reader.readLine();

    // create PreparedStatement for inserting movie data into db
    try {
        PreparedStatement s = conn.prepareStatement(
                "INSERT INTO Movie(mID, movieTitle, releaseYear, "
                        + "allCriticsRating, allCriticsNumReviews, "
                        + "topCriticsRating, topCriticsNumReviews, "
                        + "audienceRating, audienceNumRatings) "
                        + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)");

        // read remaining lines of data in the file
        while ((line = reader.readLine()) != null) {
            // separate each data field value and store into tmp array
            String[] tmp = line.split("\\t");

            s.setInt(1, Integer.parseInt(tmp[0]));
            s.setString(2, tmp[1]);
            s.setInt(3, Integer.parseInt(tmp[5]));
            s.setFloat(4, Float.parseFloat(tmp[7]));
            s.setInt(5, Integer.parseInt(tmp[8]));
            s.setFloat(6, Float.parseFloat(tmp[12]));
            s.setInt(7, Integer.parseInt(tmp[13]));
            s.setFloat(8, Float.parseFloat(tmp[17]));
            s.setInt(9, Integer.parseInt(tmp[18]));

            s.addBatch();
        }
        s.executeBatch();
        s.close();
        System.out.println("Movie table successfully populated!");
    }
    catch(SQLException e) {
        System.out.println("Movie table population failed.");
        e.printStackTrace();
    }

However, when I run this code, I'm getting a numberformatexception for input string "\N" on the first parseFloat. I don't understand where the "\n" could be coming from though. I've used this same code (adjusted for some different data fields) to populate my other tables with data from another file and it worked fine so I'm not sure why it's just this file that's giving me issues.

Thank you in advance for the help!


问:
Kivy widgets have almost-unreadable text
I am having issues with my installation of Kivy on my Windows 10 machine. I've copied the "Hello, World" example from the Kivy website, but when I run it, almost nothing shows up. The screen is black except for an extremely faint "Hello world". On a different computer (also a Windows 10 machine), I tried running the exact same code, and the "Hello world" message was white and fully readable.

Here is the code that I am running:

import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.label import Label

class MyApp(App):

    def build(self):
        return Label(text='Hello world')

if __name__ == '__main__':
    MyApp().run()
```

<p>Here is a screencap of what's actually being displayed on my machine:</p>

<p><img src="https://i.stack.imgur.com/QZsqe.png" alt="simple label testing"></p>

<p>If you look very closely, you can barely see the "Hello world" message in the middle of the image.</p>

<p>I have Kivy version 1.10.1, using Glew, running on Python 3.6. I have Cython and Pygame installed and updated to the latest version, though I installed them after I had initially installed Kivy and they didn't seem to fix the issue. I have tried to do a reinstall of Kivy and it did not seem to change anything.</p>

<p>Any help is greatly appreciated.</p>

<p>EDIT -</p>

<p>I have done a complete reinstall of all my Python packages downloaded with pip and it seems to be working a lot better. However, there is still a difference between what I'm seeing on my computer versus what I'm seeing on the other computer.</p>

<p>Here is what I'm seeing on my computer:</p>

<p><img src="https://i.stack.imgur.com/3Y7OR.png" alt="testing on my computer"></p>

<p>The text is still not white like it is supposed to be, instead it's a gray color.</p>

<p>Here is what I'm seeing on the other computer:</p>

<p><img src="https://i.stack.imgur.com/ZbIKJ.png" alt="testing with a different coputer"></p>

<p>EDIT -</p>

<p>An update - If I put my <code>Label</code> into a <code>FloatLayout</code> or a <code>StackLayout</code>, it shows up like it's supposed to. Here's code that works, as opposed to what I pasted above:</p>

<pre class="lang-py prettyprint-override"><code>import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout
from kivy.uix.floatlayout import FloatLayout

class MyApp(App):

    def build(self):
        layout = FloatLayout() # this can be swapped with StackLayout()
        layout.add_widget(Label(text="Hello, world"))
        return layout

if __name__ == '__main__':
    MyApp().run()
</code>```

EDIT -

Expanding on what's above, it seems that if, for a widget that is nested n times into layouts, if n is an even number, that widget's text will be dimmed. Here's the code I used to test this.

import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout
from kivy.uix.floatlayout import FloatLayout

class MyApp(App):

    def build(self):
        layouts = []
        nest = 6 # with nest equal to 6, the Label's text is dimmed.
        # if nest were equal to 5, the Label's text would not be dimmed.
        for _ in range(nest):
            innerLayout = StackLayout()
            if len(layouts) != 0:
                layouts[-1].add_widget(innerLayout)
            layouts.append(innerLayout)

        layouts[-1].add_widget(Label(text="Hello, world"))
        return layouts[0]

if __name__ == '__main__':
    MyApp().run()
```

<p>EDIT -</p>

<p>I have found another condition under which Kivy's text is inexplicably dimmed. When the text has newlines (or wraps around to the next line), the text after the first line will be muted.</p>

<p>Here's a code snippet.</p>

<pre class="lang-py prettyprint-override"><code>import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout

longStr = """
I am making this text very long with newlines so that I can prove
that the Kivy label's text is faint when it goes to the next
line. It's very finnicky and I don't know what would be causing
this issue, though it probably isn't that big of one because no
one else seems to be having it.
"""

class MyApp(App):

    def build(self):
        layout = StackLayout()
        layout.add_widget(Label(text=longStr))
        return layout

if __name__ == '__main__':
    MyApp().run()
</code>```

Here's what it looks like on the affected machine.

I have also realized that some of the images, when viewed as a part of this post, don't seem to have any text at all, when on Imgur they are easier to see (still, not by much). I am accounting this to StackOverflow's light theme.

答: It's a bug introduced in a recent SDL2 version, you can work around it for now by running python -m pip install kivy.deps.sdl2==0.1.18 to install a slightly older version, or wait for a new Kivy release (coming soon) where it is also fixed.

Body:
I am having issues with my installation of Kivy on my Windows 10 machine. I've copied the "Hello, World" example from the Kivy website, but when I run it, almost nothing shows up. The screen is black except for an extremely faint "Hello world". On a different computer (also a Windows 10 machine), I tried running the exact same code, and the "Hello world" message was white and fully readable.

Here is the code that I am running:

import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.label import Label

class MyApp(App):

    def build(self):
        return Label(text='Hello world')

if __name__ == '__main__':
    MyApp().run()

Here is a screencap of what's actually being displayed on my machine:

If you look very closely, you can barely see the "Hello world" message in the middle of the image.

I have Kivy version 1.10.1, using Glew, running on Python 3.6. I have Cython and Pygame installed and updated to the latest version, though I installed them after I had initially installed Kivy and they didn't seem to fix the issue. I have tried to do a reinstall of Kivy and it did not seem to change anything.

Any help is greatly appreciated.

EDIT -

I have done a complete reinstall of all my Python packages downloaded with pip and it seems to be working a lot better. However, there is still a difference between what I'm seeing on my computer versus what I'm seeing on the other computer.

Here is what I'm seeing on my computer:

The text is still not white like it is supposed to be, instead it's a gray color.

Here is what I'm seeing on the other computer:

EDIT -

An update - If I put my Label into a FloatLayout or a StackLayout, it shows up like it's supposed to. Here's code that works, as opposed to what I pasted above:

import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout
from kivy.uix.floatlayout import FloatLayout

class MyApp(App):

    def build(self):
        layout = FloatLayout() # this can be swapped with StackLayout()
        layout.add_widget(Label(text="Hello, world"))
        return layout

if __name__ == '__main__':
    MyApp().run()

EDIT -

Expanding on what's above, it seems that if, for a widget that is nested n times into layouts, if n is an even number, that widget's text will be dimmed. Here's the code I used to test this.

import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout
from kivy.uix.floatlayout import FloatLayout

class MyApp(App):

    def build(self):
        layouts = []
        nest = 6 # with nest equal to 6, the Label's text is dimmed.
        # if nest were equal to 5, the Label's text would not be dimmed.
        for _ in range(nest):
            innerLayout = StackLayout()
            if len(layouts) != 0:
                layouts[-1].add_widget(innerLayout)
            layouts.append(innerLayout)

        layouts[-1].add_widget(Label(text="Hello, world"))
        return layouts[0]

if __name__ == '__main__':
    MyApp().run()

EDIT -

I have found another condition under which Kivy's text is inexplicably dimmed. When the text has newlines (or wraps around to the next line), the text after the first line will be muted.

Here's a code snippet.

import kivy
kivy.require("1.10.1")

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout

longStr = """
I am making this text very long with newlines so that I can prove
that the Kivy label's text is faint when it goes to the next
line. It's very finnicky and I don't know what would be causing
this issue, though it probably isn't that big of one because no
one else seems to be having it.
"""

class MyApp(App):

    def build(self):
        layout = StackLayout()
        layout.add_widget(Label(text=longStr))
        return layout

if __name__ == '__main__':
    MyApp().run()

Here's what it looks like on the affected machine.

I have also realized that some of the images, when viewed as a part of this post, don't seem to have any text at all, when on Imgur they are easier to see (still, not by much). I am accounting this to StackOverflow's light theme.


问:
How to get values from this json object?
How to get values from this json?

The returned json from an API is like:

```<code>{
  "id": 191671,
  "callTrackingProfiles": {
    "1": {
      "destinationPhoneNumber": "8449000218",
      "phones": [
        {
          "phoneType": 3,
          "phoneNumber": "8443876176",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": false,
          "recordCalls": false,
          "countryCode": "USA"
        },
        {
          "phoneType": 7,
          "phoneNumber": "8442692468",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": false,
          "recordCalls": false,
          "countryCode": "USA"
        },
        {
          "phoneType": 10,
          "phoneNumber": "9493931848",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": true,
          "recordCalls": false,
          "countryCode": "USA"
        }
      ]
    },
    "2": {
      "destinationPhoneNumber": "8449000218",
      "phones": [
        {
          "phoneType": 3,
          "phoneNumber": "9495283517",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": true,
          "recordCalls": false,
          "countryCode": "USA"
        },
        {
          "phoneType": 7,
          "phoneNumber": "8443500663",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": false,
          "recordCalls": false,
          "countryCode": "USA"
        }
      ]
    }
}
</code>```

Now, I deserialized it:

```<code>dynamic jsonResults = JsonConvert.DeserializeObject<dynamic>(response);
var profiles = jsonResults.callTrackingProfiles;
</code>```

and I can use foreach to loop it.

But how can I get the values of destinationPhoneNumber and phoneNumber?

```<code>foreach (var p in profiles)
{
    ...
    p.destinationPhoneNumber
    ...
}
</code>```

This does not work, and p.1 has error:

```<code>error CS1061: 'object' does not contain a definition for 'destinationPhoneNumber' and no accessible extension method 'destinationPhoneNumber' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
</code>```

Thanks

答:
I am assuming you're using visual studios. If so this is the easiest solution in my opinion: 1.Create a c# class. 2.Then Copy all of your JSON (from your example). 3.Then go to that class you created before and go to Edit>paste special>Paste JSON as Classes.

This will create a class for you based off that JSON. Then all you have to do is deserialize it into that class type and it will create an object which you can pull all the information out of. I hope that helps!

http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

Body:
How to get values from this json?

The returned json from an API is like:

{
  "id": 191671,
  "callTrackingProfiles": {
    "1": {
      "destinationPhoneNumber": "8449000218",
      "phones": [
        {
          "phoneType": 3,
          "phoneNumber": "8443876176",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": false,
          "recordCalls": false,
          "countryCode": "USA"
        },
        {
          "phoneType": 7,
          "phoneNumber": "8442692468",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": false,
          "recordCalls": false,
          "countryCode": "USA"
        },
        {
          "phoneType": 10,
          "phoneNumber": "9493931848",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": true,
          "recordCalls": false,
          "countryCode": "USA"
        }
      ]
    },
    "2": {
      "destinationPhoneNumber": "8449000218",
      "phones": [
        {
          "phoneType": 3,
          "phoneNumber": "9495283517",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": true,
          "recordCalls": false,
          "countryCode": "USA"
        },
        {
          "phoneType": 7,
          "phoneNumber": "8443500663",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": false,
          "recordCalls": false,
          "countryCode": "USA"
        }
      ]
    }
}

Now, I deserialized it:

dynamic jsonResults = JsonConvert.DeserializeObject<dynamic>(response);
var profiles = jsonResults.callTrackingProfiles;

and I can use foreach to loop it.

But how can I get the values of destinationPhoneNumber and phoneNumber?

foreach (var p in profiles)
{
    ...
    p.destinationPhoneNumber
    ...
}

This does not work, and p.1 has error:

error CS1061: 'object' does not contain a definition for 'destinationPhoneNumber' and no accessible extension method 'destinationPhoneNumber' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Thanks


问:
Data missing JSONDecoder
I am trying to load an array of JSON dictionaries into an object with swift using Alamofire and SwiftyJSON, but when the data is downloaded, I get the error:

keyNotFound(CodingKeys(stringValue: "inProrgresss", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"inProrgresss\", intValue: nil) (\"inProrgresss\").", underlyingError: nil)).

The localised description just says that the data is missing.  My JSON is here and my code is like this:

```<code>struct CompData: Codable {
    let inProrgresss: [[String: String]]
    let past: [[String: String]]
    let upcoming: [[String: String]]
}

func getData(url: URLConvertible) {
    SVProgressHUD.show()
    Alamofire.request(url).responseJSON { (dataResponse) in
        if dataResponse.result.value != nil {
            SVProgressHUD.dismiss()
            let JSONVar = JSON(dataResponse.result.value)
            let data = Data(dataResponse.data!)
            print(data)
            let decoder = JSONDecoder()
            do {
                let newData = try decoder.decode(CompData.self, from: data)
                print("NEWDATA \(newData)")
            } catch {
                print(error)
            }
            print(JSONVar)
        }
    }
}
</code>```

I am quite new to converting JSON into datatypes, and I couldn't find anything on here that helps.

答:
Please read the JSON. There is no key inProrgresss.

And create a struct for the dictionaries, it's pretty straightforward

```<code>struct CompData: Decodable {
    let inProgress: [Location]?
    let past: [Location]
    let upcoming: [Location]
}

struct Location : Decodable {
    let city, countryCode, name, date, country, id : String
}
</code>```

And declare inProgress as optional because the array is empty.

Edit:

There is a lot of redundant code in getData. This is more efficient. convertFromSnakeCase does what it says.

```<code>func getData(url: URLConvertible) {
    SVProgressHUD.show()
    Alamofire.request(url).responseData { (response) in
        SVProgressHUD.dismiss()
        switch response.result {
        case .success(let data):
            let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            do {
                let result = try decoder.decode(CompData.self, from: data)
                print("NEWDATA \(result)")
            } catch {
                print(error)
            }
        case .failure(let error): print(error)
        }
    }
}
</code>```

Title: Data missing JSONDecoder

Body:
I am trying to load an array of JSON dictionaries into an object with swift using Alamofire and SwiftyJSON, but when the data is downloaded, I get the error:

keyNotFound(CodingKeys(stringValue: "inProrgresss", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"inProrgresss\", intValue: nil) (\"inProrgresss\").", underlyingError: nil)).

The localised description just says that the data is missing.  My JSON is here and my code is like this:

struct CompData: Codable {
    let inProrgresss: [[String: String]]
    let past: [[String: String]]
    let upcoming: [[String: String]]
}

func getData(url: URLConvertible) {
    SVProgressHUD.show()
    Alamofire.request(url).responseJSON { (dataResponse) in
        if dataResponse.result.value != nil {
            SVProgressHUD.dismiss()
            let JSONVar = JSON(dataResponse.result.value)
            let data = Data(dataResponse.data!)
            print(data)
            let decoder = JSONDecoder()
            do {
                let newData = try decoder.decode(CompData.self, from: data)
                print("NEWDATA \(newData)")
            } catch {
                print(error)
            }
            print(JSONVar)
        }
    }
}

I am quite new to converting JSON into datatypes, and I couldn't find anything on here that helps.

Body:
Please read the JSON. There is no key inProrgresss.

And create a struct for the dictionaries, it's pretty straightforward

struct CompData: Decodable {
    let inProgress: [Location]?
    let past: [Location]
    let upcoming: [Location]
}

struct Location : Decodable {
    let city, countryCode, name, date, country, id : String
}

And declare inProgress as optional because the array is empty.

Edit:

There is a lot of redundant code in getData. This is more efficient. convertFromSnakeCase does what it says.

func getData(url: URLConvertible) {
    SVProgressHUD.show()
    Alamofire.request(url).responseData { (response) in
        SVProgressHUD.dismiss()
        switch response.result {
        case .success(let data):
            let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            do {
                let result = try decoder.decode(CompData.self, from: data)
                print("NEWDATA \(result)")
            } catch {
                print(error)
            }
        case .failure(let error): print(error)
        }
    }
}


问:
Is it correct to write [self.someproperty release]
When i implement dealloc method i used to write:

```<code>[preopertyX release];
</code>```

Today i found this code:

```<code>[self.propertyX release];
</code>```

I'm not sure that this method is completely correct. What do you think about ?
(we can take as assumption that propertyX is a retained and synthesized property).

答: You can write [self.propertyX release] if you have set propertyX retained and synthesized otherwise not</p>

Body:
When i implement dealloc method i used to write:

[preopertyX release];

Today i found this code:

[self.propertyX release];

I'm not sure that this method is completely correct. What do you think about ?
(we can take as assumption that propertyX is a retained and synthesized property).


问:
How to configure nginx.ingress.kubernetes.io/rewrite-target and spec.rules.http.paths.path to satisfy the following URI patterns
How can I configure nginx.ingress.kubernetes.io/rewrite-target and spec.rules.http.paths.path to satisfy the following URI patterns?

```<code>/aa/bb-aa/coolapp
/aa/bb-aa/coolapp/cc
</code>```

Legend:

a = Any letter between a-z. Lowercase. Exactly 2 letters - no more,
no less.

b = Any letter between a-z. Lowercase. Exactly 2 letters - no more, no less.

c = any valid URI character. Lowercase. Of variable length - think slug.

Example URI:s that should match the above pattern:

```<code>/us/en-us/coolapp
/us/en-us/coolapp/faq
/us/en-us/coolapp/privacy-policy
</code>```

Attention

Starting in Version 0.22.0, ingress definitions using the annotation nginx.ingress.kubernetes.io/rewrite-target are not backwards compatible with previous versions. In Version 0.22.0 and beyond, any substrings within the request URI that need to be passed to the rewritten path must explicitly be defined in a capture group.

Note

Captured groups are saved in numbered placeholders, chronologically, in the form $1, $2 ... $n. These placeholders can be used as parameters in the rewrite-target annotation.

References:

https://kubernetes.github.io/ingress-nginx/examples/rewrite/

https://github.com/kubernetes/ingress-nginx/pull/3174

答:
The nginx.ingress.kubernetes.io/rewrite-target annotation is used to indicate the target URI where the traffic must be redirected. As per how I understand your question, you only want to match the URI patterns that you specified without redirecting the traffic. In order to achieve this, you can set the nginx.ingress.kubernetes.io/use-regex annotation to true, thus enabling regular expressions in the spec.rules.http.paths.path field.

Let's now take a look at the regex that you will need to match your URI patterns.
First of all, the regex engine used by ingress-nginx doesn't support backreferences, therefore a regex like this one will not work. This is not a problem as you can match the /aa-bb/aa part without forcing the two aas to be equal since you will —presumably— still have to check the correctness of the URI later on in your service (e.g /us/en-us may be accepted whereas /ab/cd-ab may not).

You can use this regex to match the specified URI patterns:

```<code>/[a-z]{2}/[a-z]{2}-[a-z]{2}/coolapp(/.*)?
</code>```

If you want to only match URL slugs in the cc part of the pattern you specified, you can use this regex instead:

```<code>/[a-z]{2}/[a-z]{2}-[a-z]{2}/coolapp(/[a-z0-9]+([a-z0-9]+)*)?
</code>```

Lastly, as the nginx.ingress.kubernetes.io/use-regex enforces case insensitive regex, using [A-Z] instead of [a-z] would lead to the same result.

Follows an ingress example definition using the use-regex annotation:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-regex
  annotations:
    nginx.ingress.kubernetes.io/use-regex: "true"
spec:
  rules:
  - host: test.com
    http:
      paths:
      - path: /[a-z]{2}/[a-z]{2}-[a-z]{2}/coolapp(/.*)?
        backend:
          serviceName: test
          servicePort: 80
</code>```

You can find more information about Ingress Path Matching in the official user guide.

Body:
How can I configure nginx.ingress.kubernetes.io/rewrite-target and spec.rules.http.paths.path to satisfy the following URI patterns?

/aa/bb-aa/coolapp
/aa/bb-aa/coolapp/cc

Legend:

a = Any letter between a-z. Lowercase. Exactly 2 letters - no more,
no less.

b = Any letter between a-z. Lowercase. Exactly 2 letters - no more, no less.

c = any valid URI character. Lowercase. Of variable length - think slug.

Example URI:s that should match the above pattern:

/us/en-us/coolapp
/us/en-us/coolapp/faq
/us/en-us/coolapp/privacy-policy

Attention

Starting in Version 0.22.0, ingress definitions using the annotation nginx.ingress.kubernetes.io/rewrite-target are not backwards compatible with previous versions. In Version 0.22.0 and beyond, any substrings within the request URI that need to be passed to the rewritten path must explicitly be defined in a capture group.

Note

Captured groups are saved in numbered placeholders, chronologically, in the form $1, $2 ... $n. These placeholders can be used as parameters in the rewrite-target annotation.

References:

https://kubernetes.github.io/ingress-nginx/examples/rewrite/

https://github.com/kubernetes/ingress-nginx/pull/3174

Body:
The nginx.ingress.kubernetes.io/rewrite-target annotation is used to indicate the target URI where the traffic must be redirected. As per how I understand your question, you only want to match the URI patterns that you specified without redirecting the traffic. In order to achieve this, you can set the nginx.ingress.kubernetes.io/use-regex annotation to true, thus enabling regular expressions in the spec.rules.http.paths.path field.

Let's now take a look at the regex that you will need to match your URI patterns.
First of all, the regex engine used by ingress-nginx doesn't support backreferences, therefore a regex like this one will not work. This is not a problem as you can match the /aa-bb/aa part without forcing the two aas to be equal since you will —presumably— still have to check the correctness of the URI later on in your service (e.g /us/en-us may be accepted whereas /ab/cd-ab may not).

You can use this regex to match the specified URI patterns:

/[a-z]{2}/[a-z]{2}-[a-z]{2}/coolapp(/.*)?

If you want to only match URL slugs in the cc part of the pattern you specified, you can use this regex instead:

/[a-z]{2}/[a-z]{2}-[a-z]{2}/coolapp(/[a-z0-9]+([a-z0-9]+)*)?

Lastly, as the nginx.ingress.kubernetes.io/use-regex enforces case insensitive regex, using [A-Z] instead of [a-z] would lead to the same result.

Follows an ingress example definition using the use-regex annotation:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-regex
  annotations:
    nginx.ingress.kubernetes.io/use-regex: "true"
spec:
  rules:
  - host: test.com
    http:
      paths:
      - path: /[a-z]{2}/[a-z]{2}-[a-z]{2}/coolapp(/.*)?
        backend:
          serviceName: test
          servicePort: 80

You can find more information about Ingress Path Matching in the official user guide.


问:
How to start a new Activity with an if-statement without onCreate method?
I basically want to start new Activities in each condition, but here is the problem: I want the new Activity to start when an "if-statement" is true. So when the user reaches a certain position in counter, let's say 2, the intended activity should start. Thanks in advance!

Here is some code:

```<code>public class Adapter extends PagerAdapter {

    private List<Model>models;
    private LayoutInflater layoutInflater;
    private Context context;

    public Adapter(List<Model> models, Context context) {
        this.models = models;
        this.context = context;
    }

    @Override
    public int getCount() {
        return models.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view.equals(object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, final int position) {
        layoutInflater=LayoutInflater.from(context);
        View view =layoutInflater.inflate(R.layout.item, container, false);

        ImageView imageView;
        TextView title, desc;

        imageView=view.findViewById(R.id.image);
        title=view.findViewById(R.id.title);
        desc=view.findViewById(R.id.desc);

        imageView.setImageResource(models.get(position).getImage());
        title.setText(models.get(position).getTitle());
        desc.setText(models.get(position).getDesc());

        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
//HERE IS MY PROBLEM
                if(position == 0){
                    //start activity1
                } else if(position == 1){
                    //start activity2
                }else if(position == 2){
                    //start activity3
                }else if(position == 3){
                    //start activity4
                }else {
                    Toast.makeText(context, "Click the exit button", Toast.LENGTH_SHORT).show();
                }
            }
        });
        container.addView(view,0);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View)object);
    }
}

</code>```

答:
This code worked well:

view.setOnClickListener(new View.OnClickListener() {

```<code>        @Override
        public void onClick(View view) {
            if(position == 0){
                Intent i = new Intent(view.getContext(),Levels.class);
                view.getContext().startActivity(i);
        }
</code>```

Body:
I basically want to start new Activities in each condition, but here is the problem: I want the new Activity to start when an "if-statement" is true. So when the user reaches a certain position in counter, let's say 2, the intended activity should start. Thanks in advance!

Here is some code:

public class Adapter extends PagerAdapter {

    private List<Model>models;
    private LayoutInflater layoutInflater;
    private Context context;

    public Adapter(List<Model> models, Context context) {
        this.models = models;
        this.context = context;
    }

    @Override
    public int getCount() {
        return models.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view.equals(object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, final int position) {
        layoutInflater=LayoutInflater.from(context);
        View view =layoutInflater.inflate(R.layout.item, container, false);

        ImageView imageView;
        TextView title, desc;

        imageView=view.findViewById(R.id.image);
        title=view.findViewById(R.id.title);
        desc=view.findViewById(R.id.desc);

        imageView.setImageResource(models.get(position).getImage());
        title.setText(models.get(position).getTitle());
        desc.setText(models.get(position).getDesc());

        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
//HERE IS MY PROBLEM
                if(position == 0){
                    //start activity1
                } else if(position == 1){
                    //start activity2
                }else if(position == 2){
                    //start activity3
                }else if(position == 3){
                    //start activity4
                }else {
                    Toast.makeText(context, "Click the exit button", Toast.LENGTH_SHORT).show();
                }
            }
        });
        container.addView(view,0);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View)object);
    }
}

Body:
This code worked well:

view.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if(position == 0){
                Intent i = new Intent(view.getContext(),Levels.class);
                view.getContext().startActivity(i);
        }


问:
Scroll background by dragging fingers vertically
I want to change that code instead of scrolling the background itself, to scroll by dragging fingers vertically.</p>

```<code>private float speed = 0.5f;
Vector2 startPos;

void Start () {

    startPos = transform.position;

}

void Update () {

    transform.Translate((new Vector2(0, -1)) * speed * Time.deltaTime);

    if (transform.position.y < -19)
    {

        transform.position = startPos;

    }

}
</code>```

答:
Use Input.touchCount, Input.GetTouch and touch.deltaPosition to detect how far the touch has moved.

You can ignore deltaTime because it's already expressed in how much of the screen has been dragged since the last frame.

```<code>void Update () {
    if (Input.touchCount > 0 )
    {
        Touch touch = Input.GetTouch(0);

        float yMove = touch.deltaPosition.y / Screen.height;

        transform.Translate(Vector2.up * yMove * speed);

        if (transform.position.y < -19)
        {
            transform.position = startPos;
        }
    }

}
</code>```

Body:
I want to change that code instead of scrolling the background itself, to scroll by dragging fingers vertically.

private float speed = 0.5f;
Vector2 startPos;

void Start () {

    startPos = transform.position;

}

void Update () {

    transform.Translate((new Vector2(0, -1)) * speed * Time.deltaTime);

    if (transform.position.y < -19)
    {

        transform.position = startPos;

    }

}

Body:
Use Input.touchCount, Input.GetTouch and touch.deltaPosition to detect how far the touch has moved.

You can ignore deltaTime because it's already expressed in how much of the screen has been dragged since the last frame.

void Update () {
    if (Input.touchCount > 0 )
    {
        Touch touch = Input.GetTouch(0);

        float yMove = touch.deltaPosition.y / Screen.height;

        transform.Translate(Vector2.up * yMove * speed);

        if (transform.position.y < -19)
        {
            transform.position = startPos;
        }
    }

}


问:
Pandas - Replace values based on index and not in index
Here is the sample code.

```<code>import pandas as pd, numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(10, 1)), columns=list('A'))
</code>```

I have a list dl=[0,2,3,4,7]

At the index positions specified by list, I would like to have column A as "Yes".

The following code works

```<code>df.loc[dl,'A']='Yes'
</code>```

How do I fill column 'A' with 'No' for column values not in index.
Please forgive me if this is a duplicate post.

答:
One way is to use the isin function. '~' will reverse it so that the output is elements that are not in dl.</p>

```<code>df.loc[~df.index.isin(dl),'A']='No'
</code>```

Body:
Here is the sample code.

import pandas as pd, numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(10, 1)), columns=list('A'))

I have a list dl=[0,2,3,4,7]

At the index positions specified by list, I would like to have column A as "Yes".

The following code works

df.loc[dl,'A']='Yes'

How do I fill column 'A' with 'No' for column values not in index.
Please forgive me if this is a duplicate post.

Body:
One way is to use the isin function. '~' will reverse it so that the output is elements that are not in dl.

df.loc[~df.index.isin(dl),'A']='No'


问:
How to make collisions more OOP style
I'm making a game in pygame. My main problem is how to realize pygame collisions in one class. I have lots of collision detection in my game could I do them less in one class or something like that. There are also some group collisions.

Also does lots of collisions effects optimization of games(Not that game I'm talking about 3A games).

    def update(self):
        self.all_sprites.update()
        self.score += self.start_time
        collision = pygame.sprite.spritecollide(self.player, self.platforms, False)
        collideGroup = pygame.sprite.groupcollide(self.bullet_list, self.enemyRocket, True, True)
        collideGroupPlat = pygame.sprite.groupcollide(self.bullet_list, self.platforms, True, False)
        collide = pygame.sprite.spritecollide(self.player, self.enemyRocket, False)
        collideWithEND = pygame.sprite.spritecollide(self.player, self.endLevel, False)
        collideWithFuel = pygame.sprite.groupcollide(self.bullet_list, self.fuel, True, True)

        if collision:
            self.player_health -= 1
            self.new()
        if collide:
            self.player_health -= 1
            self.new()
        if collideGroup:
            self.score += 10
        if collideWithEND:
            self.level += 1
        if collideWithFuel:
            self.fuelBar += 10
```

<p>Should I add in sprites classes some functions to detect collisions or should I open another class for collisions.
Here are my spites classes.</p>

<pre class="lang-py prettyprint-override"><code>
    class Player(pygame.sprite.Sprite):
    def __init__(self, img, pos_x, pos_y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(os.path.join('images', img)).convert()
        self.image.convert_alpha()
        self.image.set_colorkey(ALPHA)
        self.rect = self.image.get_rect()
        self.rect.center = (pos_x, pos_y)
        self.vx = 0
        self.vy = 0

    def update(self):
        self.vx = 0
        self.vy = 0
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            self.vy = -5
            if self.rect.y < 0:
                self.rect.y += 5
        if keys[pygame.K_DOWN]:
            self.vy = 3
        if keys[pygame.K_RIGHT]:
            self.vx = 3
            if self.rect.x > (WIDTH-58):
                self.rect.x -= 5
        if keys[pygame.K_LEFT]:
            self.vx = -5
            if self.rect.x < 0:
                self.rect.x += 5

        self.rect.x += self.vx
        self.rect.y += self.vy

class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((5, 3))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.vx = 0

    def update(self):
        keys = pygame.key.get_pressed()

        self.rect.x += self.vx
        if self.rect.x > WIDTH:
            self.kill()
        if keys[pygame.K_SPACE]:
            self.vx = 2
        self.rect.x += self.vx
</code>```

答:
If you want only one class the enum module probably is what you're after: https://docs.python.org/3/library/enum.html

If you don't want one class only why not make a baseclass of some sort and all the variants children to that (maybe as singletons - i have code for that if you're interested)

Title: How to make collisions more OOP style

Body:
I'm making a game in pygame. My main problem is how to realize pygame collisions in one class. I have lots of collision detection in my game could I do them less in one class or something like that. There are also some group collisions.

Also does lots of collisions effects optimization of games(Not that game I'm talking about 3A games).

    def update(self):
        self.all_sprites.update()
        self.score += self.start_time
        collision = pygame.sprite.spritecollide(self.player, self.platforms, False)
        collideGroup = pygame.sprite.groupcollide(self.bullet_list, self.enemyRocket, True, True)
        collideGroupPlat = pygame.sprite.groupcollide(self.bullet_list, self.platforms, True, False)
        collide = pygame.sprite.spritecollide(self.player, self.enemyRocket, False)
        collideWithEND = pygame.sprite.spritecollide(self.player, self.endLevel, False)
        collideWithFuel = pygame.sprite.groupcollide(self.bullet_list, self.fuel, True, True)

        if collision:
            self.player_health -= 1
            self.new()
        if collide:
            self.player_health -= 1
            self.new()
        if collideGroup:
            self.score += 10
        if collideWithEND:
            self.level += 1
        if collideWithFuel:
            self.fuelBar += 10

Should I add in sprites classes some functions to detect collisions or should I open another class for collisions.
Here are my spites classes.

    class Player(pygame.sprite.Sprite):
    def __init__(self, img, pos_x, pos_y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(os.path.join('images', img)).convert()
        self.image.convert_alpha()
        self.image.set_colorkey(ALPHA)
        self.rect = self.image.get_rect()
        self.rect.center = (pos_x, pos_y)
        self.vx = 0
        self.vy = 0

    def update(self):
        self.vx = 0
        self.vy = 0
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            self.vy = -5
            if self.rect.y < 0:
                self.rect.y += 5
        if keys[pygame.K_DOWN]:
            self.vy = 3
        if keys[pygame.K_RIGHT]:
            self.vx = 3
            if self.rect.x > (WIDTH-58):
                self.rect.x -= 5
        if keys[pygame.K_LEFT]:
            self.vx = -5
            if self.rect.x < 0:
                self.rect.x += 5

        self.rect.x += self.vx
        self.rect.y += self.vy

class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((5, 3))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.vx = 0

    def update(self):
        keys = pygame.key.get_pressed()

        self.rect.x += self.vx
        if self.rect.x > WIDTH:
            self.kill()
        if keys[pygame.K_SPACE]:
            self.vx = 2
        self.rect.x += self.vx


问:
Get error Error response from daemon: OCI runtime create failed: container_linux.go:344 if I try to publish port
I am new to docker and I am following the tutorial
https://github.com/docker/labs/blob/master/beginner/chapters/webapps.md

After I have build my image (named expose-static), I can run
docker run expose-static

However, if I do something like this to publish port:

```<code>docker run expose-static -p 5000:5000
</code>```

It fails and gives the error:

```<code>C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error response from daemon: OCI runtime create failed: container_linux.go:344: starting container process caused "exec: \"-p\": executable file not found in $PATH": unknown.
</code>```

This is the console output if I do docker ps

```<code>CONTAINER ID        IMAGE               COMMAND                  CREATED          STATUS              PORTS               NAMES
9f8c404eadf4        expose-static       "/bin/sh -c 'cd /usr…"   2 minutes ago       Up 2 minutes        80/tcp, 5000/tcp    <some_name_I_dunno>
</code>```

content of my Dockerfile

```<code>FROM nginx
EXPOSE 5000
ENV AUTHOR=Docker

WORKDIR /usr/share/nginx/html
COPY Hello_docker.html /usr/share/nginx/html

CMD cd /usr/share/nginx/html && sed -e s/Docker/"$AUTHOR"/ Hello_docker.html > index.html ; nginx -g 'daemon off;'
</code>```

答:
Instead of doing

```<code>docker run expose-static -p 5000:5000
</code>```

Doing

```<code>docker run -p 5000:5000 expose-static
</code>```

will not run into problem

Body:
I am new to docker and I am following the tutorial
https://github.com/docker/labs/blob/master/beginner/chapters/webapps.md

After I have build my image (named expose-static), I can run
docker run expose-static

However, if I do something like this to publish port:

docker run expose-static -p 5000:5000

It fails and gives the error:

C:\Program Files\Docker\Docker\Resources\bin\docker.exe: Error response from daemon: OCI runtime create failed: container_linux.go:344: starting container process caused "exec: \"-p\": executable file not found in $PATH": unknown.

This is the console output if I do docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED          STATUS              PORTS               NAMES
9f8c404eadf4        expose-static       "/bin/sh -c 'cd /usr…"   2 minutes ago       Up 2 minutes        80/tcp, 5000/tcp    <some_name_I_dunno>

content of my Dockerfile

FROM nginx
EXPOSE 5000
ENV AUTHOR=Docker

WORKDIR /usr/share/nginx/html
COPY Hello_docker.html /usr/share/nginx/html

CMD cd /usr/share/nginx/html && sed -e s/Docker/"$AUTHOR"/ Hello_docker.html > index.html ; nginx -g 'daemon off;'

Body:
Instead of doing

docker run expose-static -p 5000:5000

Doing

docker run -p 5000:5000 expose-static

will not run into problem


答:
Try creating some classes that define the structure of your JSON:

```<code>public class RequestVm
{
    public long Id { get; set; }
    public Dictionary<string, CallTrackingProfileVm> callTrackingProfiles { get; set; }
}

public class CallTrackingProfileVm
{
    public string destinationPhoneNumber { get; set; }
    public List<PhoneNumberVm> phones { get; set; }
}

public class PhoneNumberVm
{
    public int phoneType { get; set; }
    public string phoneNumber { get; set; }
    public bool destinationWhisper { get; set; }
    public bool isLocal { get; set; }
    public bool recordCalls { get; set; }
    public string countryCode { get; set; }
}
</code>```

Then you can iterate over it like so:

```<code>var jsonResults = JsonConvert.DeserializeObject<RequestVm>(str);
var profiles = jsonResults.callTrackingProfiles;
foreach(var value in profiles.Values)
{
    var phone = value.destinationPhoneNumber;
}
</code>```

Title: How to get values from this json object?

Body:
Try creating some classes that define the structure of your JSON:

public class RequestVm
{
    public long Id { get; set; }
    public Dictionary<string, CallTrackingProfileVm> callTrackingProfiles { get; set; }
}

public class CallTrackingProfileVm
{
    public string destinationPhoneNumber { get; set; }
    public List<PhoneNumberVm> phones { get; set; }
}

public class PhoneNumberVm
{
    public int phoneType { get; set; }
    public string phoneNumber { get; set; }
    public bool destinationWhisper { get; set; }
    public bool isLocal { get; set; }
    public bool recordCalls { get; set; }
    public string countryCode { get; set; }
}

Then you can iterate over it like so:

var jsonResults = JsonConvert.DeserializeObject<RequestVm>(str);
var profiles = jsonResults.callTrackingProfiles;
foreach(var value in profiles.Values)
{
    var phone = value.destinationPhoneNumber;
}


问:
extern declaration and definition in C
a global variable may one to two different storage classes in C, to my best knowledge, and the declaration may be given with two different keywords, correspodingly

```<code>extern int foo; //default
static int bar;
</code>```

Static variables are only visible within the module of declaration, and cannot be exported. In case of extern declaration, the variable is in the common namespace of all modules linked, unless shadowed by static variable.

Whereas static variables have to be defined in their module, an extern variable may be defined somewhere else. It has to be defined if ever used.

My compiler (GCC) accepts

```<code>static int bar = 5;
</code>```

but casts a complain at

```<code>extern int foo = 4;
</code>```

It seems to be expected that extern variables are never defined with the keyword 'extern'. This leads to the following question:

What kind of storage class does the Object 'foo' in the example above have in the module where it is defined?

答:
Actually you missed two storage classes: auto and register

Register doesn't matter here but the default storage class is auto.

Auto reserves space for a variable somewhere in the memory (which is usually what you want when you declare a variable). It should be noted that for 'auto variables' new space will be allocated every time the scope of the variable is entered. (i.e. calling the function func() from within func() when func() declares an 'auto' variable will result in two different variables and each call to func() will only know about its own variable.

From this follows that auto variables declared at the global scope will be unique (since the scope is enterd only once).

Static variables however are always unique. Unique in the sense that space will only be allocated once. This is useful when func() calls func() and you want both function calls to operate on the same variable.

Extern variables are simply references to unique variables.

You use these when you want to access a global variable declared in a different file.

Given the files 1.c and 2.c it does not suffice to declare "int global;" in both files because space would be allocated twice and the name clash would result in a linking error.

Hence what you do is in one file to reserve space (using "int global;") and in the other file tell the linker to look for a variable of the name "global" in another file by writing "extern int global;".

Title: extern declaration and definition in C

Body:
a global variable may one to two different storage classes in C, to my best knowledge, and the declaration may be given with two different keywords, correspodingly

extern int foo; //default
static int bar;

Static variables are only visible within the module of declaration, and cannot be exported. In case of extern declaration, the variable is in the common namespace of all modules linked, unless shadowed by static variable.

Whereas static variables have to be defined in their module, an extern variable may be defined somewhere else. It has to be defined if ever used.

My compiler (GCC) accepts

static int bar = 5;

but casts a complain at

extern int foo = 4;

It seems to be expected that extern variables are never defined with the keyword 'extern'. This leads to the following question:

What kind of storage class does the Object 'foo' in the example above have in the module where it is defined?


问:
Common authentication interface for multiple applications
My customer wants to develop several small web applications, each with its own purpose. They want to provide a common interface for external users to login using 2-3 third party identity providers like Okta, that support SAML authentication. Once the user logs in, the applications he is authorized to access should be listed as icons and he should be able to enter an application by clicking on the icon.

Even if there is no interface for listing accessible applications for the user, the customer is fine with having a framework that will force the user to authenticate when he accesses the URL of an application directly and allow access only if the user is authorized.

This sounds like a common requirement of many organizations that want to expose their applications to external or internal users with proper authorization controls. Is there a common pattern/framework to achieve this?

答:
In the .NET world, decorating a method in the application with:

[Authorize]

forces the user to authenticate with the configured IDP.

Using e.g. ADFS as an IDP, the user sees a Home Realm Discovery page that shows the user all the IDP available for the user to authenticate on.

In Azure AD, all the applications that a user has permissions to use appear in:

myapps.microsoft.com

There are similar "patterns" for other providers but I'm not aware of any formal specification.


问:
AWS : Invalid identity pool configuration. Check assigned IAM roles for this pool
I have created one user pool & identity pool.

I have used javascript sdk.

I am able to signup, send confirmation code & confirm user successfully with javascript sdk.

But when i try to sign in user with authenticate method & try to get credentials with "CognitoIdentityCredentials" by passing idToken with below code

```<code>logins[cognitoEndpoint + "/" + userPoolId] = jwtToken;

    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: identityPoolId,
      Logins: logins
    });
</code>```

it's giving me below error

```<code>Error: Invalid identity pool configuration. Check assigned IAM roles for this pool.
    at Request.extractError (aws-sdk.js:104063)
    at Request.callListeners (aws-sdk.js:106060)
    at Request.emit (aws-sdk.js:106034)
    at Request.emit (aws-sdk.js:105121)
    at Request.transition (aws-sdk.js:104843)
    at AcceptorStateMachine.runTo (aws-sdk.js:108480)
    at aws-sdk.js:108492
    at Request.<anonymous> (aws-sdk.js:104859)
    at Request.<anonymous> (aws-sdk.js:105123)
    at Request.callListeners (aws-sdk.js:106070)
</code>```

I have given administrator access to "Unauthenticated role" & "Unauthenticated role"  of identity pool and to user whose credentials i am using.

I am new to aws. Can anyone tell me what am i missing?

Any help would be appreciated.

答: When you create role in IAM and choose identity provider, make sure you don't choose user pool id, instead, you have to choose identity pool id.

Body:
I have created one user pool & identity pool.

I have used javascript sdk.

I am able to signup, send confirmation code & confirm user successfully with javascript sdk.

But when i try to sign in user with authenticate method & try to get credentials with "CognitoIdentityCredentials" by passing idToken with below code

logins[cognitoEndpoint + "/" + userPoolId] = jwtToken;

    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: identityPoolId,
      Logins: logins
    });

it's giving me below error

Error: Invalid identity pool configuration. Check assigned IAM roles for this pool.
    at Request.extractError (aws-sdk.js:104063)
    at Request.callListeners (aws-sdk.js:106060)
    at Request.emit (aws-sdk.js:106034)
    at Request.emit (aws-sdk.js:105121)
    at Request.transition (aws-sdk.js:104843)
    at AcceptorStateMachine.runTo (aws-sdk.js:108480)
    at aws-sdk.js:108492
    at Request.<anonymous> (aws-sdk.js:104859)
    at Request.<anonymous> (aws-sdk.js:105123)
    at Request.callListeners (aws-sdk.js:106070)

I have given administrator access to "Unauthenticated role" & "Unauthenticated role"  of identity pool and to user whose credentials i am using.

I am new to aws. Can anyone tell me what am i missing?

Any help would be appreciated.