问:
How to resolve compatibility issues for Tensorflow and associated packages?
I cannot find a way to pip install the following Python modules without compatibility issues (from a requirements.txt file, on Red Hat Enterprise Linux release 8.2):

tensorflow_gpu
tensorflow_addons
tensorflow_io
pandas
pillow
matplotlib
```
<p>I tried to specify versions like</p>
```tensorflow_gpu
tensorflow_addons==2.6.0
tensorflow_io
pandas
pillow
matplotlib
```
<p>however, the installation always fails.</p>
<p>I tried the above mentioned within a virtual environment. During my latest attempts, I removed the site packages to avoid further compatibility issues:</p>
```~$ mkdir ./venv
~$ python3 -m venv ./venv
~$ source ./venv/bin/activate
(venv) ~$ cd ./venv
(venv) ./venv$ pip3.8 freeze | xargs pip3.8 uninstall -y
(venv) ./venv$ pip3.8 install -r requirements.txt
```
<p>After the installation finished with problems, I cannot import tensorflow and tensorflow_addons like this:</p>
```(venv) ./venv$ python3
>>> import tensorflow as tf
>>> import tensorflow_addons as tfa
```
<p>because of the following error (full output further down):</p>
```tensorflow.python.framework.errors_impl.AlreadyExistsError: Another metric with the same name already exists
```
<p>Is there a place where I can find matching versions or is the issue not resolvable by simply specifying certain versions of the modules?</p>
<hr />
<p><strong>Full module import error output:</strong></p>
```2022-02-09 06:29:07.367472: E tensorflow/core/lib/monitoring/collection_registry.cc:77] Cannot register 2 metrics with the same name: /tensorflow/api/keras/optimizers
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow_addons/__init__.py", line 21, in <module>
    from tensorflow_addons import activations
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow_addons/activations/__init__.py", line 17, in <module>
    from tensorflow_addons.activations.gelu import gelu
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow_addons/activations/gelu.py", line 19, in <module>
    from tensorflow_addons.utils.types import TensorLike
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow_addons/utils/types.py", line 24, in <module>
    from keras.engine import keras_tensor
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/__init__.py", line 25, in <module>
    from keras import models
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/models.py", line 20, in <module>
    from keras import metrics as metrics_module
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/metrics.py", line 26, in <module>
    from keras import activations
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/activations.py", line 20, in <module>
    from keras.layers import advanced_activations
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/layers/__init__.py", line 23, in <module>
    from keras.engine.input_layer import Input
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/engine/input_layer.py", line 21, in <module>
    from keras.engine import base_layer
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/engine/base_layer.py", line 43, in <module>
    from keras.mixed_precision import loss_scale_optimizer
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/mixed_precision/loss_scale_optimizer.py", line 18, in <module>
    from keras import optimizers
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/optimizers.py", line 26, in <module>
    from keras.optimizer_v2 import adadelta as adadelta_v2
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/optimizer_v2/adadelta.py", line 22, in <module>
    from keras.optimizer_v2 import optimizer_v2
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py", line 36, in <module>
    keras_optimizers_gauge = tf.__internal__.monitoring.BoolGauge(
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow/python/eager/monitoring.py", line 360, in __init__
    super(BoolGauge, self).__init__('BoolGauge', _bool_gauge_methods,
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow/python/eager/monitoring.py", line 135, in __init__
    self._metric = self._metric_methods[self._label_length].create(*args)
tensorflow.python.framework.errors_impl.AlreadyExistsError: Another metric with the same name already exists.
```
<hr />
<p><strong>During module installation</strong>
This is the output during installation of the modules in requirements.txt:</p>
```WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
Requirement already satisfied: tensorflow==2.6.0 in /pfs/data5/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages (from -r requirements.txt (line 1)) (2.6.0)
Collecting tensorflow_gpu==2.6.0
  Using cached tensorflow_gpu-2.6.0-cp38-cp38-manylinux2010_x86_64.whl (458.4 MB)
Requirement already satisfied: tensorflow_addons in /pfs/data5/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages (from -r requirements.txt (line 3)) (0.15.0)
Requirement already satisfied: tensorflow_io in /pfs/data5/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages (from -r requirements.txt (line 4)) (0.21.0)
Requirement already satisfied: pandas in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from -r requirements.txt (line 5)) (1.4.0)
Requirement already satisfied: pillow in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from -r requirements.txt (line 6)) (9.0.0)
Requirement already satisfied: matplotlib in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from -r requirements.txt (line 7)) (3.5.1)
Requirement already satisfied: wheel~=0.35 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (0.37.1)
Collecting absl-py~=0.10
  Using cached absl_py-0.15.0-py3-none-any.whl (132 kB)
Requirement already satisfied: google-pasta~=0.2 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (0.2.0)
Collecting six~=1.15.0
  Using cached six-1.15.0-py2.py3-none-any.whl (10 kB)
Collecting flatbuffers~=1.12.0
  Using cached flatbuffers-1.12-py2.py3-none-any.whl (15 kB)
Requirement already satisfied: keras-preprocessing~=1.1.2 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (1.1.2)
Requirement already satisfied: tensorflow-estimator~=2.6 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (2.7.0)
Collecting typing-extensions~=3.7.4
  Using cached typing_extensions-3.7.4.3-py3-none-any.whl (22 kB)
Requirement already satisfied: keras~=2.6 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (2.7.0)
Requirement already satisfied: termcolor~=1.1.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (1.1.0)
Collecting h5py~=3.1.0
  Using cached h5py-3.1.0-cp38-cp38-manylinux1_x86_64.whl (4.4 MB)
Collecting numpy~=1.19.2
  Using cached numpy-1.19.5-cp38-cp38-manylinux2010_x86_64.whl (14.9 MB)
Requirement already satisfied: gast==0.4.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (0.4.0)
Requirement already satisfied: grpcio<2.0,>=1.37.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (1.43.0)
Requirement already satisfied: opt-einsum~=3.3.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (3.3.0)
Requirement already satisfied: tensorboard~=2.6 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (2.8.0)
Collecting clang~=5.0
  Using cached clang-5.0-py3-none-any.whl
Collecting wrapt~=1.12.1
  Using cached wrapt-1.12.1-cp38-cp38-linux_x86_64.whl
