问:
resource for practical javascript exercise
I am beginner to webprogramming &  Javascript. I have went through few tutorials and learned the basics. Could someone suggest me the best resource with practical exercise with solutions.

I found "pagetutor.com" which has practical javascript exercises, but it's paid! Please
suggest any paid sites too which is really worth for practical learning.

答: This online free eloquent javascript book is awesome. But not much practical exercises.</p>


来源: stackexchange

问:
How to use GraphQL?
I start a tutorial to install graphql with python(graphene). But there is a step I can't reach because I don't know how I can reach it.
Here's the link. After installing Python, pip, GraphQL, WHERE can I write the code to creating a basic schema ?? I have spyder as IDE to code in python but otherwise I don't have anything else, and they don't give any hint to reach this step...</p>

答:
This is a big question, given what you're wanting to do. You should familiarize yourself with basic python project work before approaching this.

I'd suggest going through a tutorial or two regarding the use of modules. One I'd recommend is the free How to Think Like a Computer Scientist. The working with modules section begins at https://runestone.academy/runestone/static/thinkcspy/PythonModules/toctree.html

Working with GraphQL implies that you have some larger project or framework that you'll be working within. Is that the case here?

If you are just starting out, I'd highly recommend the above course, or another. Google, for instance, has a great intro at https://developers.google.com/edu/python/introduction.

If you aren't tied to Spyder, I might suggest you consider VSCode, which is a great IDE for beginners as well as advanced coders. They have a good intro to working with Python at https://code.visualstudio.com/docs/python/python-tutorial.

Forgive me if I've misunderstood your skill level and familiarity.

ContentLicense: CC BY-SA 4.0

Title: How to use GraphQL?


问:
Not able to login in docker private repositry
I configured insecure registry by self singed certificate.After providing user name and password , getting error message as " Error response from daemon: Get https://ip address:5000/v1/users/: x509: certificate signed by unknown authority".

答:
For CentOS7

nano /etc/pki/tls/openssl.cnf

and add

subjectAltName = IP:10.0.1.111

to Your [ v3_ca ] section

where IP is DockerRepositoryIP machine, then generate SSL key's again and send ca.crt to remote host that push image to repo..

ContentLicense: CC BY-SA 3.0


问:
I want to find data from firebase data base like this by using query. if input are matched with stored data then show mobile number
I want to find data from firebase data base like this if(name=="name 1" && age == "age 1" && birth date =="birth date 1"). then show mobile number , how can i face data from firebase by and check itenter image description here</p>

答:
Firebase Real-time Database does not support multiple equal queries so at a time you can use only one equalTo() query of the firebase database so try to apply the field here which breaks your data in the best manner so that you receive the least data to process at your side.

And finally you can apply your rest two equal queries at the backend in the received data to get the desired result.


问:
How to use telnet in a script?
I need to connect in a system where I have to SSH first then telnet. Then I can start executing some command.
I am struggling about the telnet part. Can you tell me how I can make it please? Is there another alternative than spawn please? Thank you

```<code>#!/bin/bash
cat command.sh | sshpass -p 'passowrd' ssh -q -o StrictHostKeyChecking=no root@pc1;
</code>```

Then my command.sh

```<code>#!/bin/bash
spawn telnet pc_modem
expect "login:"
send "root"
expect "Password:"
send "youyou"

cliclient GetMonitoringData;
</code>```

答:
In this use, the shebang has no effect*. You're passing the contents of the script file to ssh to be executed line by line as if each line were separate commands that will be interpreted by the shell instead of expect.

Try changing command.sh to something like:

# no shebang here
/bin/expect -f - <<<'spawn telnet pc_modem
expect "login:"
send "root"
expect "Password:"
send "youyou"

cliclient GetMonitoringData;'
```

This sends the expect script as a here string to expect's STDIN. If you use variables in your expect script you may need to change the quoting or escaping depending on whether they are shell or TCL variables and where the substitution needs to take place.

* The shebang is used by the kernel to select the program to interpret the contents of the file when the file has been marked as executable and is run by invoking the file by its name. When a file is run by explicitly naming the interpreter (e.g. sh run_me or ssh user@host run_me_there) the shebang doesn't come in to play.

Title: How to use telnet in a script?

Body:
I need to connect in a system where I have to SSH first then telnet. Then I can start executing some command.
I am struggling about the telnet part. Can you tell me how I can make it please? Is there another alternative than spawn please? Thank you

#!/bin/bash
cat command.sh | sshpass -p 'passowrd' ssh -q -o StrictHostKeyChecking=no root@pc1;

Then my command.sh

#!/bin/bash
spawn telnet pc_modem
expect "login:"
send "root"
expect "Password:"
send "youyou"

cliclient GetMonitoringData;

Body:
In this use, the shebang has no effect*. You're passing the contents of the script file to ssh to be executed line by line as if each line were separate commands that will be interpreted by the shell instead of expect.

Try changing command.sh to something like:

# no shebang here
/bin/expect -f - <<<'spawn telnet pc_modem
expect "login:"
send "root"
expect "Password:"
send "youyou"

cliclient GetMonitoringData;'

This sends the expect script as a here string to expect's STDIN. If you use variables in your expect script you may need to change the quoting or escaping depending on whether they are shell or TCL variables and where the substitution needs to take place.

* The shebang is used by the kernel to select the program to interpret the contents of the file when the file has been marked as executable and is run by invoking the file by its name. When a file is run by explicitly naming the interpreter (e.g. sh run_me or ssh user@host run_me_there) the shebang doesn't come in to play.


问:
Node dependency/permission errors when installing expo-cli
I am trying to install expo to use react native, using npm install -g expo-cli but I get huge error logs.

I tried to chown /usr/local using sudo chown -R $(whoami) $(brew --prefix)/* /usr/local and sudo chown -R $USER /usr/local  but I get chown: /usr/local: Operation not permitted. I tried updating node and npm, deleting them, reinstalling them, updating with homebrew, installing expo-cli with homebrew. I tried sudo installing. I get similar errors. I tried yarn add global expo-cli and I got almost the exact same output that I got from  npm install -g expo-cli about the dependencies.

Here's the output I get in terminal from running npm install -g expo-cli:

```<code>npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@6.1.3: This module has moved and is now available at @hapi/hoek. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN deprecated topo@3.0.3: This module has moved and is now available at @hapi/topo. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm WARN @expo/dev-tools@0.5.14 requires a peer of @expo/xdl@^53.8.0 but none is installed. You must install peer dependencies yourself.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.

npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).
</code>```

When I try to use yarn add I get the same errors about dependencies but instead of the "npm ERR!" part I get:

```<code>[2/4]   Fetching packages...
info @expo/traveling-fastlane-linux@1.9.4: The platform "darwin" is incompatible with this module.
info "@expo/traveling-fastlane-linux@1.9.4" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-darwin-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
info "@expo/ngrok-bin-darwin-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-arm@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-linux-arm64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-arm64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm64@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-freebsd-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-freebsd-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-freebsd-ia32@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-freebsd-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-freebsd-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-linux-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-sunos-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-sunos-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-win32-ia32@2.2.8-beta.1" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-win32-x64@2.2.8-beta.1: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-win32-x64@2.2.8-beta.1" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-ia32@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
[3/4]   Linking dependencies...
warning "expo-cli > @expo/dev-tools@0.5.14" has incorrect peer dependency "@expo/xdl@^53.8.0".
error An unexpected error occurred: "EACCES: permission denied, unlink '/Users/<username>/node_modules/.bin/detect-libc'".
info If you think this is a bug, please open a bug report with the information provided in "/Users/<username>/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
</code>```

When I run sudo npm install -g expo-cli I get the following:

```<code>npm WARN deprecated joi@14.0.4: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@3.0.3: This module has moved and is now available at @hapi/topo. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN deprecated hoek@6.1.3: This module has moved and is now available at @hapi/hoek. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.

> @expo/traveling-fastlane-darwin@1.9.4 preinstall /usr/local/lib/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-darwin
> node platform.js

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
/usr/local/bin/expo-cli -> /usr/local/lib/node_modules/expo-cli/bin/expo.js
/usr/local/bin/expo -> /usr/local/lib/node_modules/expo-cli/bin/expo.js

> fsevents@1.2.9 install /usr/local/lib/node_modules/expo-cli/node_modules/fsevents
> node install

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

> iltorb@2.4.3 install /usr/local/lib/node_modules/expo-cli/node_modules/iltorb
> node ./scripts/install.js || node-gyp rebuild

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
sh: node-gyp: command not found
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied

> sharp@0.22.1 install /usr/local/lib/node_modules/expo-cli/node_modules/sharp
> (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
sh: node-gyp: command not found
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
npm WARN @expo/dev-tools@0.5.14 requires a peer of @expo/xdl@^53.8.0 but none is installed. You must install peer dependencies yourself.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-linux@1.9.4 (node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/traveling-fastlane-linux@1.9.4: wanted {"os":"win32,linux","arch":"any"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-win32-x64@2.2.8-beta.1 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-win32-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-win32-x64@2.2.8-beta.1: wanted {"os":"win32","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-win32-ia32@2.2.8-beta.1 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-win32-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: wanted {"os":"win32","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-sunos-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-sunos-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-sunos-x64@2.2.8: wanted {"os":"sunos","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-x64@2.2.8: wanted {"os":"linux","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-ia32@2.2.8: wanted {"os":"linux","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-arm64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-arm64@2.2.8: wanted {"os":"linux","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-arm@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-arm):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-arm@2.2.8: wanted {"os":"linux","arch":"arm"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-freebsd-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-freebsd-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-freebsd-ia32@2.2.8: wanted {"os":"freebsd","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-freebsd-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-freebsd-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-freebsd-x64@2.2.8: wanted {"os":"freebsd","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-darwin-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-darwin-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-darwin-ia32@2.2.8: wanted {"os":"darwin","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-darwin@1.9.4 (node_modules/expo-cli/node_modules/@expo/traveling-fastlane-darwin):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-darwin@1.9.4 preinstall: `node platform.js`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/expo-cli/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 install: `node install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: iltorb@2.4.3 (node_modules/expo-cli/node_modules/iltorb):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: iltorb@2.4.3 install: `node ./scripts/install.js || node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: spawn ENOENT

npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! sharp@0.22.1 install: `(node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the sharp@0.22.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

I expected the output to say something like expo installed ok but instead it gives me the error logs about dependencies and permissions.

答:
You need to have super user access to install a package globally. Try:
sudo npm install -g expo-cli

Body:
I am trying to install expo to use react native, using npm install -g expo-cli but I get huge error logs.

I tried to chown /usr/local using sudo chown -R $(whoami) $(brew --prefix)/* /usr/local and sudo chown -R $USER /usr/local  but I get chown: /usr/local: Operation not permitted. I tried updating node and npm, deleting them, reinstalling them, updating with homebrew, installing expo-cli with homebrew. I tried sudo installing. I get similar errors. I tried yarn add global expo-cli and I got almost the exact same output that I got from  npm install -g expo-cli about the dependencies.

Here's the output I get in terminal from running npm install -g expo-cli:

npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@6.1.3: This module has moved and is now available at @hapi/hoek. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN deprecated topo@3.0.3: This module has moved and is now available at @hapi/topo. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm WARN @expo/dev-tools@0.5.14 requires a peer of @expo/xdl@^53.8.0 but none is installed. You must install peer dependencies yourself.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.

npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

When I try to use yarn add I get the same errors about dependencies but instead of the "npm ERR!" part I get:

[2/4]   Fetching packages...
info @expo/traveling-fastlane-linux@1.9.4: The platform "darwin" is incompatible with this module.
info "@expo/traveling-fastlane-linux@1.9.4" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-darwin-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
info "@expo/ngrok-bin-darwin-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-arm@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-linux-arm64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-arm64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm64@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-freebsd-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-freebsd-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-freebsd-ia32@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-freebsd-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-freebsd-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-linux-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-sunos-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-sunos-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-win32-ia32@2.2.8-beta.1" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-win32-x64@2.2.8-beta.1: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-win32-x64@2.2.8-beta.1" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-ia32@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
[3/4]   Linking dependencies...
warning "expo-cli > @expo/dev-tools@0.5.14" has incorrect peer dependency "@expo/xdl@^53.8.0".
error An unexpected error occurred: "EACCES: permission denied, unlink '/Users/<username>/node_modules/.bin/detect-libc'".
info If you think this is a bug, please open a bug report with the information provided in "/Users/<username>/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

When I run sudo npm install -g expo-cli I get the following:

npm WARN deprecated joi@14.0.4: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@3.0.3: This module has moved and is now available at @hapi/topo. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN deprecated hoek@6.1.3: This module has moved and is now available at @hapi/hoek. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.

> @expo/traveling-fastlane-darwin@1.9.4 preinstall /usr/local/lib/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-darwin
> node platform.js

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
/usr/local/bin/expo-cli -> /usr/local/lib/node_modules/expo-cli/bin/expo.js
/usr/local/bin/expo -> /usr/local/lib/node_modules/expo-cli/bin/expo.js

> fsevents@1.2.9 install /usr/local/lib/node_modules/expo-cli/node_modules/fsevents
> node install

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

> iltorb@2.4.3 install /usr/local/lib/node_modules/expo-cli/node_modules/iltorb
> node ./scripts/install.js || node-gyp rebuild

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
sh: node-gyp: command not found
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied

> sharp@0.22.1 install /usr/local/lib/node_modules/expo-cli/node_modules/sharp
> (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
sh: node-gyp: command not found
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
npm WARN @expo/dev-tools@0.5.14 requires a peer of @expo/xdl@^53.8.0 but none is installed. You must install peer dependencies yourself.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-linux@1.9.4 (node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/traveling-fastlane-linux@1.9.4: wanted {"os":"win32,linux","arch":"any"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-win32-x64@2.2.8-beta.1 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-win32-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-win32-x64@2.2.8-beta.1: wanted {"os":"win32","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-win32-ia32@2.2.8-beta.1 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-win32-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: wanted {"os":"win32","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-sunos-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-sunos-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-sunos-x64@2.2.8: wanted {"os":"sunos","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-x64@2.2.8: wanted {"os":"linux","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-ia32@2.2.8: wanted {"os":"linux","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-arm64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-arm64@2.2.8: wanted {"os":"linux","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-arm@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-arm):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-arm@2.2.8: wanted {"os":"linux","arch":"arm"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-freebsd-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-freebsd-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-freebsd-ia32@2.2.8: wanted {"os":"freebsd","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-freebsd-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-freebsd-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-freebsd-x64@2.2.8: wanted {"os":"freebsd","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-darwin-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-darwin-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-darwin-ia32@2.2.8: wanted {"os":"darwin","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-darwin@1.9.4 (node_modules/expo-cli/node_modules/@expo/traveling-fastlane-darwin):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-darwin@1.9.4 preinstall: `node platform.js`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/expo-cli/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 install: `node install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: iltorb@2.4.3 (node_modules/expo-cli/node_modules/iltorb):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: iltorb@2.4.3 install: `node ./scripts/install.js || node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: spawn ENOENT

npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! sharp@0.22.1 install: `(node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the sharp@0.22.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I expected the output to say something like expo installed ok but instead it gives me the error logs about dependencies and permissions.


问:
What's the difference between a "pull request" and a "branch"?
What's the difference between a "pull request" and a "branch"?

pull request
  branch

答:
In a few words and adding the concept of 'Merge':

Branch: you take the project at a certain stage and start a new 'version' where you can make further changes or improvements. The original version can evolve, while the new version can also evolve with further changes ('commits').

This is how a branch looks like:

Merge: at a certain point, you may want to include all the changes that you were making... let's merge both branches then:

Pull Request: in some projects, you may have permission to start a new branch but not to merge this branch back into the main branch (or maybe you just want your colleagues to have a look and review before integrating). Then you start a pull request. It's like "Hey guys, have a look at this... do you think we can merge those changes into this other branch?".


问:
TextBlock selective line coloring
I want to read a file and then, based on some conditions, mark some lines with different colors.
I have found similar problems&answers, but its not written using MVVM pattern:
Selective coloring on dynamic TextBlock content in WPF

I have tried:

```<code><ScrollViewer>
  <TextBlock >
    <Run Background="{Binding Path=DiffStatus}" Text="{Binding Path=Diff,   Mode=OneWay}"/>
  </TextBlock>
</ScrollViewer>
</code>```

But it is coloring whole text, not only selected lines

答:
My usual way of doing this is with an ItemsControl, you can replace the panel with a WrapPanel and the item template with a TextBlock containing all your bindings:

```<code><ItemsControl ItemsSource="{Binding Elements}">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Text}">
                <TextBlock.Foreground>
                    <SolidColorBrush Color="{Binding Foreground}" />
                </TextBlock.Foreground>
            </TextBlock>
        </DataTemplate>
    </ItemsControl.ItemTemplate>

</ItemsControl>
</code>```

Then back in your viewmodel you can do something like this:

```<code>public class MainViewModel
{
    public TextElement[] Elements { get; } = new TextElement[]
    {
        new TextElement{ Text="Hello World! "},
        new TextElement{ Text="This is some blue text!", Foreground=Colors.Blue }
    };
}

public class TextElement
{
    public string Text { get; set; }
    public Color Foreground { get; set; } = Colors.Black;
}
</code>```

Results:

Obviously if you want a dynamic document then you'd replace the TextElement[] with an ObservableCollection<TextElement> and add INPC etc.

This is more heavy-weight than adding runs and spans etc, but on the plus side you can replace the item template with typed DataTemplates in your resources block which allows you to easily embed graphics or anything else you want.

The only other way I've managed to achieve this is with a generic custom behavior that binds to an ObservableCollection and manages the child GUI elements manually.

Title: TextBlock selective line coloring

Body:
I want to read a file and then, based on some conditions, mark some lines with different colors.
I have found similar problems&answers, but its not written using MVVM pattern:
Selective coloring on dynamic TextBlock content in WPF

I have tried:

<ScrollViewer>
  <TextBlock >
    <Run Background="{Binding Path=DiffStatus}" Text="{Binding Path=Diff,   Mode=OneWay}"/>
  </TextBlock>
</ScrollViewer>

But it is coloring whole text, not only selected lines

Body:
My usual way of doing this is with an ItemsControl, you can replace the panel with a WrapPanel and the item template with a TextBlock containing all your bindings:

<ItemsControl ItemsSource="{Binding Elements}">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Text}">
                <TextBlock.Foreground>
                    <SolidColorBrush Color="{Binding Foreground}" />
                </TextBlock.Foreground>
            </TextBlock>
        </DataTemplate>
    </ItemsControl.ItemTemplate>

</ItemsControl>

Then back in your viewmodel you can do something like this:

public class MainViewModel
{
    public TextElement[] Elements { get; } = new TextElement[]
    {
        new TextElement{ Text="Hello World! "},
        new TextElement{ Text="This is some blue text!", Foreground=Colors.Blue }
    };
}

public class TextElement
{
    public string Text { get; set; }
    public Color Foreground { get; set; } = Colors.Black;
}

Results:

Obviously if you want a dynamic document then you'd replace the TextElement[] with an ObservableCollection<TextElement> and add INPC etc.

This is more heavy-weight than adding runs and spans etc, but on the plus side you can replace the item template with typed DataTemplates in your resources block which allows you to easily embed graphics or anything else you want.

The only other way I've managed to achieve this is with a generic custom behavior that binds to an ObservableCollection and manages the child GUI elements manually.


问:
Log4J - Is there any point in explicitly specifying the class name in the call to LogManager.getLogger()?
I'm working on some legacy code with a lot of code like

```<code>private final Logger logger = LogManager.getLogger(ThisClassName.class);
</code>```

I'm wondering if there is any advantage to typing out "ThisClassName.class" as opposed to

```<code>LogManager.getLogger(getClass());
</code>```

As far as I can tell, there is none, but I'm wondering if there are any negative ramifications to using getClass().  Thanks.

答: Also, getClass() will obscure the actual class if there's a subclass that's actually invoking the method. For example, assume that in class A, method X, you call log.debug() and class B extends class A, overwriting method X, but calling super.X at some point. The log file will show class B, not class A.</p>

OwnerDisplayName: nc

ContentLicense: CC BY-SA 2.5

Body:
I'm working on some legacy code with a lot of code like

private final Logger logger = LogManager.getLogger(ThisClassName.class);

I'm wondering if there is any advantage to typing out "ThisClassName.class" as opposed to

LogManager.getLogger(getClass());

As far as I can tell, there is none, but I'm wondering if there are any negative ramifications to using getClass().  Thanks.

OwnerDisplayName: Gary Kephart


问:
Python - Find similar colors, best way
I've made a function to find a color within a image, and return x, y. Now I need to add a new function, where I can find a color with a given tolerence. Should be easy?

Code to find color in image, and return x, y:

```<code>def FindColorIn(r,g,b, xmin, xmax, ymin, ymax):
    image = ImageGrab.grab()
    for x in range(xmin, xmax):
        for y in range(ymin,ymax):
            px = image.getpixel((x, y))
            if px[0] == r and px[1] == g and px[2] == b:
                return x, y

def FindColor(r,g,b):
    image = ImageGrab.grab()
    size = image.size
    pos = FindColorIn(r,g,b, 1, size[0], 1, size[1])
    return pos
</code>```

Outcome:

Taken from the answers the normal methods of comparing two colors are in Euclidean distance, or Chebyshev distance.

I decided to mostly use (squared) euclidean distance, and multiple different color-spaces. LAB, deltaE (LCH), XYZ, HSL, and RGB. In my code, most color-spaces use squared euclidean distance to compute the difference.

For example with LAB, RGB and XYZ a simple squared euc. distance does the trick:

```<code>if ((X-X1)^2 + (Y-Y1)^2 + (Z-Z1)^2) <= (Tol^2) then
  ...
</code>```

LCH, and HSL is a little more complicated as both have a cylindrical hue, but some piece of math solves that, then it's on to using squared eucl. here as well.

In most these cases I've added "separate parameters" for tolerance for each channel (using 1 global tolerance, and alternative "modifiers" HueTol := Tolerance * hueMod or LightTol := Tolerance * LightMod).

It seems like colorspaces built on top of XYZ (LAB, LCH) does perform best in many of my scenarios. Tho HSL yields very good results in some cases, and it's much cheaper to convert to from RGB, RGB is also great tho, and fills most of my needs.

答:
Here is a simple function that does not require any libraries:

```<code>def color_distance(rgb1, rgb2):
    rm = 0.5 * (rgb1[0] + rgb2[0])
    rd = ((2 + rm) * (rgb1[0] - rgb2[0])) ** 2
    gd = (4 * (rgb1[1] - rgb2[1])) ** 2
    bd = ((3 - rm) * (rgb1[2] - rgb2[2])) ** 2
    return (rd + gd + bd) ** 0.5
</code>```

assuming that rgb1 and rgb2 are RBG tuples

Title: Python - Find similar colors, best way

Body:
I've made a function to find a color within a image, and return x, y. Now I need to add a new function, where I can find a color with a given tolerence. Should be easy?

Code to find color in image, and return x, y:

def FindColorIn(r,g,b, xmin, xmax, ymin, ymax):
    image = ImageGrab.grab()
    for x in range(xmin, xmax):
        for y in range(ymin,ymax):
            px = image.getpixel((x, y))
            if px[0] == r and px[1] == g and px[2] == b:
                return x, y

def FindColor(r,g,b):
    image = ImageGrab.grab()
    size = image.size
    pos = FindColorIn(r,g,b, 1, size[0], 1, size[1])
    return pos

Outcome:

Taken from the answers the normal methods of comparing two colors are in Euclidean distance, or Chebyshev distance.

I decided to mostly use (squared) euclidean distance, and multiple different color-spaces. LAB, deltaE (LCH), XYZ, HSL, and RGB. In my code, most color-spaces use squared euclidean distance to compute the difference.

For example with LAB, RGB and XYZ a simple squared euc. distance does the trick:

if ((X-X1)^2 + (Y-Y1)^2 + (Z-Z1)^2) <= (Tol^2) then
  ...

LCH, and HSL is a little more complicated as both have a cylindrical hue, but some piece of math solves that, then it's on to using squared eucl. here as well.

In most these cases I've added "separate parameters" for tolerance for each channel (using 1 global tolerance, and alternative "modifiers" HueTol := Tolerance * hueMod or LightTol := Tolerance * LightMod).

It seems like colorspaces built on top of XYZ (LAB, LCH) does perform best in many of my scenarios. Tho HSL yields very good results in some cases, and it's much cheaper to convert to from RGB, RGB is also great tho, and fills most of my needs.

Body:
Here is a simple function that does not require any libraries:

def color_distance(rgb1, rgb2):
    rm = 0.5 * (rgb1[0] + rgb2[0])
    rd = ((2 + rm) * (rgb1[0] - rgb2[0])) ** 2
    gd = (4 * (rgb1[1] - rgb2[1])) ** 2
    bd = ((3 - rm) * (rgb1[2] - rgb2[2])) ** 2
    return (rd + gd + bd) ** 0.5

assuming that rgb1 and rgb2 are RBG tuples


问:
Implementing a count sort is crashing my program every time, cannot spot malloc/free error
I've been stuck on this for a while and absolutely cannot find a solution to my problem. I following along Sedgewick's algorithms in C to implement a count sort, but for some reason my b array is not reading the values of my input array correctly, and also crashes the program when trying to free. Any help will be appreciated.

void count_sort(int* a, int l, int r, int M)
{
    int i, j;
    int* cnt = (int*)malloc(M * sizeof(int));
    if (!cnt) {
        printf("Returned NULL PTR for cnt\n");
        exit(1);
    }
    int* b = (int*)malloc((r + 1) * sizeof(int));
    if (!b) {
        printf("Returned NULL PTR for b\n");
        exit(1);
    }
    printf("\n\n\n");

    for (j = 0; j < M; ++j)
        cnt[j] = 0;
    for (i = l; i <= r; ++i)
        cnt[a[i]]++;
    for (i = 1; i < M; ++i)
        cnt[i] += cnt[i - 1];

    /*
free(b);
free(cnt);
printf("Able to free here\n");
exit(0);
*/

    for (i = l; i <= r; ++i) {
        b[cnt[a[i]]] = a[i];
        printf("%d\n", b[cnt[a[i]]]);
        ++cnt[a[i]];
    }

    /*
free(b);
free(cnt);
printf("Able to free here\n");
exit(0);
*/
    for (i = l; i <= r; ++i)
        a[i] = b[i - l];

    free(cnt);
    free(b);
}

int is_sort(int* a, int N)
{
    int i;
    for (i = 0; i < N - 1; ++i) {
        if (a[i + 1] < a[i]) {
            printf("%d %d\t%d %d\n", i, a[i], i + 1, a[i + 1]);
            return 0;
        }
    }
    return 1;
}

int main(int argc, char** argv)
{

    srand(time(NULL));
    rand();

    int N = atoi(argv[1]);
    int M = atoi(argv[2]);

    int* arr = (int*)malloc(N * sizeof(int));
    int i;
    for (i = 0; i < N; ++i) {
        arr[i] = ((int)(1000 * (1.0 * rand() / RAND_MAX))) % M;
        printf("%d\n", arr[i]);
    }

    count_sort(arr, 0, N - 1, M);
    if (is_sort(arr, N))
        printf("sorted\n");
    else
        printf("not sorted");

    free(arr);
    return 0;
}
```

答:
The issue lies in these lines:

```<code>
    for (i = l; i <=r; ++i) {
        b[cnt[a[i]]] = a[i];
        printf("%d\n", b[cnt[a[i]]]);
        ++cnt[a[i]];
    }
</code>```

You want to decrement cnt[a[i]], not increment and also you want to do it before the assignment b[cnt[a[i]]] = a[i];, not after.

With these modifications the code works correctly.

Body:
The issue lies in these lines:

    for (i = l; i <=r; ++i) {
        b[cnt[a[i]]] = a[i];
        printf("%d\n", b[cnt[a[i]]]);
        ++cnt[a[i]];
    }

You want to decrement cnt[a[i]], not increment and also you want to do it before the assignment b[cnt[a[i]]] = a[i];, not after.

With these modifications the code works correctly.


问:
Ray-bounded plane intersection
I'm trying to write a ray tracer in my freetime. Currently trying to do ray - bounded plane intersections.

My program is already working with infinite planes. I'm trying to work out the math for non-infinite planes. Tried to google, but all of the resources talk only about infinite planes.

My plane has a corner point (called position), from which two vectors (u and v) extend (their length correspond to the length of the sides). The ray has an origin and a direction.

First I calculate the intersection point with an infinite plane with the formula

t = normal * (position - origin) / (normal * direction)

The normal is calculated as a cross product of u and v.
Then with the formula

origin + direction * t

I get the intersection point itself.

The next step is checking if this point is in the bounds of the rectangle, and this is where I'm having trouble.

My idea was to get the relative vector intersection - position that is extending from the corner of the plane to the intersection point, then transform it to a new basis of u, normal and v then check if the lengths of the transformed vectors are shorter than the u and v vectors.

bool BoundedPlane::intersect(const Vec3f &origin, const Vec3f &direction, float &t) const {
    t = normal * (position - origin) / (normal * direction);
    Vec3f relative = (origin + direction * t) - position;

    Mat3f transform{
        Vec3f(u.x, normal.x, v.x),
        Vec3f(u.y, normal.y, v.y),
        Vec3f(u.z, normal.z, v.z)
    };

    Vec3f local = transform.mul(relative);
    return t > 0 && local.x >= 0 && local.x <= u.x && local.z <= 0 && local.z <= v.z;

}
```

<p>At the end I check if t is larger than 0, meaning the intersection is in front of the camera, and if the lengths of the vectors are inside the bounds. This gives me a weird line:</p>

<p><img src="https://i.stack.imgur.com/UYFGi.png" alt="weird line">. </p>

<p>The plane should appear below the spheres like this:</p>

<p><img src="https://i.stack.imgur.com/Qd99l.png" alt="like this"> </p>

<p>(this used manual checking to see if it appears correctly if the numbers are right). </p>

<p>I'm not sure what I'm doing wrong, and if there's an easier way to check the bounds. Thanks in advance.</p>

<p><strong>Edit1:</strong></p>

<p>I moved the transformation matrix calculations into the constructor, so now the intersection test is:</p>

<pre class="lang-cpp prettyprint-override"><code>bool BoundedPlane::intersect(const Vec3f &origin, const Vec3f &direction, float &t) const {
    if (!InfinitePlane::intersect(origin, direction, t)) {
        return false;
    }

    Vec3f local = transform.mul((origin + direction * t) - position);

    return local.x >= 0 && local.x <= 1 && local.z >= 0 && local.z <= 1;
}
</code>```

The transform member is the inverse of the transformation matrix.

答:
Could I suggest another approach? Consider the frame with origin
position and basis vectors

```<code>u = { u.x, u.y, u.z }
v = { v.x, v.y, v.z }
direction = { direction.x, direction.y, direction.z}
</code>```

Step 1: Form the matrix

```<code>M = {
      {u.x,  v.x,  direction.x},
      {u.y,  v.y,  direction.y},
      {u.z,  v.z,  direction.z}
    }
</code>```

Step 2: Calculate the vector w, which is a solution to the 3 x 3 system of liner equations

M * w = origin - position, i.e.

```<code>w = inverse(M) * (origin - position);
</code>```

Make sure that direction is not coplanar with u,  v, otherwise there is no intersection and inverse(M) does not exist.

Step 3: if 0.0 <= w.x && w.x <= 1.0 && 0.0 <= w.y && w.y <= 1.0 then the line intersects the parallelogram spanned by the vectors u,  v and the point of intersection is

```<code>w0 = { w.x, w.y , 0 };

intersection = position + M * w0;
</code>```

else, the line does not intersect the parallelogram spanned by the vectors u,  v

The idea of this algorithm is to consider the (non-orthonormal) frame position,  u, v, direction. Then the matrix M changes everything in the coordinates of this new frame. In this frame, the line is vertical, parallel to the "z-"axis, the point origin has coordinates w, and the vertical line through w intersects the plane at w0.

Edit 1: Here is a templet formula for the inverse of a 3x3 matrix:

If original matrix M is

```<code>a  b  c

d  e  f

g  h  i
</code>```

inverse is

```<code>(1 / det(M)) * {
                 {e*i - f*h,     c*h - b*i,     b*f - c*e},

                 {f*g - d*i,     a*i - c*g,     c*d - a*f},

                 {d*h - e*g,     b*g - a*h,     a*e - b*d},
                }
</code>```

where

```<code>det(M) = a*(e*i - f*h) + b*(f*g - d*i) + c*(d*h - e*h)
</code>```

is the determinant of M.

So the inversion algorithm can be as follows:

Given

```<code>M = {
      {a,  b,  c},
      {d,  e,  f},
      {g,  h,  i},
    }
</code>```

Calculate

```<code>inv_M = {
           {e*i - f*h,     c*h - b*i,     b*f - c*e},

           {f*g - d*i,     a*i - c*g,     c*d - a*f},

           {d*h - e*g,     b*g - a*h,     a*e - b*d},
         };
</code>```

Calculate

```<code>det_M = a*inv_M[1][1] + b*inv_M[2][1] + c*inv_M[3][1];
</code>```

Return inverse matrix of M

```<code>inv_M = (1/det_M) * inv_M;
</code>```

Edit 2: Let's try another approach in order to speed things up.

Step 1: For each plane, determined by the point position and the two vectors u and v, precompute the following quatntities:

```<code>normal = cross(u, v);

u_dot_u = dot(u, u);

u_dot_v = dot(u, v);

v_dot_v = dot(v, v); // all these need to be computed only once for the u and v vectors

det = u_dot_u * v_dot_v - u_dot_v * u_dot_v; // again only once per u and v
</code>```

Step 2: Now, for a given line with point origin and direction direction, as before, calculate the intersection point int_point with the plane spanned by u and  v:

```<code>t = dot(normal,  position - origin) / dot(normal, direction);

int_point = origin + t * direction;

rhs = int_point - position;
</code>```

Step 3: Calcualte

```<code>u_dot_rhs = dot(u, rhs);

v_dot_rhs = dot(v, rhs);

w1 = (v_dot_v * u_dot_rhs - u_dot_v * v_dot_rhs) / det;

w2 = (- u_dot_v * u_dot_rhs + u_dot_u * v_dot_rhs) / det;
</code>```

Step 4:

```<code>if (0 < = w1 && w1 <= 1 && 0 < = w2 && w2 <= 1 ){
   int_point is in the parallelogram;
}
else{
   int_point is not in the parallelogram;
}
</code>```

So what I am doing here is basically finding the intersection point of the line origin,  direction with the plane given by position,  u,  v and restricting myself to the plane, which allows me to work in 2D rather than 3D. I am representing

```<code>int_point = position + w1 * u + w2 * v;

rhs = int_point - position = w1 * u + w2 * v
</code>```

and finding w1 and w2 by dot-multiplying of this vector expression with the basis vectors u and v, which results in a 2x2 linear system, which I am solving directly.

Title: Ray-bounded plane intersection

Body:
I'm trying to write a ray tracer in my freetime. Currently trying to do ray - bounded plane intersections.

My program is already working with infinite planes. I'm trying to work out the math for non-infinite planes. Tried to google, but all of the resources talk only about infinite planes.

My plane has a corner point (called position), from which two vectors (u and v) extend (their length correspond to the length of the sides). The ray has an origin and a direction.

First I calculate the intersection point with an infinite plane with the formula

t = normal * (position - origin) / (normal * direction)

The normal is calculated as a cross product of u and v.
Then with the formula

origin + direction * t

I get the intersection point itself.

The next step is checking if this point is in the bounds of the rectangle, and this is where I'm having trouble.

My idea was to get the relative vector intersection - position that is extending from the corner of the plane to the intersection point, then transform it to a new basis of u, normal and v then check if the lengths of the transformed vectors are shorter than the u and v vectors.

bool BoundedPlane::intersect(const Vec3f &origin, const Vec3f &direction, float &t) const {
    t = normal * (position - origin) / (normal * direction);
    Vec3f relative = (origin + direction * t) - position;

    Mat3f transform{
        Vec3f(u.x, normal.x, v.x),
        Vec3f(u.y, normal.y, v.y),
        Vec3f(u.z, normal.z, v.z)
    };

    Vec3f local = transform.mul(relative);
    return t > 0 && local.x >= 0 && local.x <= u.x && local.z <= 0 && local.z <= v.z;

}

At the end I check if t is larger than 0, meaning the intersection is in front of the camera, and if the lengths of the vectors are inside the bounds. This gives me a weird line:

.

The plane should appear below the spheres like this:

(this used manual checking to see if it appears correctly if the numbers are right).

I'm not sure what I'm doing wrong, and if there's an easier way to check the bounds. Thanks in advance.

Edit1:

I moved the transformation matrix calculations into the constructor, so now the intersection test is:

bool BoundedPlane::intersect(const Vec3f &origin, const Vec3f &direction, float &t) const {
    if (!InfinitePlane::intersect(origin, direction, t)) {
        return false;
    }

    Vec3f local = transform.mul((origin + direction * t) - position);

    return local.x >= 0 && local.x <= 1 && local.z >= 0 && local.z <= 1;
}

The transform member is the inverse of the transformation matrix.

Body:
Could I suggest another approach? Consider the frame with origin
position and basis vectors

u = { u.x, u.y, u.z }
v = { v.x, v.y, v.z }
direction = { direction.x, direction.y, direction.z}

Step 1: Form the matrix

M = {
      {u.x,  v.x,  direction.x},
      {u.y,  v.y,  direction.y},
      {u.z,  v.z,  direction.z}
    }

Step 2: Calculate the vector w, which is a solution to the 3 x 3 system of liner equations

M * w = origin - position, i.e.

w = inverse(M) * (origin - position);

Make sure that direction is not coplanar with u,  v, otherwise there is no intersection and inverse(M) does not exist.

Step 3: if 0.0 <= w.x && w.x <= 1.0 && 0.0 <= w.y && w.y <= 1.0 then the line intersects the parallelogram spanned by the vectors u,  v and the point of intersection is

w0 = { w.x, w.y , 0 };

intersection = position + M * w0;

else, the line does not intersect the parallelogram spanned by the vectors u,  v

The idea of this algorithm is to consider the (non-orthonormal) frame position,  u, v, direction. Then the matrix M changes everything in the coordinates of this new frame. In this frame, the line is vertical, parallel to the "z-"axis, the point origin has coordinates w, and the vertical line through w intersects the plane at w0.

Edit 1: Here is a templet formula for the inverse of a 3x3 matrix:

If original matrix M is

a  b  c

d  e  f

g  h  i

inverse is

(1 / det(M)) * {
                 {e*i - f*h,     c*h - b*i,     b*f - c*e},

                 {f*g - d*i,     a*i - c*g,     c*d - a*f},

                 {d*h - e*g,     b*g - a*h,     a*e - b*d},
                }

where

det(M) = a*(e*i - f*h) + b*(f*g - d*i) + c*(d*h - e*h)

is the determinant of M.

So the inversion algorithm can be as follows:

Given

M = {
      {a,  b,  c},
      {d,  e,  f},
      {g,  h,  i},
    }

Calculate

inv_M = {
           {e*i - f*h,     c*h - b*i,     b*f - c*e},

           {f*g - d*i,     a*i - c*g,     c*d - a*f},

           {d*h - e*g,     b*g - a*h,     a*e - b*d},
         };

Calculate

det_M = a*inv_M[1][1] + b*inv_M[2][1] + c*inv_M[3][1];

Return inverse matrix of M

inv_M = (1/det_M) * inv_M;

Edit 2: Let's try another approach in order to speed things up.

Step 1: For each plane, determined by the point position and the two vectors u and v, precompute the following quatntities:

normal = cross(u, v);

u_dot_u = dot(u, u);

u_dot_v = dot(u, v);

v_dot_v = dot(v, v); // all these need to be computed only once for the u and v vectors

det = u_dot_u * v_dot_v - u_dot_v * u_dot_v; // again only once per u and v

Step 2: Now, for a given line with point origin and direction direction, as before, calculate the intersection point int_point with the plane spanned by u and  v:

t = dot(normal,  position - origin) / dot(normal, direction);

int_point = origin + t * direction;

rhs = int_point - position;

Step 3: Calcualte

u_dot_rhs = dot(u, rhs);

v_dot_rhs = dot(v, rhs);

w1 = (v_dot_v * u_dot_rhs - u_dot_v * v_dot_rhs) / det;

w2 = (- u_dot_v * u_dot_rhs + u_dot_u * v_dot_rhs) / det;

Step 4:

if (0 < = w1 && w1 <= 1 && 0 < = w2 && w2 <= 1 ){
   int_point is in the parallelogram;
}
else{
   int_point is not in the parallelogram;
}

So what I am doing here is basically finding the intersection point of the line origin,  direction with the plane given by position,  u,  v and restricting myself to the plane, which allows me to work in 2D rather than 3D. I am representing

int_point = position + w1 * u + w2 * v;

rhs = int_point - position = w1 * u + w2 * v

and finding w1 and w2 by dot-multiplying of this vector expression with the basis vectors u and v, which results in a 2x2 linear system, which I am solving directly.


问:
Can a lambda in an AWS Step Function know the "execution name" of the step function that launched it?
I have this step function that can sometimes fail and I'd like to record this in a (dynamo) DB. What would be handy is if I could just create a new error handling step and that guy would just pick up the "execution name" from somewhere (didn't find it in the context) and record this as a failure.

Is that possible?

答:
AWS Step Functions released recently a feature called context object.

Using $$ notation inside the Parameters block you can access information regarding your execution, including execution name, arn, state machine name, arn and others.

https://docs.aws.amazon.com/step-functions/latest/dg/input-output-contextobject.html


问:
Dijkstra's algorithm with adjacency matrix
I'm trying to implement the following code from here but it won't work correctly.

What I want is the shortest path distances from a source to all nodes and also the predecessors. Also, I want the input of the graph to be an adjacency matrix which contains all of the edge weights.

I'm trying to make it work in just one function so I have to rewrite it. If I'm right the original code calls other functions (from graph.jl for example).

I don't quite understand how to rewrite the for loop which calls the adj() function.

Also, I'm not sure if the input is correct in the way the code is for now.

```<code>function dijkstra(graph, source)
    node_size = size(graph, 1)
    dist = ones(Float64, node_size) * Inf
    dist[source] = 0.0
    Q = Set{Int64}()  # visited nodes
    T = Set{Int64}(1:node_size)  # unvisited nodes
    pred = ones(Int64, node_size) * -1
    while condition(T)
        # node selection
        untraversed_nodes = [(d, k) for (k, d) in enumerate(dist) if k in T]
        if minimum(untraversed_nodes)[1] == Inf
            break # Break if remaining nodes are disconnected
        end
        node_ind = untraversed_nodes[argmin(untraversed_nodes)][2]
        push!(Q, node_ind)
        delete!(T, node_ind)
        # distance update
        curr_node = graph.nodes[node_ind]
        for (neigh, edge) in adj(graph, curr_node)
            t_ind = neigh.index
            weight = edge.cost
            if dist[t_ind] > dist[node_ind] + weight
                dist[t_ind] = dist[node_ind] + weight
                pred[t_ind] = node_ind
            end
        end
    end
    return dist, pred
end
</code>```

So if I'm trying it with the following matrix

```<code>A = [0 2 1 4 5 1; 1 0 4 2 3 4; 2 1 0 1 2 4; 3 5 2 0 3 3; 2 4 3 4 0 1; 3 4 7 3 1 0]
</code>```

and source 2 i would like to get the distances in a vector dist and the predeccessors in anothe vectore pred.

Right now I'm getting

ERROR: type Array has no field nodes

Stacktrace:  [1] getproperty(::Any, ::Symbol) at .\sysimg.jl:18

I guess I have to rewrite it a bit more.

I m  thankful for any help.

答:
Assuming that graph[i,j] is a length of path from i to j (your graph is directed looking at your data), and it is a Matrix with non-negative entries, where 0 indicates no edge from i to j, a minimal rewrite of your code should be something like:

```<code>function dijkstra(graph, source)
    @assert size(graph, 1) == size(graph, 2)
    node_size = size(graph, 1)
    dist = fill(Inf, node_size)
    dist[source] = 0.0
    T = Set{Int}(1:node_size)  # unvisited nodes
    pred = fill(-1, node_size)
    while !isempty(T)
        min_val, min_idx = minimum((dist[v], v) for v in T)
        if isinf(min_val)
            break # Break if remaining nodes are disconnected
        end
        delete!(T, min_idx)
        # distance update
        for nei in 1:node_size
            if graph[min_idx, nei] > 0 && nei in T
                possible_dist = dist[min_idx] + graph[min_idx, nei]
                if possible_dist < dist[nei]
                    dist[nei] = possible_dist
                    pred[nei] = min_idx
                end
            end
        end
    end
    return dist, pred
end
</code>```

(I have not tested it extensively, so please report if you find any bugs)

Body:
I'm trying to implement the following code from here but it won't work correctly.

What I want is the shortest path distances from a source to all nodes and also the predecessors. Also, I want the input of the graph to be an adjacency matrix which contains all of the edge weights.

I'm trying to make it work in just one function so I have to rewrite it. If I'm right the original code calls other functions (from graph.jl for example).

I don't quite understand how to rewrite the for loop which calls the adj() function.

Also, I'm not sure if the input is correct in the way the code is for now.

function dijkstra(graph, source)
    node_size = size(graph, 1)
    dist = ones(Float64, node_size) * Inf
    dist[source] = 0.0
    Q = Set{Int64}()  # visited nodes
    T = Set{Int64}(1:node_size)  # unvisited nodes
    pred = ones(Int64, node_size) * -1
    while condition(T)
        # node selection
        untraversed_nodes = [(d, k) for (k, d) in enumerate(dist) if k in T]
        if minimum(untraversed_nodes)[1] == Inf
            break # Break if remaining nodes are disconnected
        end
        node_ind = untraversed_nodes[argmin(untraversed_nodes)][2]
        push!(Q, node_ind)
        delete!(T, node_ind)
        # distance update
        curr_node = graph.nodes[node_ind]
        for (neigh, edge) in adj(graph, curr_node)
            t_ind = neigh.index
            weight = edge.cost
            if dist[t_ind] > dist[node_ind] + weight
                dist[t_ind] = dist[node_ind] + weight
                pred[t_ind] = node_ind
            end
        end
    end
    return dist, pred
end

So if I'm trying it with the following matrix

A = [0 2 1 4 5 1; 1 0 4 2 3 4; 2 1 0 1 2 4; 3 5 2 0 3 3; 2 4 3 4 0 1; 3 4 7 3 1 0]

and source 2 i would like to get the distances in a vector dist and the predeccessors in anothe vectore pred.

Right now I'm getting

ERROR: type Array has no field nodes

Stacktrace:  [1] getproperty(::Any, ::Symbol) at .\sysimg.jl:18

I guess I have to rewrite it a bit more.

I m  thankful for any help.

Body:
Assuming that graph[i,j] is a length of path from i to j (your graph is directed looking at your data), and it is a Matrix with non-negative entries, where 0 indicates no edge from i to j, a minimal rewrite of your code should be something like:

function dijkstra(graph, source)
    @assert size(graph, 1) == size(graph, 2)
    node_size = size(graph, 1)
    dist = fill(Inf, node_size)
    dist[source] = 0.0
    T = Set{Int}(1:node_size)  # unvisited nodes
    pred = fill(-1, node_size)
    while !isempty(T)
        min_val, min_idx = minimum((dist[v], v) for v in T)
        if isinf(min_val)
            break # Break if remaining nodes are disconnected
        end
        delete!(T, min_idx)
        # distance update
        for nei in 1:node_size
            if graph[min_idx, nei] > 0 && nei in T
                possible_dist = dist[min_idx] + graph[min_idx, nei]
                if possible_dist < dist[nei]
                    dist[nei] = possible_dist
                    pred[nei] = min_idx
                end
            end
        end
    end
    return dist, pred
end

(I have not tested it extensively, so please report if you find any bugs)


问:
Swift: Keep mouse pointer from leaving window
I have a Mac SpriteKit / swift app (a game) where I need to keep the cursor within a window. or at least give some warning when it leaves the game window.

I already have a tracking area set up and am using the mouse to move a game paddle. But when the cursor moves outside the window, the paddle stops working.

```<code> let options = [ .mouseMoved,
                .activeAlways,
                .mouseEnteredAndExited] as NSTrackingArea.Options
let tracker = NSTrackingArea(rect:frame, options: options, owner:view, userInfo: nil)
view.addTrackingArea(tracker)
</code>```

The mouse entered and exited functions don't seem to fire

```<code>override func mouseExited(with event: NSEvent) {
   // NSCursor.unhide()
    print("_____________________EXIT")
   //Never fires

  }

  override func mouseEntered(with event: NSEvent) {
 //   NSCursor.hide()
    print("_____________________ENTER")
 // never fires

  }
</code>```

Any ideas ? Thanks

答:
If you want to keep the mouse in the window you can use CGWarpMouseCursorPosition. It sets the mouse cursor position on screen.

Here's an example, to keep the mouse centered in a view:

NSEvent.addLocalMonitorForEvents(matching: .mouseMoved) { (event) -> NSEvent? in

    let point = NSPoint(x: self.view.frame.width * 0.5, y: self.view.frame.height * 0.5)
    let pointInWindow = self.view.convert(point, to: nil)
    if let pointOnScreen = self.view.window?.convertPoint(toScreen: pointInWindow) {
        let cgPoint = CGPoint(x: pointOnScreen.x, y: pointOnScreen.y)
        CGWarpMouseCursorPosition(cgPoint)
    }

    return event
}
```

Note: use NSEvent.addLocalMonitorForEvents in that case to get .mouseMoved events instead of NSTrackingArea.

Body:
I have a Mac SpriteKit / swift app (a game) where I need to keep the cursor within a window. or at least give some warning when it leaves the game window.

I already have a tracking area set up and am using the mouse to move a game paddle. But when the cursor moves outside the window, the paddle stops working.

 let options = [ .mouseMoved,
                .activeAlways,
                .mouseEnteredAndExited] as NSTrackingArea.Options
let tracker = NSTrackingArea(rect:frame, options: options, owner:view, userInfo: nil)
view.addTrackingArea(tracker)

The mouse entered and exited functions don't seem to fire

override func mouseExited(with event: NSEvent) {
   // NSCursor.unhide()
    print("_____________________EXIT")
   //Never fires

  }

  override func mouseEntered(with event: NSEvent) {
 //   NSCursor.hide()
    print("_____________________ENTER")
 // never fires

  }

Any ideas ? Thanks

Body:
If you want to keep the mouse in the window you can use CGWarpMouseCursorPosition. It sets the mouse cursor position on screen.

Here's an example, to keep the mouse centered in a view:

NSEvent.addLocalMonitorForEvents(matching: .mouseMoved) { (event) -> NSEvent? in

    let point = NSPoint(x: self.view.frame.width * 0.5, y: self.view.frame.height * 0.5)
    let pointInWindow = self.view.convert(point, to: nil)
    if let pointOnScreen = self.view.window?.convertPoint(toScreen: pointInWindow) {
        let cgPoint = CGPoint(x: pointOnScreen.x, y: pointOnScreen.y)
        CGWarpMouseCursorPosition(cgPoint)
    }

    return event
}

Note: use NSEvent.addLocalMonitorForEvents in that case to get .mouseMoved events instead of NSTrackingArea.


问:
Implement a trait for another trait Item type
I need to convert a parse error to my own Error type while returning Result. Simplified, it looks like the following:

```<code>enum MyError {
    Parse,
    ...,
}

fn process<R: FromStr>(s: &str) -> Result<(), MyError> {
    Ok(s.parse::<R>()?)
}
</code>```

For above to work From trait should be implemented. This doesn't work:

```<code>impl From<std::str::FromStr::Err> for MyError {
    fn from(e: std::str::FromStr::Err) -> MyError {
        MyError::Parse
    }
}
</code>```

The compiler diagnostics:

```<code>help: use fully-qualified syntax: `<Type as std::str::FromStr>::Err`
</code>```

But I don't know the exact Type here. The whole point is to allow conversion from all possible errors.

答:
If you're discarding the parse error anyway, use map_err to change the error locally:

```<code>fn process<R: FromStr>(s: &str) -> Result<(), MyError> {
    let _ = s.parse::<R>().map_err(|_| MyError::Parse)?;
    Ok(())
}
</code>```

Body:
I need to convert a parse error to my own Error type while returning Result. Simplified, it looks like the following:

enum MyError {
    Parse,
    ...,
}

fn process<R: FromStr>(s: &str) -> Result<(), MyError> {
    Ok(s.parse::<R>()?)
}

For above to work From trait should be implemented. This doesn't work:

impl From<std::str::FromStr::Err> for MyError {
    fn from(e: std::str::FromStr::Err) -> MyError {
        MyError::Parse
    }
}

The compiler diagnostics:

help: use fully-qualified syntax: `<Type as std::str::FromStr>::Err`

But I don't know the exact Type here. The whole point is to allow conversion from all possible errors.

Body:
If you're discarding the parse error anyway, use map_err to change the error locally:

fn process<R: FromStr>(s: &str) -> Result<(), MyError> {
    let _ = s.parse::<R>().map_err(|_| MyError::Parse)?;
    Ok(())
}