Requirement already satisfied: protobuf>=3.9.2 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (3.19.4)
Requirement already satisfied: astunparse~=1.6.3 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (1.6.3)
Requirement already satisfied: typeguard>=2.7 in /pfs/data5/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages (from tensorflow_addons->-r requirements.txt (line 3)) (2.13.3)
Requirement already satisfied: tensorflow-io-gcs-filesystem==0.21.0 in /pfs/data5/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages (from tensorflow_io->-r requirements.txt (line 4)) (0.21.0)
Requirement already satisfied: pytz>=2020.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from pandas->-r requirements.txt (line 5)) (2021.3)
Requirement already satisfied: python-dateutil>=2.8.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from pandas->-r requirements.txt (line 5)) (2.8.2)
Requirement already satisfied: fonttools>=4.22.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 7)) (4.29.0)
Requirement already satisfied: pyparsing>=2.2.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 7)) (3.0.7)
Requirement already satisfied: cycler>=0.10 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 7)) (0.11.0)
Requirement already satisfied: packaging>=20.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 7)) (21.3)
Requirement already satisfied: kiwisolver>=1.0.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 7)) (1.3.2)
Requirement already satisfied: setuptools>=41.0.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (41.6.0)
Requirement already satisfied: requests<3,>=2.21.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (2.27.1)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (1.8.1)
Requirement already satisfied: markdown>=2.6.8 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (3.3.6)
Requirement already satisfied: google-auth<3,>=1.6.3 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (2.5.0)
Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (0.6.1)
Requirement already satisfied: werkzeug>=0.11.15 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (2.0.2)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (0.4.6)
Requirement already satisfied: cachetools<6.0,>=2.0.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (5.0.0)
Requirement already satisfied: rsa<5,>=3.1.4 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (4.8)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (0.2.8)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (1.3.1)
Requirement already satisfied: importlib-metadata>=4.4 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from markdown>=2.6.8->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (4.10.1)
Requirement already satisfied: idna<4,>=2.5 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (3.3)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (1.26.8)
Requirement already satisfied: certifi>=2017.4.17 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (2021.10.8)
Requirement already satisfied: charset-normalizer~=2.0.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (2.0.11)
Requirement already satisfied: zipp>=0.5 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (3.7.0)
Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (0.4.8)
Requirement already satisfied: oauthlib>=3.0.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (3.2.0)
Installing collected packages: wrapt, typing-extensions, flatbuffers, clang, six, numpy, h5py, absl-py, tensorflow_gpu
  Attempting uninstall: wrapt
    Found existing installation: wrapt 1.13.3
    Not uninstalling wrapt at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'wrapt'. No files were found to uninstall.
  Attempting uninstall: typing-extensions
    Found existing installation: typing_extensions 4.0.1
    Not uninstalling typing-extensions at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'typing_extensions'. No files were found to uninstall.
  Attempting uninstall: flatbuffers
    Found existing installation: flatbuffers 2.0
    Not uninstalling flatbuffers at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'flatbuffers'. No files were found to uninstall.
  Attempting uninstall: six
    Found existing installation: six 1.16.0
    Not uninstalling six at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'six'. No files were found to uninstall.
  Attempting uninstall: numpy
    Found existing installation: numpy 1.22.1
    Not uninstalling numpy at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'numpy'. No files were found to uninstall.
  Attempting uninstall: h5py
    Found existing installation: h5py 3.6.0
    Not uninstalling h5py at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'h5py'. No files were found to uninstall.
  Attempting uninstall: absl-py
    Found existing installation: absl-py 1.0.0
    Not uninstalling absl-py at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'absl-py'. No files were found to uninstall.
  Attempting uninstall: tensorflow_gpu
    Found existing installation: tensorflow-gpu 2.7.0
    Not uninstalling tensorflow-gpu at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'tensorflow-gpu'. No files were found to uninstall.
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
bokeh 2.4.2 requires typing-extensions>=3.10.0, but you have typing-extensions 3.7.4.3 which is incompatible.
black 22.1.0 requires typing-extensions>=3.10.0.0; python_version < "3.10", but you have typing-extensions 3.7.4.3 which is incompatible.
Successfully installed absl-py-0.15.0 clang-5.0 flatbuffers-1.12 h5py-3.1.0 numpy-1.19.5 six-1.15.0 tensorflow_gpu-2.6.0 typing-extensions-3.7.4.3 wrapt-1.12.1
WARNING: You are using pip version 22.0.2; however, version 22.0.3 is available.
You should consider upgrading via the '/pfs/data5/home/kit/ifgg/mp3890/ven0/bin/python3 -m pip install --upgrade pip' command.
```

Following the suggestion to invoke Python with -m pip (as python3 -m pip install -r requirements.txt) led to the same output (except for that message).

答:
The problem was caused by jupyter/tensorflow being loaded in the background. The following solved the issue:

```<code>module purge
module load devel/cuda
/usr/bin/python3.8 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
</code>```

Many thanks to Samuel Braun from our cluster support team

Body:
I cannot find a way to pip install the following Python modules without compatibility issues (from a requirements.txt file, on Red Hat Enterprise Linux release 8.2):

tensorflow_gpu
tensorflow_addons
tensorflow_io
pandas
pillow
matplotlib

I tried to specify versions like

tensorflow_gpu
tensorflow_addons==2.6.0
tensorflow_io
pandas
pillow
matplotlib

however, the installation always fails.

I tried the above mentioned within a virtual environment. During my latest attempts, I removed the site packages to avoid further compatibility issues:

~$ mkdir ./venv
~$ python3 -m venv ./venv
~$ source ./venv/bin/activate
(venv) ~$ cd ./venv
(venv) ./venv$ pip3.8 freeze | xargs pip3.8 uninstall -y
(venv) ./venv$ pip3.8 install -r requirements.txt

After the installation finished with problems, I cannot import tensorflow and tensorflow_addons like this:

(venv) ./venv$ python3
>>> import tensorflow as tf
>>> import tensorflow_addons as tfa

because of the following error (full output further down):

tensorflow.python.framework.errors_impl.AlreadyExistsError: Another metric with the same name already exists

Is there a place where I can find matching versions or is the issue not resolvable by simply specifying certain versions of the modules?

Full module import error output:

2022-02-09 06:29:07.367472: E tensorflow/core/lib/monitoring/collection_registry.cc:77] Cannot register 2 metrics with the same name: /tensorflow/api/keras/optimizers
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow_addons/__init__.py", line 21, in <module>
    from tensorflow_addons import activations
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow_addons/activations/__init__.py", line 17, in <module>
    from tensorflow_addons.activations.gelu import gelu
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow_addons/activations/gelu.py", line 19, in <module>
    from tensorflow_addons.utils.types import TensorLike
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow_addons/utils/types.py", line 24, in <module>
    from keras.engine import keras_tensor
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/__init__.py", line 25, in <module>
    from keras import models
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/models.py", line 20, in <module>
    from keras import metrics as metrics_module
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/metrics.py", line 26, in <module>
    from keras import activations
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/activations.py", line 20, in <module>
    from keras.layers import advanced_activations
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/layers/__init__.py", line 23, in <module>
    from keras.engine.input_layer import Input
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/engine/input_layer.py", line 21, in <module>
    from keras.engine import base_layer
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/engine/base_layer.py", line 43, in <module>
    from keras.mixed_precision import loss_scale_optimizer
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/mixed_precision/loss_scale_optimizer.py", line 18, in <module>
    from keras import optimizers
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/optimizers.py", line 26, in <module>
    from keras.optimizer_v2 import adadelta as adadelta_v2
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/optimizer_v2/adadelta.py", line 22, in <module>
    from keras.optimizer_v2 import optimizer_v2
  File "/opt/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py", line 36, in <module>
    keras_optimizers_gauge = tf.__internal__.monitoring.BoolGauge(
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow/python/eager/monitoring.py", line 360, in __init__
    super(BoolGauge, self).__init__('BoolGauge', _bool_gauge_methods,
  File "/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages/tensorflow/python/eager/monitoring.py", line 135, in __init__
    self._metric = self._metric_methods[self._label_length].create(*args)
tensorflow.python.framework.errors_impl.AlreadyExistsError: Another metric with the same name already exists.

During module installation
This is the output during installation of the modules in requirements.txt:

WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
Requirement already satisfied: tensorflow==2.6.0 in /pfs/data5/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages (from -r requirements.txt (line 1)) (2.6.0)
Collecting tensorflow_gpu==2.6.0
  Using cached tensorflow_gpu-2.6.0-cp38-cp38-manylinux2010_x86_64.whl (458.4 MB)
Requirement already satisfied: tensorflow_addons in /pfs/data5/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages (from -r requirements.txt (line 3)) (0.15.0)
Requirement already satisfied: tensorflow_io in /pfs/data5/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages (from -r requirements.txt (line 4)) (0.21.0)
Requirement already satisfied: pandas in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from -r requirements.txt (line 5)) (1.4.0)
Requirement already satisfied: pillow in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from -r requirements.txt (line 6)) (9.0.0)
Requirement already satisfied: matplotlib in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from -r requirements.txt (line 7)) (3.5.1)
Requirement already satisfied: wheel~=0.35 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (0.37.1)
Collecting absl-py~=0.10
  Using cached absl_py-0.15.0-py3-none-any.whl (132 kB)
Requirement already satisfied: google-pasta~=0.2 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (0.2.0)
Collecting six~=1.15.0
  Using cached six-1.15.0-py2.py3-none-any.whl (10 kB)
Collecting flatbuffers~=1.12.0
  Using cached flatbuffers-1.12-py2.py3-none-any.whl (15 kB)
Requirement already satisfied: keras-preprocessing~=1.1.2 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (1.1.2)
Requirement already satisfied: tensorflow-estimator~=2.6 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (2.7.0)
Collecting typing-extensions~=3.7.4
  Using cached typing_extensions-3.7.4.3-py3-none-any.whl (22 kB)
Requirement already satisfied: keras~=2.6 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (2.7.0)
Requirement already satisfied: termcolor~=1.1.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (1.1.0)
Collecting h5py~=3.1.0
  Using cached h5py-3.1.0-cp38-cp38-manylinux1_x86_64.whl (4.4 MB)
Collecting numpy~=1.19.2
  Using cached numpy-1.19.5-cp38-cp38-manylinux2010_x86_64.whl (14.9 MB)
Requirement already satisfied: gast==0.4.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (0.4.0)
Requirement already satisfied: grpcio<2.0,>=1.37.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (1.43.0)
Requirement already satisfied: opt-einsum~=3.3.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (3.3.0)
Requirement already satisfied: tensorboard~=2.6 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (2.8.0)
Collecting clang~=5.0
  Using cached clang-5.0-py3-none-any.whl
Collecting wrapt~=1.12.1
  Using cached wrapt-1.12.1-cp38-cp38-linux_x86_64.whl
Requirement already satisfied: protobuf>=3.9.2 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (3.19.4)
Requirement already satisfied: astunparse~=1.6.3 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorflow==2.6.0->-r requirements.txt (line 1)) (1.6.3)
Requirement already satisfied: typeguard>=2.7 in /pfs/data5/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages (from tensorflow_addons->-r requirements.txt (line 3)) (2.13.3)
Requirement already satisfied: tensorflow-io-gcs-filesystem==0.21.0 in /pfs/data5/home/kit/ifgg/mp3890/.local/lib/python3.8/site-packages (from tensorflow_io->-r requirements.txt (line 4)) (0.21.0)
Requirement already satisfied: pytz>=2020.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from pandas->-r requirements.txt (line 5)) (2021.3)
Requirement already satisfied: python-dateutil>=2.8.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from pandas->-r requirements.txt (line 5)) (2.8.2)
Requirement already satisfied: fonttools>=4.22.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 7)) (4.29.0)
Requirement already satisfied: pyparsing>=2.2.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 7)) (3.0.7)
Requirement already satisfied: cycler>=0.10 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 7)) (0.11.0)
Requirement already satisfied: packaging>=20.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 7)) (21.3)
Requirement already satisfied: kiwisolver>=1.0.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from matplotlib->-r requirements.txt (line 7)) (1.3.2)
Requirement already satisfied: setuptools>=41.0.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (41.6.0)
Requirement already satisfied: requests<3,>=2.21.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (2.27.1)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (1.8.1)
Requirement already satisfied: markdown>=2.6.8 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (3.3.6)
Requirement already satisfied: google-auth<3,>=1.6.3 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (2.5.0)
Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (0.6.1)
Requirement already satisfied: werkzeug>=0.11.15 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (2.0.2)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (0.4.6)
Requirement already satisfied: cachetools<6.0,>=2.0.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (5.0.0)
Requirement already satisfied: rsa<5,>=3.1.4 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (4.8)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (0.2.8)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (1.3.1)
Requirement already satisfied: importlib-metadata>=4.4 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from markdown>=2.6.8->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (4.10.1)
Requirement already satisfied: idna<4,>=2.5 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (3.3)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (1.26.8)
Requirement already satisfied: certifi>=2017.4.17 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (2021.10.8)
Requirement already satisfied: charset-normalizer~=2.0.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from requests<3,>=2.21.0->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (2.0.11)
Requirement already satisfied: zipp>=0.5 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from importlib-metadata>=4.4->markdown>=2.6.8->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (3.7.0)
Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (0.4.8)
Requirement already satisfied: oauthlib>=3.0.0 in /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard~=2.6->tensorflow==2.6.0->-r requirements.txt (line 1)) (3.2.0)
Installing collected packages: wrapt, typing-extensions, flatbuffers, clang, six, numpy, h5py, absl-py, tensorflow_gpu
  Attempting uninstall: wrapt
    Found existing installation: wrapt 1.13.3
    Not uninstalling wrapt at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'wrapt'. No files were found to uninstall.
  Attempting uninstall: typing-extensions
    Found existing installation: typing_extensions 4.0.1
    Not uninstalling typing-extensions at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'typing_extensions'. No files were found to uninstall.
  Attempting uninstall: flatbuffers
    Found existing installation: flatbuffers 2.0
    Not uninstalling flatbuffers at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'flatbuffers'. No files were found to uninstall.
  Attempting uninstall: six
    Found existing installation: six 1.16.0
    Not uninstalling six at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'six'. No files were found to uninstall.
  Attempting uninstall: numpy
    Found existing installation: numpy 1.22.1
    Not uninstalling numpy at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'numpy'. No files were found to uninstall.
  Attempting uninstall: h5py
    Found existing installation: h5py 3.6.0
    Not uninstalling h5py at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'h5py'. No files were found to uninstall.
  Attempting uninstall: absl-py
    Found existing installation: absl-py 1.0.0
    Not uninstalling absl-py at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'absl-py'. No files were found to uninstall.
  Attempting uninstall: tensorflow_gpu
    Found existing installation: tensorflow-gpu 2.7.0
    Not uninstalling tensorflow-gpu at /pfs/data5/software_uc2/bwhpc/common/jupyter/tensorflow/2022-01-11/lib/python3.8/site-packages, outside environment /pfs/data5/home/kit/ifgg/mp3890/ven0
    Can't uninstall 'tensorflow-gpu'. No files were found to uninstall.
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
bokeh 2.4.2 requires typing-extensions>=3.10.0, but you have typing-extensions 3.7.4.3 which is incompatible.
black 22.1.0 requires typing-extensions>=3.10.0.0; python_version < "3.10", but you have typing-extensions 3.7.4.3 which is incompatible.
Successfully installed absl-py-0.15.0 clang-5.0 flatbuffers-1.12 h5py-3.1.0 numpy-1.19.5 six-1.15.0 tensorflow_gpu-2.6.0 typing-extensions-3.7.4.3 wrapt-1.12.1
WARNING: You are using pip version 22.0.2; however, version 22.0.3 is available.
You should consider upgrading via the '/pfs/data5/home/kit/ifgg/mp3890/ven0/bin/python3 -m pip install --upgrade pip' command.

Following the suggestion to invoke Python with -m pip (as python3 -m pip install -r requirements.txt) led to the same output (except for that message).

Body:
The problem was caused by jupyter/tensorflow being loaded in the background. The following solved the issue:

module purge
module load devel/cuda
/usr/bin/python3.8 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt

Many thanks to Samuel Braun from our cluster support team


来源: stackexchange

问:
why is this a deadlock in golang / waitgroup?
I'm not sure what I'm missing but I get a deadlock error.  I'm using a buffered channel that I range over after all go routines complete. The channel has the capacity of 4 and I'm running 4 go routines so I'm expecting it to be "closed" automatically once it reaches the max capacity.</p>

```<code>package main

import "fmt"
import "sync"

func main() {
    ch := make(chan []int, 4)
    var m []int

    var wg sync.WaitGroup
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            ch <- m
            return
        }()
    }
    wg.Wait()

    for c := range ch {
        fmt.Printf("c is %v", c)
    }
}
</code>```

答:
@Denys Séguret is right

but follow is anohter Solution easier to fix it:

```<code>func main() {
    ch := make(chan []int, 4)
    var m []int

    var wg sync.WaitGroup
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            ch <- m
            return
        }()
    }
    go func() {
        wg.Wait()
        close(ch)
    }()
    for c := range ch {
        fmt.Printf("c is %v", c)
    }
}
</code>```

form https://go.dev/blog/pipelines   Fan-out, fan-in 's func merge()

```<code>func merge(cs ...<-chan int) <-chan int {
    var wg sync.WaitGroup
    out := make(chan int)

    // Start an output goroutine for each input channel in cs.  output
    // copies values from c to out until c is closed, then calls wg.Done.
    output := func(c <-chan int) {
        for n := range c {
            out <- n
        }
        wg.Done()
    }
    wg.Add(len(cs))
    for _, c := range cs {
        go output(c)
    }

    // Start a goroutine to close out once all the output goroutines are
    // done.  This must start after the wg.Add call.
    go func() {
        wg.Wait()
        close(out)
    }()
    return out
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm not sure what I'm missing but I get a deadlock error.  I'm using a buffered channel that I range over after all go routines complete. The channel has the capacity of 4 and I'm running 4 go routines so I'm expecting it to be "closed" automatically once it reaches the max capacity.

package main

import "fmt"
import "sync"

func main() {
    ch := make(chan []int, 4)
    var m []int

    var wg sync.WaitGroup
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            ch <- m
            return
        }()
    }
    wg.Wait()

    for c := range ch {
        fmt.Printf("c is %v", c)
    }
}

Body:
@Denys Séguret is right

but follow is anohter Solution easier to fix it:

func main() {
    ch := make(chan []int, 4)
    var m []int

    var wg sync.WaitGroup
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            ch <- m
            return
        }()
    }
    go func() {
        wg.Wait()
        close(ch)
    }()
    for c := range ch {
        fmt.Printf("c is %v", c)
    }
}

form https://go.dev/blog/pipelines   Fan-out, fan-in 's func merge()

func merge(cs ...<-chan int) <-chan int {
    var wg sync.WaitGroup
    out := make(chan int)

    // Start an output goroutine for each input channel in cs.  output
    // copies values from c to out until c is closed, then calls wg.Done.
    output := func(c <-chan int) {
        for n := range c {
            out <- n
        }
        wg.Done()
    }
    wg.Add(len(cs))
    for _, c := range cs {
        go output(c)
    }

    // Start a goroutine to close out once all the output goroutines are
    // done.  This must start after the wg.Add call.
    go func() {
        wg.Wait()
        close(out)
    }()
    return out
}

ContentLicense: CC BY-SA 4.0


问:
How to split objects
How to split objects?
I want to split Object.
Such as one object per group or two object per group.</p>
```<code>obj1: {
    1: 1,
    2: 2,
    3: 3,
},
Split objects into groups(convert obj1 to obj2)
obj2: {
    0: {
            1: 1,
        },
    1: {
            2: 2,
        },
    },
    2: {
            3: 3,
        },
    },
}

</code>```

答:
You could get the entries, chunk them by getting a new object and assign the array to an object.

function chunk(object, size) {
    const
        entries = Object.entries(object),
        chunks = [];

    let i = 0;

    while (i < entries.length)
        chunks.push(Object.fromEntries(entries.slice(i, i += size)));

    return Object.assign({}, chunks);
}

console.log(chunk({ 1: 1, 2: 2, 3: 3 }, 1));
console.log(chunk({ 1: 1, 2: 2, 3: 3 }, 2));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: How to split objects

Body:
How to split objects?
I want to split Object.
Such as one object per group or two object per group.

obj1: {
    1: 1,
    2: 2,
    3: 3,
},
Split objects into groups(convert obj1 to obj2)
obj2: {
    0: {
            1: 1,
        },
    1: {
            2: 2,
        },
    },
    2: {
            3: 3,
        },
    },
}

Body:
You could get the entries, chunk them by getting a new object and assign the array to an object.

function chunk(object, size) {
    const
        entries = Object.entries(object),
        chunks = [];

    let i = 0;

    while (i < entries.length)
        chunks.push(Object.fromEntries(entries.slice(i, i += size)));

    return Object.assign({}, chunks);
}

console.log(chunk({ 1: 1, 2: 2, 3: 3 }, 1));
console.log(chunk({ 1: 1, 2: 2, 3: 3 }, 2));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Databinding with parameters
I'm currently trying to develop a small finance application. My application needs a quite complex GUI (basically a table with dynamic rows and columns as well as categories and subcategories); since I couldn't think of a standard xaml-way to achieve that, I'm writing a custom control that is supposed to display my data.

So long story short, I'm creating a lot of different WPF UI elements in C# code directly, not in XAML. Now I'll need a way to synchronize some of these component's values with dynamically changing data. An obvious example is that some of my text boxes (or labels or whatever) will need to display the price of a stock. It should thus be bound to another class which provides up to date prices.

My main problem is that I don't know in advance which prices will be needed and where they should be displayed. So what I'd need is basically a way for my textbox to contact my price-object and ask "hey, i'm going to need a price for stock US0123456789. Please tell me that price and keep updating my value whenever the price of that stock is updated."

All databinding examples I found were usually focused on binding to the variables within a specific object instance, but I can't simply bind to, say, PriceObject.Price because there can't be a simple "Price" variable. After all, there's going to be various different stocks managed by the price object and each text box only needs the price of one specific stock, so it'd need to bind to something like PriceObject.PriceForStock("US0123456789"). I couldn't find a way to bind to a method, though, and I don't know how how else it'd be possible.

The only way I could think of was to have a Dictionary in my GUI-class witch stock ISINs as its keys and a reference to the UI Element as value. Then my GUI could observe the Price Object and each time prices change, and event is triggered and the GUI class could update the UI Element manually, something like (pseudo code incoming):

```<code>private Dictionary<string, UIElement> displayed_stocks = new Dictionary<string, UIElement>();

private void create_gui()
{
   Textbox textbox = new Textbox();
   displayed_stocks.Add(isin, textbox);
}

private void receive_change_event_of_price_object(string affected_isin, double new_price)
{
  displayed_stocks[affected_isin].Text = new_price.ToString();
}
</code>```

But I don't know, I feel like this is a sloppy solution. Especially because I won't only need dynamic prices but also other dynamic information like portfolio holdings, which will rely not only on ISIN but on ISIN and portfolio ID, so it wouldn't be that simple with a dictionary. Is there any better way to do it? I'd be glad to be pushed in the right direction there!
Thanks

答:
Dynamic Bindings are achieved using...

Indexer as Bas has already said above. Even ToString() can do the trick too.

MultiBinding with IMultiValueConverter deciding which binding source(s) should take effect. MultiBinding has an advatnage that you can bind all possible things that can be displayed in your TextBox and send them to the converter (whether available or not) and then the converter will decide which one to mould and display.

If the sequence of priority of source values is fixed then you can use PriorityBinding. No need for the converter discussed above.

Title: Databinding with parameters

Body:
I'm currently trying to develop a small finance application. My application needs a quite complex GUI (basically a table with dynamic rows and columns as well as categories and subcategories); since I couldn't think of a standard xaml-way to achieve that, I'm writing a custom control that is supposed to display my data.

So long story short, I'm creating a lot of different WPF UI elements in C# code directly, not in XAML. Now I'll need a way to synchronize some of these component's values with dynamically changing data. An obvious example is that some of my text boxes (or labels or whatever) will need to display the price of a stock. It should thus be bound to another class which provides up to date prices.

My main problem is that I don't know in advance which prices will be needed and where they should be displayed. So what I'd need is basically a way for my textbox to contact my price-object and ask "hey, i'm going to need a price for stock US0123456789. Please tell me that price and keep updating my value whenever the price of that stock is updated."

All databinding examples I found were usually focused on binding to the variables within a specific object instance, but I can't simply bind to, say, PriceObject.Price because there can't be a simple "Price" variable. After all, there's going to be various different stocks managed by the price object and each text box only needs the price of one specific stock, so it'd need to bind to something like PriceObject.PriceForStock("US0123456789"). I couldn't find a way to bind to a method, though, and I don't know how how else it'd be possible.

The only way I could think of was to have a Dictionary in my GUI-class witch stock ISINs as its keys and a reference to the UI Element as value. Then my GUI could observe the Price Object and each time prices change, and event is triggered and the GUI class could update the UI Element manually, something like (pseudo code incoming):

private Dictionary<string, UIElement> displayed_stocks = new Dictionary<string, UIElement>();

private void create_gui()
{
   Textbox textbox = new Textbox();
   displayed_stocks.Add(isin, textbox);
}

private void receive_change_event_of_price_object(string affected_isin, double new_price)
{
  displayed_stocks[affected_isin].Text = new_price.ToString();
}

But I don't know, I feel like this is a sloppy solution. Especially because I won't only need dynamic prices but also other dynamic information like portfolio holdings, which will rely not only on ISIN but on ISIN and portfolio ID, so it wouldn't be that simple with a dictionary. Is there any better way to do it? I'd be glad to be pushed in the right direction there!
Thanks


问:
As seen in the image, create two responsive DIVs with space between them

I'm working on a codewell challenge and I'm stuck on this portion. I can't make an even space between them, and the images are overlapping.

.website {
  display: flex;
  justify-content: space-between;
}

.arrow {
  display: inline-block;
  width: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="website">
  <div class="spense">
    <img id="spense" src="./Assets/Spense.png" alt="spense">
    <h3>Spense.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Rethinking the way writers get paid, an open resource platform <br> design to help writers focus more on writing, and less on <br> when and how they'll get paid, Projects in collaboration with <br> Codewell.cc
  </div>
  <div class="yelp">
    <img id="yelp" src="./Assets/YelpCamp.png" alt="YelpCamp">
    <h3>YelpCamp.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Allowing backpack travelers to perfectly plan their trip <br> through an open-source platform similar to TripAdvisor. With <br>over 1m MAU, YelpCamp has been the crowd's favorite in <br>2021.
  </div>
</div></code>```

答:
You can use width property on each child inside flex container.

.website {
  display: flex;
  justify-content: space-between;
}

.spense, .yelp{
  width:40%;
}
.arrow {
  display: inline-block;
  width: 1rem;
}
.image{
width:100%;
object-fit:cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="website">
  <div class="spense">
    <img class="image" id="spense" src="https://via.placeholder.com/350

C/O https://placeholder.com/" alt="spense">
    <h3>Spense.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Rethinking the way writers get paid, an open resource platform <br> design to help writers focus more on writing, and less on <br> when and how they'll get paid, Projects in collaboration with <br> Codewell.cc
  </div>
  <div class="yelp">
    <img class="image" id="yelp" src="https://via.placeholder.com/350

C/O https://placeholder.com/" alt="YelpCamp">
    <h3>YelpCamp.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Allowing backpack travelers to perfectly plan their trip <br> through an open-source platform similar to TripAdvisor. With <br>over 1m MAU, YelpCamp has been the crowd's favorite in <br>2021.
  </div></code>```

Body:
I'm working on a codewell challenge and I'm stuck on this portion. I can't make an even space between them, and the images are overlapping.

.website {
  display: flex;
  justify-content: space-between;
}

.arrow {
  display: inline-block;
  width: 1rem;
}

Spense.com

    Rethinking the way writers get paid, an open resource platform
 design to help writers focus more on writing, and less on
 when and how they'll get paid, Projects in collaboration with
 Codewell.cc

YelpCamp.com

    Allowing backpack travelers to perfectly plan their trip
 through an open-source platform similar to TripAdvisor. With
over 1m MAU, YelpCamp has been the crowd's favorite in
2021.

Body:
You can use width property on each child inside flex container.

.website {
  display: flex;
  justify-content: space-between;
}

.spense, .yelp{
  width:40%;
}
.arrow {
  display: inline-block;
  width: 1rem;
}
.image{
width:100%;
object-fit:cover;
}

<div class="website">
  <div class="spense">
    <img class="image" id="spense" src="https://via.placeholder.com/350

C/O https://placeholder.com/" alt="spense">
    <h3>Spense.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Rethinking the way writers get paid, an open resource platform <br> design to help writers focus more on writing, and less on <br> when and how they'll get paid, Projects in collaboration with <br> Codewell.cc
  </div>
  <div class="yelp">
    <img class="image" id="yelp" src="https://via.placeholder.com/350

C/O https://placeholder.com/" alt="YelpCamp">
    <h3>YelpCamp.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Allowing backpack travelers to perfectly plan their trip <br> through an open-source platform similar to TripAdvisor. With <br>over 1m MAU, YelpCamp has been the crowd's favorite in <br>2021.
  </div>


问:
VM load date but keep in memory when switching windows
Working with a Xamarin.Forms app (with UWP). I'm very new to MVVM and this is my first real project working with it. I get how this is better but honestly, finding good videos have been difficult. Almost all of the videos are for people that have either worked with MVVM previously or they talk about a framework that has been sunset. I'm currently using no framework for this project.

I'm was thinking of using a singleton but I have seen many post about how that is a bad programming mistake. I have a VM that loads a single json file that stores between 1 and 50 models. It loads the models into an observablecollection that gets passed to a ListView. If a user clicks on a line, I want it to load a different page with that specific item. You will be allowed to update the model and if you click "save". It needs to take the model and overwrite the item in the observablecollection with the new data. The part that I'm getting lost is when I switch contentpage, the VM that was loaded also goes away. I just don't know the proper way to handle this because it recreates the VM when I navigate to he new page (Navigation.PushModalAsync(new Settings()). Normally, that isn't a horrible approach but I will be loading data from a server and I just thought reloading the data again from the cloud would be a waste of bandwidth because the json file is 1 MB and this would easily approach the gigabyte bandwidth for this one little button over a month. What would be the best way to not have to reload the data and keep the data a live?

Also, if you have a recommendations for MVVM for Xamarin.Forms for newbies. I would be happy to watch more videos!

答:
```<code>1.For Moving between multiple pages and use the VM,like Jason said you are in complete control of the VM.Below is the code snippets moving from mainPage to detailPage.

    private async void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        //selected item
        var s =collectionView.SelectedItem as NoteModel;
        //transfer data via viewmodel constructor
        var detailVM = new DetailPageViewModel
        {
            NoteTexter = s.Text
        };

        var detailPage = new DetailPage
        {
            BindingContext = detailVM
        };

        await Application.Current.MainPage.Navigation.PushAsync(detailPage);
    }

2.For keeping the data live in Xamarin forms app, you have a couple options: Files and local database.
  You can refer to this link: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/data/
</code>```


问:
React native async storage returning previous value
I'm using react-native-async-storage for saving API headers and user information received from API

```<code>const storeUserInfo = async (userInfo: any, headers: any) => {
  console.log(
    'Info Received in Local Storage Function',
    userInfo,
    'Headers Received in Local Storage Function',
    headers,
  );

  try {
    const user = JSON.stringify(userInfo);
    const userheaders = JSON.stringify(headers);
    await AsyncStorage.setItem('user', user);
    await AsyncStorage.setItem('headers', userheaders);
  } catch (e) {
    console.log('Error while storing user info', e);
  }
};
</code>```

when i try to get headers from async-storage, it gave old stored headers rather than returning latest.

// Getting headers like this..

```<code>const headers = await AsyncStorage.getItem('headers');
console.log('Headers received in get Profile Action', headers);
</code>```

but it returning old headers..

答:
Try using the below approach to fetch the data.</p>
```<code>const getData = async () => {
  try {
    const headers = await AsyncStorage.getItem('headers')
    return headers != null ? JSON.parse(headers) : null;
  } catch(e) {
    // error reading value
  }
}
</code>```

Body:
I'm using react-native-async-storage for saving API headers and user information received from API

const storeUserInfo = async (userInfo: any, headers: any) => {
  console.log(
    'Info Received in Local Storage Function',
    userInfo,
    'Headers Received in Local Storage Function',
    headers,
  );

  try {
    const user = JSON.stringify(userInfo);
    const userheaders = JSON.stringify(headers);
    await AsyncStorage.setItem('user', user);
    await AsyncStorage.setItem('headers', userheaders);
  } catch (e) {
    console.log('Error while storing user info', e);
  }
};

when i try to get headers from async-storage, it gave old stored headers rather than returning latest.

// Getting headers like this..

const headers = await AsyncStorage.getItem('headers');
console.log('Headers received in get Profile Action', headers);

but it returning old headers..

Body:
Try using the below approach to fetch the data.

const getData = async () => {
  try {
    const headers = await AsyncStorage.getItem('headers')
    return headers != null ? JSON.parse(headers) : null;
  } catch(e) {
    // error reading value
  }
}


问:
How do I parse a number from a String that may have a leading zero?
In ruby I am parsing a date in the following format: 24092008.
I want to convert each section (year, month, date) into a number.

I have split them up using a regex which produces three Strings which I am passing into the Integer constructor.

```<code>  date =~ /^([\d]{2})([\d]{2})([\d]{4})/
  year = Integer($3)
  month = Integer($2)
  day = Integer($1)
</code>```

When it hits the month line it crashes as follows:

```<code>`Integer': invalid value for Integer: "09" (ArgumentError)
</code>```

It took me a while to realise that it's interpreting the leading zero as Octal and 09 is not a valid Octal number (it works fine with "07").

Is there an elegant solution to this or should I just test for numbers less than 10 and remove the zero first?

Thanks.

答:
Instead of checking any integer with leading 0 directly. Eg:

Integer("08016") #=> ArgumentError: invalid value for Integer(): "08016"

Create a method to check and rescue for leading 0:

```<code>def is_numeric(data)
  _is_numeric = true if Integer(data) rescue false

  # To deal with Integers with leading 0
  if !_is_numeric
    _is_numeric = data.split("").all?{|q| Integer(q.to_i).to_s == q }
  end

  _is_numeric
end
</code>```

is_numeric("08016") #=> true
is_numeric("A8016") #=> false

OwnerDisplayName: boncey

ContentLicense: CC BY-SA 2.5

Body:
In ruby I am parsing a date in the following format: 24092008.
I want to convert each section (year, month, date) into a number.

I have split them up using a regex which produces three Strings which I am passing into the Integer constructor.

  date =~ /^([\d]{2})([\d]{2})([\d]{4})/
  year = Integer($3)
  month = Integer($2)
  day = Integer($1)

When it hits the month line it crashes as follows:

`Integer': invalid value for Integer: "09" (ArgumentError)

It took me a while to realise that it's interpreting the leading zero as Octal and 09 is not a valid Octal number (it works fine with "07").

Is there an elegant solution to this or should I just test for numbers less than 10 and remove the zero first?

Thanks.

LastEditorDisplayName: Prakash

Body:
Instead of checking any integer with leading 0 directly. Eg:

Integer("08016") #=> ArgumentError: invalid value for Integer(): "08016"

Create a method to check and rescue for leading 0:

def is_numeric(data)
  _is_numeric = true if Integer(data) rescue false

  # To deal with Integers with leading 0
  if !_is_numeric
    _is_numeric = data.split("").all?{|q| Integer(q.to_i).to_s == q }
  end

  _is_numeric
end

is_numeric("08016") #=> true
is_numeric("A8016") #=> false


问:
php - mysql avoid sql injections
I have many functions like

```<code>updateUser($id,$username,$email)
updateMusic($id, $music)
</code>```

etc...

Is there a generic function to avoid SQL injections ?

I just want to avoid using mysql_real_escape_string for each parameter I have

```<code>$username = mysql_real_escape_string($username);
$email= mysql_real_escape_string($email);
$music= mysql_real_escape_string($music);
</code>```

答:
you may use,

```<code>list($id,$music) = array_map('mysql_real_escape_string',array($id,$music))
</code>```

but prepared statements rocks

Title: php - mysql avoid sql injections

Body:
I have many functions like

updateUser($id,$username,$email)
updateMusic($id, $music)

etc...

Is there a generic function to avoid SQL injections ?

I just want to avoid using mysql_real_escape_string for each parameter I have

$username = mysql_real_escape_string($username);
$email= mysql_real_escape_string($email);
$music= mysql_real_escape_string($music);

Body:
you may use,

list($id,$music) = array_map('mysql_real_escape_string',array($id,$music))

but prepared statements rocks


问:
Disable click event on text selection
I have the following jQuery, when a user clicks on a td, it reads the text of the td and then does a redirect. How can I disable the click event if the user is selecting the text instead clicking on the td?</p>

```<code>$("td").click(function() {
    var brand = $(this).closest("tr").attr("data-brand");
    var url = window.btoa(window.location.toString());
    window.location = "?page=sku&action=brand&brand=" + brand + "&b=" + url;
});
</code>```

答:
You can just do this</p>
```<code>function getSelected() {
   return (window.getSelection) ? window.getSelection().toString() : document.getSelection().toString();
}
</code>```

Title: Disable click event on text selection

Body:
I have the following jQuery, when a user clicks on a td, it reads the text of the td and then does a redirect. How can I disable the click event if the user is selecting the text instead clicking on the td?

$("td").click(function() {
    var brand = $(this).closest("tr").attr("data-brand");
    var url = window.btoa(window.location.toString());
    window.location = "?page=sku&action=brand&brand=" + brand + "&b=" + url;
});

Body:
You can just do this

function getSelected() {
   return (window.getSelection) ? window.getSelection().toString() : document.getSelection().toString();
}


问:
Convert a String into a List of Tuples
I want to write a function that receives a string as a parameter and then converts it into a list of tuples.

String with dummy data:

locations_data = """
NewYork 37.936389°N 23.947222°E
London  37.936389°N 23.947222°E
Berlin  37.936389°N 23.947222°E
Milano  37.936389°N 23.947222°E
```
<p>So far I know that I have to loop over the string splitter by <code>°E</code> but I'm getting confused when I have to separate each "rows" data.</p>
<pre class="lang-py prettyprint-override"><code>for i in locations_data.split("°E")
</code>```

Desired output:

locations = [
(NewYork, 37.936389, 23.947222),
(London, 37.936389, 23.947222),
(Berlin, 37.936389, 23.947222),
(Milano, 37.936389, 23.947222)
]
```

答:
You can use this way to solve the problem.

```<code>locations = list(map(lambda x: tuple(x.split()), locations_data.split("°E")[:4]))
print(locations)
</code>```

locations_data.split("°E")[:4] here this [:4] part is use to remove the last empty string.

Title: Convert a String into a List of Tuples

Body:
I want to write a function that receives a string as a parameter and then converts it into a list of tuples.

String with dummy data:

locations_data = """
NewYork 37.936389°N 23.947222°E
London  37.936389°N 23.947222°E
Berlin  37.936389°N 23.947222°E
Milano  37.936389°N 23.947222°E

So far I know that I have to loop over the string splitter by °E but I'm getting confused when I have to separate each "rows" data.

for i in locations_data.split("°E")

Desired output:

locations = [
(NewYork, 37.936389, 23.947222),
(London, 37.936389, 23.947222),
(Berlin, 37.936389, 23.947222),
(Milano, 37.936389, 23.947222)
]

Body:
You can use this way to solve the problem.

locations = list(map(lambda x: tuple(x.split()), locations_data.split("°E")[:4]))
print(locations)

locations_data.split("°E")[:4] here this [:4] part is use to remove the last empty string.


问:
Solving equation to find center point of circle from 3 points

I'm looking for a high precision solution to find the center point of a circle from 3 data points on a canvas (x,y). I found this example in the attached screenshot above, now I'm using the Math.NET package to solve the equation and I'm comparing the results against this online tool: https://planetcalc.com/8116/.

However, when I calculate the radius its completely off and often a negative number???

```<code>using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Double;
using System;

namespace ConsoleAppTestBed
{
  class Program
  {
    static void Main(string[] args)
    {
        var dataPoints = new double[,]
        {

            { 5, 80 },
            { 20, 100 },
            { 40, 140 }
        };

        var fitter = new CircleFitter();
        var result = fitter.Fit(dataPoints);

        var x = -result[0];
        var y = -result[1];
        var c = result[2];

        Console.WriteLine("Center Point:");
        Console.WriteLine(x);
        Console.WriteLine(y);
        Console.WriteLine(c);

        //// (x^2 + y^2 - c^2)
        var radius = Math.Pow(x, 2) + Math.Pow(y, 2) - Math.Pow(c, 2);
        //// sqrt((x^2 + y^2 - c^2))
        radius =  Math.Sqrt(radius);
        Console.WriteLine("Radius:");
        Console.WriteLine(radius);
        Console.ReadLine();
    }

    public class CircleFitter
    {
        public double[] Fit(double[,] v)
        {
            var xy1 = new double[] { v[0,0], v[0,1] };
            var xy2= new double[] { v[1, 0], v[1, 1] };
            var xy3 = new double[] { v[2, 0], v[2, 1] };

            // Create Left Side Matrix of Equation
            var a = CreateLeftSide_(xy1);
            var b = CreateLeftSide_(xy2);
            var c = CreateLeftSide_(xy3);
            var matrixA = DenseMatrix.OfArray(new[,]
            {
                { a[0], a[1], a[2] },
                { b[0], b[1], b[2] },
                { c[0], c[1], c[2] }
            });

            // Create Right Side Vector of Equation
            var d = CreateRightSide_(xy1);
            var e = CreateRightSide_(xy2);
            var f = CreateRightSide_(xy3);
            double[] vector = { d, e, f };
            var vectorB =  Vector<double>.Build.Dense(vector);

            // Solve Equation
            var r = matrixA.Solve(vectorB);
            var result = r.ToArray();

            return result;
        }

        //2x, 2y, 1
        public double[] CreateLeftSide_(double[] d)
        {
            return new double[] { (2 * d[0]), (2 * d[1]) , 1};

        }

        // -(x^2 + y^2)
        public double CreateRightSide_(double[] d)
        {
            return -(Math.Pow(d[0], 2) + Math.Pow(d[1], 2));

        }
    }
  }

}
</code>```

Any ideas?

Thanks in advance.

答:
Updated Answer

The equation for radius is incorrect; it should be (not c squared):

which is why you get incorrect values for the radius.

The original answer was incorrect, but it is still 'interesting'.

(Incorrect) Original Answer

The cause of the problematic calculation is not solely due to the precision of the numbers, but more because problem is ill-conditioned. If you look at the three points and where they are located on the circle, you'll see that they are bunched on a small segment of the circumference. When the points are so close to each other, it is a tough ask to find the circle's centre and radius accurately.

So the intermediate calculations, which will have small rounding errors, result in hugely exaggerated errors.

You can see the ill-conditioned nature of the problem by adding the ConditionNumber() method.

```<code>    // Solve Equation
    Console.WriteLine(matrixA.ConditionNumber()); // <<< Returns 5800 -> Big!
    var r = matrixA.Solve(vectorB);               // Existing code
</code>```

A large result indicates an ill-conditioned problem. In this case a value of 5800 is returned, which is large. You might get better results using Gaussian Elimination with partial pivoting, but it still does not address the fact that the basic problem is ill-conditioned, which is why you get wildly incorrect answers.

Body:
I'm looking for a high precision solution to find the center point of a circle from 3 data points on a canvas (x,y). I found this example in the attached screenshot above, now I'm using the Math.NET package to solve the equation and I'm comparing the results against this online tool: https://planetcalc.com/8116/.

However, when I calculate the radius its completely off and often a negative number???

using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Double;
using System;

namespace ConsoleAppTestBed
{
  class Program
  {
    static void Main(string[] args)
    {
        var dataPoints = new double[,]
        {

            { 5, 80 },
            { 20, 100 },
            { 40, 140 }
        };

        var fitter = new CircleFitter();
        var result = fitter.Fit(dataPoints);

        var x = -result[0];
        var y = -result[1];
        var c = result[2];

        Console.WriteLine("Center Point:");
        Console.WriteLine(x);
        Console.WriteLine(y);
        Console.WriteLine(c);

        //// (x^2 + y^2 - c^2)
        var radius = Math.Pow(x, 2) + Math.Pow(y, 2) - Math.Pow(c, 2);
        //// sqrt((x^2 + y^2 - c^2))
        radius =  Math.Sqrt(radius);
        Console.WriteLine("Radius:");
        Console.WriteLine(radius);
        Console.ReadLine();
    }

    public class CircleFitter
    {
        public double[] Fit(double[,] v)
        {
            var xy1 = new double[] { v[0,0], v[0,1] };
            var xy2= new double[] { v[1, 0], v[1, 1] };
            var xy3 = new double[] { v[2, 0], v[2, 1] };

            // Create Left Side Matrix of Equation
            var a = CreateLeftSide_(xy1);
            var b = CreateLeftSide_(xy2);
            var c = CreateLeftSide_(xy3);
            var matrixA = DenseMatrix.OfArray(new[,]
            {
                { a[0], a[1], a[2] },
                { b[0], b[1], b[2] },
                { c[0], c[1], c[2] }
            });

            // Create Right Side Vector of Equation
            var d = CreateRightSide_(xy1);
            var e = CreateRightSide_(xy2);
            var f = CreateRightSide_(xy3);
            double[] vector = { d, e, f };
            var vectorB =  Vector<double>.Build.Dense(vector);

            // Solve Equation
            var r = matrixA.Solve(vectorB);
            var result = r.ToArray();

            return result;
        }

        //2x, 2y, 1
        public double[] CreateLeftSide_(double[] d)
        {
            return new double[] { (2 * d[0]), (2 * d[1]) , 1};

        }

        // -(x^2 + y^2)
        public double CreateRightSide_(double[] d)
        {
            return -(Math.Pow(d[0], 2) + Math.Pow(d[1], 2));

        }
    }
  }

}

Any ideas?

Thanks in advance.

Body:
Updated Answer

The equation for radius is incorrect; it should be (not c squared):

which is why you get incorrect values for the radius.

The original answer was incorrect, but it is still 'interesting'.

(Incorrect) Original Answer

The cause of the problematic calculation is not solely due to the precision of the numbers, but more because problem is ill-conditioned. If you look at the three points and where they are located on the circle, you'll see that they are bunched on a small segment of the circumference. When the points are so close to each other, it is a tough ask to find the circle's centre and radius accurately.

So the intermediate calculations, which will have small rounding errors, result in hugely exaggerated errors.

You can see the ill-conditioned nature of the problem by adding the ConditionNumber() method.

    // Solve Equation
    Console.WriteLine(matrixA.ConditionNumber()); // <<< Returns 5800 -> Big!
    var r = matrixA.Solve(vectorB);               // Existing code

A large result indicates an ill-conditioned problem. In this case a value of 5800 is returned, which is large. You might get better results using Gaussian Elimination with partial pivoting, but it still does not address the fact that the basic problem is ill-conditioned, which is why you get wildly incorrect answers.


问:
Perl Get File Last Modified Date Time No Module
I'm creating a script where I need to get the Last Modified Date of the files
I checked this thread How do I get a file's last modified time in Perl?

So I used the script below to get the last modified, at first it was working but when I try to run it again, the timestamp returns 00:00 January 1, 1970.

Why is that happening and how can I get the correct last modified date and time?

```<code>my $dir = '/tmp';

opendir(DIR, $dir) or die $!;
@content=readdir(DIR);

foreach(@content)
{
    next unless ($_ =~ m/\bfile.txt|file2.csv\b/);

    my $epoch_timestamp = (stat($_))[9];
    my $timestamp       = localtime($epoch_timestamp);
    $f_detail = $_ .' '.$timestamp;
    print "$f_detail\n";
}
closedir(DIR);

exit 0;
</code>```

When I tried to run the perl, I will get this result

file.txt Thu Jan  1 00:00:00 1970

file2.csv Thu Jan  1 00:00:00 1970

Ok, last update, it is working now, I try to run all of the scripts you've given to me, standalone script. I found what's causing the default time, see the script below, I remove that in my program and it works, didn't notice this at first, sorry. But still, it feels weird because I was sure that it is working when I first run it, but now it is working so yeah thank you guys!

```<code>if (($month = ((localtime)[4] + 1)) < 10)
{
  $month = '0' . $month;
}
if (($day = ((localtime)[3])) < 10)
{
  $day = '0' . $day;
}
if (($year = ((localtime)[5]+1900)) >= 2000)
{

  if (($year = $year - 2000) < 10)
  {
    $year = '0' . $year;
  }
}
else
{
  $year = $year - 1900;
}

$date = $month . $day . $year;
</code>```

答:
Following demo code utilizes glob to obtain modification time for specified files in a directory.</p>
```<code>use strict;
use warnings;
use feature 'say';

my $dir   = '/tmp';
my @files = qw(file.txt file2.csv);
my $mask  = join ' ',  map { "$dir/$_" } @files;

say "$_\t" . localtime((stat($_))[9]) for glob($mask);
</code>```

Body:
I'm creating a script where I need to get the Last Modified Date of the files
I checked this thread How do I get a file's last modified time in Perl?

So I used the script below to get the last modified, at first it was working but when I try to run it again, the timestamp returns 00:00 January 1, 1970.

Why is that happening and how can I get the correct last modified date and time?

my $dir = '/tmp';

opendir(DIR, $dir) or die $!;
@content=readdir(DIR);

foreach(@content)
{
    next unless ($_ =~ m/\bfile.txt|file2.csv\b/);

    my $epoch_timestamp = (stat($_))[9];
    my $timestamp       = localtime($epoch_timestamp);
    $f_detail = $_ .' '.$timestamp;
    print "$f_detail\n";
}
closedir(DIR);

exit 0;

When I tried to run the perl, I will get this result

file.txt Thu Jan  1 00:00:00 1970

file2.csv Thu Jan  1 00:00:00 1970

Ok, last update, it is working now, I try to run all of the scripts you've given to me, standalone script. I found what's causing the default time, see the script below, I remove that in my program and it works, didn't notice this at first, sorry. But still, it feels weird because I was sure that it is working when I first run it, but now it is working so yeah thank you guys!

if (($month = ((localtime)[4] + 1)) < 10)
{
  $month = '0' . $month;
}
if (($day = ((localtime)[3])) < 10)
{
  $day = '0' . $day;
}
if (($year = ((localtime)[5]+1900)) >= 2000)
{

  if (($year = $year - 2000) < 10)
  {
    $year = '0' . $year;
  }
}
else
{
  $year = $year - 1900;
}

$date = $month . $day . $year;

Body:
Following demo code utilizes glob to obtain modification time for specified files in a directory.

use strict;
use warnings;
use feature 'say';

my $dir   = '/tmp';
my @files = qw(file.txt file2.csv);
my $mask  = join ' ',  map { "$dir/$_" } @files;

say "$_\t" . localtime((stat($_))[9]) for glob($mask);


问:
Correctly set the right picture orientation when shooting photo
On my iOS app written in Swift I need to take pictures and save them on gallery; as Apple documentation, all the pictures are taken in landscape also if the phone is in portrait; if we save the picture as-is it will be saved 90° rotated.

The question: How can I correctly manage the device orientation when saving picture?

Thank to some searches I used this solution:

```<code>    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        // ...error handling here

        guard let imageData = photo.fileDataRepresentation(with: self) else {
            NSLog("Fail to convert pixel buffer")
            return
        }

        // Save image to gallery here
    }

</code>```

My class is AVCapturePhotoFileDataRepresentationCustomizer delegate, so:

```<code>    func replacementMetadata(for photo: AVCapturePhoto) -> [String : Any]? {
        var properties = photo.metadata

        // Image orientation
        properties[kCGImagePropertyOrientation as String] = CGImagePropertyOrientation.right

        let exifData = NSMutableDictionary(dictionary: properties[kCGImagePropertyExifDictionary as String] as! NSDictionary)
        let xDimension = exifData[kCGImagePropertyExifPixelYDimension as String]
        let yDimension = exifData[kCGImagePropertyExifPixelXDimension as String]

        if xDimension != nil && yDimension != nil {
            exifData[kCGImagePropertyExifPixelXDimension as String] = xDimension
            exifData[kCGImagePropertyExifPixelYDimension as String] = yDimension

            properties[kCGImagePropertyExifDictionary as String] = exifData
        }

        return properties
    }
</code>```

Because the image is shot in portrait the orientation is .right and I read in my searches that also the X and Y dimensions in exif data should be swapped.

Unfortunately everything lead no result: Inspecting the saved image with an exif explorer image orientation is still a 0=unknown value and X and Y as originally set.

I'm sure the data is correctly set and written because:

Breakpoing on return properties underlined that the orientation tag set correctly; moreover if a tag is not correctly set or unknown the app crashes...

In the same replacementMetadata function I also set GPS data (I cut this for simplicity here!) and I wrote some test value (like heading = 101) and these data are correctly reported on the final image metadata.

So my question remains ... Thank you for pointing me in the right direction with code snippets or documents.

答:
```<code>import Foundation
import CoreMotion
import AVFoundation
import UIKit

protocol OrientationHandlerDelegate: class {
   func didChange(deviceOrientation: UIDeviceOrientation)
}

class OrientationHandler {

  private let motionManager = CMMotionManager()
  private let queue = OperationQueue()
  private var deviceOrientation: UIDeviceOrientation = .unknown
  weak var delegate: OrientationHandlerDelegate?

  init() {
    motionManager.accelerometerUpdateInterval = 1.0
    motionManager.deviceMotionUpdateInterval = 1.0
    motionManager.gyroUpdateInterval = 1.0
    motionManager.magnetometerUpdateInterval = 1.0
  }

  func startMeasuring() {
    guard motionManager.isDeviceMotionAvailable else {
        return
    }
    motionManager.startAccelerometerUpdates(to: queue) { [weak self] (accelerometerData, error) in
        guard let strongSelf = self else {
            return
        }
        guard let accelerometerData = accelerometerData else {
            return
        }

        let acceleration = accelerometerData.acceleration
        let xx = -acceleration.x
        let yy = acceleration.y
        let z = acceleration.z
        let angle = atan2(yy, xx)
        var deviceOrientation = strongSelf.deviceOrientation
        let absoluteZ = fabs(z)

        if deviceOrientation == .faceUp || deviceOrientation == .faceDown {
            if absoluteZ < 0.845 {
                if angle < -2.6 {
                    deviceOrientation = .landscapeRight
                } else if angle > -2.05 && angle < -1.1 {
                    deviceOrientation = .portrait
                } else if angle > -0.48 && angle < 0.48 {
                    deviceOrientation = .landscapeLeft
                } else if angle > 1.08 && angle < 2.08 {
                    deviceOrientation = .portraitUpsideDown
                }
            } else if z < 0 {
                deviceOrientation = .faceUp
            } else if z > 0 {
                deviceOrientation = .faceDown
            }
        } else {
            if z > 0.875 {
                deviceOrientation = .faceDown
            } else if z < -0.875 {
                deviceOrientation = .faceUp
            } else {
                switch deviceOrientation {
                case .landscapeLeft:
                    if angle < -1.07 {
                        deviceOrientation = .portrait
                    }
                    if angle > 1.08 {
                        deviceOrientation = .portraitUpsideDown
                    }
                case .landscapeRight:
                    if angle < 0 && angle > -2.05 {
                        deviceOrientation = .portrait
                    }
                    if angle > 0 && angle < 2.05 {
                        deviceOrientation = .portraitUpsideDown
                    }
                case .portraitUpsideDown:
                    if angle > 2.66 {
                        deviceOrientation = .landscapeRight
                    }
                    if angle < 0.48 {
                        deviceOrientation = .landscapeLeft
                    }
                case .portrait:
                    if angle > -0.47 {
                        deviceOrientation = .landscapeLeft
                    }
                    if angle < -2.64 {
                        deviceOrientation = .landscapeRight
                    }
                default:
                    if angle > -0.47 {
                        deviceOrientation = .landscapeLeft
                    }
                    if angle < -2.64 {
                        deviceOrientation = .landscapeRight
                    }
                }
            }
        }
        if strongSelf.deviceOrientation != deviceOrientation {
            strongSelf.deviceOrientation = deviceOrientation
            strongSelf.delegate?.didChange(deviceOrientation: deviceOrientation)
        }
    }
  }

  func stopMeasuring() {
    motionManager.stopAccelerometerUpdates()
  }

  func currentInterfaceOrientation() -> AVCaptureVideoOrientation {
    switch deviceOrientation {
    case .portrait:
        return .portrait
    case .landscapeRight:
        return .landscapeLeft
    case .landscapeLeft:
        return .landscapeRight
    case .portraitUpsideDown:
        return .portraitUpsideDown
    default:
        return .portrait
    }
  }
}
</code>```

In your file having camera code:

```<code>let orientationHandler = OrientationHandler()
</code>```

Start measuring orientation when camera is active.

```<code>orientationHandler.delegate = self
orientationHandler.startMeasuring()
</code>```

Stop measuring orientation when camera is not in use.

```<code>orientationHandler.stopMeasuring()
orientationHandler.delegate = nil
</code>```

Finally add one line just before calling capturePhoto(with: settings, delegate: self)

```<code>//Need to correct image orientation before moving further
    if let photoOutputConnection = photoOutput?.connection(with: .video) {
        photoOutputConnection.videoOrientation = orientationHandler.currentInterfaceOrientation()
    }
    photoOutput?.capturePhoto(with: settings, delegate: self)
</code>```

Body:
On my iOS app written in Swift I need to take pictures and save them on gallery; as Apple documentation, all the pictures are taken in landscape also if the phone is in portrait; if we save the picture as-is it will be saved 90° rotated.

The question: How can I correctly manage the device orientation when saving picture?

Thank to some searches I used this solution:

    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        // ...error handling here

        guard let imageData = photo.fileDataRepresentation(with: self) else {
            NSLog("Fail to convert pixel buffer")
            return
        }

        // Save image to gallery here
    }

My class is AVCapturePhotoFileDataRepresentationCustomizer delegate, so:

    func replacementMetadata(for photo: AVCapturePhoto) -> [String : Any]? {
        var properties = photo.metadata

        // Image orientation
        properties[kCGImagePropertyOrientation as String] = CGImagePropertyOrientation.right

        let exifData = NSMutableDictionary(dictionary: properties[kCGImagePropertyExifDictionary as String] as! NSDictionary)
        let xDimension = exifData[kCGImagePropertyExifPixelYDimension as String]
        let yDimension = exifData[kCGImagePropertyExifPixelXDimension as String]

        if xDimension != nil && yDimension != nil {
            exifData[kCGImagePropertyExifPixelXDimension as String] = xDimension
            exifData[kCGImagePropertyExifPixelYDimension as String] = yDimension

            properties[kCGImagePropertyExifDictionary as String] = exifData
        }

        return properties
    }

Because the image is shot in portrait the orientation is .right and I read in my searches that also the X and Y dimensions in exif data should be swapped.

Unfortunately everything lead no result: Inspecting the saved image with an exif explorer image orientation is still a 0=unknown value and X and Y as originally set.

I'm sure the data is correctly set and written because:

Breakpoing on return properties underlined that the orientation tag set correctly; moreover if a tag is not correctly set or unknown the app crashes...

In the same replacementMetadata function I also set GPS data (I cut this for simplicity here!) and I wrote some test value (like heading = 101) and these data are correctly reported on the final image metadata.

So my question remains ... Thank you for pointing me in the right direction with code snippets or documents.

Body:
import Foundation
import CoreMotion
import AVFoundation
import UIKit

protocol OrientationHandlerDelegate: class {
   func didChange(deviceOrientation: UIDeviceOrientation)
}

class OrientationHandler {

  private let motionManager = CMMotionManager()
  private let queue = OperationQueue()
  private var deviceOrientation: UIDeviceOrientation = .unknown
  weak var delegate: OrientationHandlerDelegate?

  init() {
    motionManager.accelerometerUpdateInterval = 1.0
    motionManager.deviceMotionUpdateInterval = 1.0
    motionManager.gyroUpdateInterval = 1.0
    motionManager.magnetometerUpdateInterval = 1.0
  }

  func startMeasuring() {
    guard motionManager.isDeviceMotionAvailable else {
        return
    }
    motionManager.startAccelerometerUpdates(to: queue) { [weak self] (accelerometerData, error) in
        guard let strongSelf = self else {
            return
        }
        guard let accelerometerData = accelerometerData else {
            return
        }

        let acceleration = accelerometerData.acceleration
        let xx = -acceleration.x
        let yy = acceleration.y
        let z = acceleration.z
        let angle = atan2(yy, xx)
        var deviceOrientation = strongSelf.deviceOrientation
        let absoluteZ = fabs(z)

        if deviceOrientation == .faceUp || deviceOrientation == .faceDown {
            if absoluteZ < 0.845 {
                if angle < -2.6 {
                    deviceOrientation = .landscapeRight
                } else if angle > -2.05 && angle < -1.1 {
                    deviceOrientation = .portrait
                } else if angle > -0.48 && angle < 0.48 {
                    deviceOrientation = .landscapeLeft
                } else if angle > 1.08 && angle < 2.08 {
                    deviceOrientation = .portraitUpsideDown
                }
            } else if z < 0 {
                deviceOrientation = .faceUp
            } else if z > 0 {
                deviceOrientation = .faceDown
            }
        } else {
            if z > 0.875 {
                deviceOrientation = .faceDown
            } else if z < -0.875 {
                deviceOrientation = .faceUp
            } else {
                switch deviceOrientation {
                case .landscapeLeft:
                    if angle < -1.07 {
                        deviceOrientation = .portrait
                    }
                    if angle > 1.08 {
                        deviceOrientation = .portraitUpsideDown
                    }
                case .landscapeRight:
                    if angle < 0 && angle > -2.05 {
                        deviceOrientation = .portrait
                    }
                    if angle > 0 && angle < 2.05 {
                        deviceOrientation = .portraitUpsideDown
                    }
                case .portraitUpsideDown:
                    if angle > 2.66 {
                        deviceOrientation = .landscapeRight
                    }
                    if angle < 0.48 {
                        deviceOrientation = .landscapeLeft
                    }
                case .portrait:
                    if angle > -0.47 {
                        deviceOrientation = .landscapeLeft
                    }
                    if angle < -2.64 {
                        deviceOrientation = .landscapeRight
                    }
                default:
                    if angle > -0.47 {
                        deviceOrientation = .landscapeLeft
                    }
                    if angle < -2.64 {
                        deviceOrientation = .landscapeRight
                    }
                }
            }
        }
        if strongSelf.deviceOrientation != deviceOrientation {
            strongSelf.deviceOrientation = deviceOrientation
            strongSelf.delegate?.didChange(deviceOrientation: deviceOrientation)
        }
    }
  }

  func stopMeasuring() {
    motionManager.stopAccelerometerUpdates()
  }

  func currentInterfaceOrientation() -> AVCaptureVideoOrientation {
    switch deviceOrientation {
    case .portrait:
        return .portrait
    case .landscapeRight:
        return .landscapeLeft
    case .landscapeLeft:
        return .landscapeRight
    case .portraitUpsideDown:
        return .portraitUpsideDown
    default:
        return .portrait
    }
  }
}

In your file having camera code:

let orientationHandler = OrientationHandler()

Start measuring orientation when camera is active.

orientationHandler.delegate = self
orientationHandler.startMeasuring()

Stop measuring orientation when camera is not in use.

orientationHandler.stopMeasuring()
orientationHandler.delegate = nil

Finally add one line just before calling capturePhoto(with: settings, delegate: self)

//Need to correct image orientation before moving further
    if let photoOutputConnection = photoOutput?.connection(with: .video) {
        photoOutputConnection.videoOrientation = orientationHandler.currentInterfaceOrientation()
    }
    photoOutput?.capturePhoto(with: settings, delegate: self)