问:
AttributeError: module 'tensorflow' has no attribute 'keras' in conda prompt
*I try to install tensorflow and keras

I installed tensorflow and I imported it with no errors

Keras is installed but I can't import it
*

```<code>(base) C:\Windows\system32>pip uninstall keras
Found existing installation: Keras 2.3.1
Uninstalling Keras-2.3.1:
  Would remove:
    c:\users\asus\anaconda3\anaconda\lib\site-packages\docs\*
    c:\users\asus\anaconda3\anaconda\lib\site-packages\keras-2.3.1.dist-info\*
    c:\users\asus\anaconda3\anaconda\lib\site-packages\keras\*
Proceed (y/n)? y
  Successfully uninstalled Keras-2.3.1

(base) C:\Windows\system32>pip install keras
Collecting keras
  Using cached Keras-2.3.1-py2.py3-none-any.whl (377 kB)
Requirement already satisfied: six>=1.9.0 in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (1.14.0)
Requirement already satisfied: numpy>=1.9.1 in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (1.18.4)
Requirement already satisfied: keras-applications>=1.0.6 in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (1.0.8)
Requirement already satisfied: keras-preprocessing>=1.0.5 in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (1.1.2)
Requirement already satisfied: scipy>=0.14 in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (1.4.1)
Requirement already satisfied: pyyaml in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (5.3.1)
Requirement already satisfied: h5py in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (2.10.0)
Installing collected packages: keras
Successfully installed keras-2.3.1
</code>```

then I try

```<code>(base) C:\Windows\system32>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> from keras.models import sequential
Using TensorFlow backend.
2020-05-21 10:03:38.204077: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-05-21 10:03:38.210602: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\__init__.py", line 3, in <module>
    from . import utils
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\utils\__init__.py", line 26, in <module>
    from .vis_utils import model_to_dot
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\utils\vis_utils.py", line 7, in <module>
    from ..models import Model
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\models.py", line 10, in <module>
    from .engine.input_layer import Input
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\__init__.py", line 8, in <module>
    from .training import Model
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\training.py", line 14, in <module>
    from . import training_utils
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\training_utils.py", line 17, in <module>
    from .. import metrics as metrics_module
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\metrics.py", line 1850, in <module>
    BaseMeanIoU = tf.keras.metrics.MeanIoU
AttributeError: module 'tensorflow' has no attribute 'keras'
>>> from keras.models import Sequential
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\__init__.py", line 3, in <module>
    from . import utils
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\utils\__init__.py", line 26, in <module>
    from .vis_utils import model_to_dot
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\utils\vis_utils.py", line 7, in <module>
    from ..models import Model
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\models.py", line 12, in <module>
    from .engine.training import Model
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\__init__.py", line 8, in <module>
    from .training import Model
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\training.py", line 14, in <module>
    from . import training_utils
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\training_utils.py", line 17, in <module>
    from .. import metrics as metrics_module
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\metrics.py", line 1850, in <module>
    BaseMeanIoU = tf.keras.metrics.MeanIoU
AttributeError: module 'tensorflow' has no attribute 'keras'
</code>```

I try :
  pip install --upgrade --no-deps --force-reinstall tensorflow

pip install --upgrade pip setuptools wheel

pip uninstall protobuf

pip install protobuf

pip install termcolor

**I have:
keras                     2.3.1                    pypi_0    pypi

keras-applications        1.0.8                    pypi_0    pypi

keras-preprocessing       1.1.2                    pypi_0    pypi

keyring                   21.1.1                   py36_2

kivy                      1.10.1.dev0              pypi_0    pypi

kivy-deps-glew            0.2.0                    pypi_0    pypi

kivy-deps-gstreamer       0.2.0                    pypi_0    pypi

kivy-deps-sdl2            0.2.0                    pypi_0    pypi

kivy-garden               0.1.4                    pypi_0    pypi

kiwisolver                1.2.0            py36h74a9793_0

lazy-object-proxy         1.4.3            py36he774522_0
**

I have numpy, pytorch, pip, tensorflow, and most DL, ML, CV, Ai, DS libraries

```<code>(base) C:\Users\ASUS>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import tensorflow
2020-05-22 06:23:19.327748: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-05-22 06:23:19.343057: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
>>> print(tensorflow)
<module 'tensorflow' from 'C:\\Users\\ASUS\\Anaconda3\\Anaconda\\lib\\site-packages\\tensorflow\\__init__.py'>
>>>
</code>```

When I run tensorflow

```<code>(base) C:\Users\ASUS>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow.compat.v1 as tf
2020-05-22 06:18:12.900849: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-05-22 06:18:12.914907: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
>>> tf.disable_v2_behavior()
WARNING:tensorflow:From C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\tensorflow\python\compat\v2_compat.py:96: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not supported in the long term
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.compat.v1.Session()
2020-05-22 06:20:28.305196: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library nvcuda.dll
2020-05-22 06:20:29.278356: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1561] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1050 computeCapability: 6.1
coreClock: 1.493GHz coreCount: 5 deviceMemorySize: 4.00GiB deviceMemoryBandwidth: 104.43GiB/s
2020-05-22 06:20:29.295408: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-05-22 06:20:29.305186: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cublas64_10.dll'; dlerror: cublas64_10.dll not found
2020-05-22 06:20:29.314235: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cufft64_10.dll'; dlerror: cufft64_10.dll not found
2020-05-22 06:20:29.323997: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'curand64_10.dll'; dlerror: curand64_10.dll not found
2020-05-22 06:20:29.336231: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cusolver64_10.dll'; dlerror: cusolver64_10.dll not found
2020-05-22 06:20:29.349522: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cusparse64_10.dll'; dlerror: cusparse64_10.dll not found
2020-05-22 06:20:29.362633: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudnn64_7.dll'; dlerror: cudnn64_7.dll not found
2020-05-22 06:20:29.372823: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1598] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
2020-05-22 06:20:29.392493: I tensorflow/core/platform/cpu_feature_guard.cc:143] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2020-05-22 06:20:29.413844: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x18bf4dc2f60 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-05-22 06:20:29.424116: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
2020-05-22 06:20:29.432117: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-05-22 06:20:29.446877: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1108]
>>> print(sess.run(hello))
b'Hello, TensorFlow!'
</code>```

After I Solve it
  Check my answer below

```<code>(base) C:\Users\ASUS>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
2020-05-29 17:59:47.814562: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_101.dll
>>> import keras
Using TensorFlow backend.
>>> from keras.models import Sequential
>>> tf.test.is_built_with_cuda()
True
>>> tf.config.list_physical_devices('GPU')
2020-05-29 18:02:56.764618: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library nvcuda.dll
2020-05-29 18:02:57.602680: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1561] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1050 computeCapability: 6.1
coreClock: 1.493GHz coreCount: 5 deviceMemorySize: 4.00GiB deviceMemoryBandwidth: 104.43GiB/s
2020-05-29 18:02:57.607142: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_101.dll
2020-05-29 18:02:57.703213: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cublas64_10.dll
2020-05-29 18:02:57.766722: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cufft64_10.dll
2020-05-29 18:02:57.797062: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library curand64_10.dll
2020-05-29 18:02:57.872961: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusolver64_10.dll
2020-05-29 18:02:57.920469: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusparse64_10.dll
2020-05-29 18:02:58.035860: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudnn64_7.dll
2020-05-29 18:02:58.148699: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1703] Adding visible gpu devices: 0
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
>>> tf.test.is_gpu_available(cuda_only=False, min_cuda_compute_capability=None)
2020-05-29 18:03:43.187834: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1561] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1050 computeCapability: 6.1
coreClock: 1.493GHz coreCount: 5 deviceMemorySize: 4.00GiB deviceMemoryBandwidth: 104.43GiB/s
2020-05-29 18:03:43.200093: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_101.dll
2020-05-29 18:03:43.205083: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cublas64_10.dll
2020-05-29 18:03:43.214701: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cufft64_10.dll
2020-05-29 18:03:43.217616: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library curand64_10.dll
2020-05-29 18:03:43.229945: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusolver64_10.dll
2020-05-29 18:03:43.238134: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusparse64_10.dll
2020-05-29 18:03:43.247848: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudnn64_7.dll
2020-05-29 18:03:43.256302: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1703] Adding visible gpu devices: 0
2020-05-29 18:03:43.264822: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-05-29 18:03:43.269994: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1108]      0
2020-05-29 18:03:43.271951: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1121] 0:   N
2020-05-29 18:03:43.275672: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1247] Created TensorFlow device (/device:GPU:0 with 2993 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1050, pci bus id: 0000:01:00.0, compute capability: 6.1)
True
>>>
</code>```

答: Thanks for all answers But I solve it I follow this tutorial with CUDA 10.1 https://towardsdatascience.com/installing-tensorflow-with-cuda-cudnn-and-gpu-support-on-windows-10-60693e46e781 .After this tutorial I uninstall this Libs and install it againpip install keras, pip install --upgrade setuptools, pip install cmake, pip install keras-models, pip install keras-applications, pip install keras-preprocessing and download Visual studio 2015. Then Run Code from my quesion like from keras.models import Sequential and check pathon path.

Body:
*I try to install tensorflow and keras

I installed tensorflow and I imported it with no errors

Keras is installed but I can't import it
*

(base) C:\Windows\system32>pip uninstall keras
Found existing installation: Keras 2.3.1
Uninstalling Keras-2.3.1:
  Would remove:
    c:\users\asus\anaconda3\anaconda\lib\site-packages\docs\*
    c:\users\asus\anaconda3\anaconda\lib\site-packages\keras-2.3.1.dist-info\*
    c:\users\asus\anaconda3\anaconda\lib\site-packages\keras\*
Proceed (y/n)? y
  Successfully uninstalled Keras-2.3.1

(base) C:\Windows\system32>pip install keras
Collecting keras
  Using cached Keras-2.3.1-py2.py3-none-any.whl (377 kB)
Requirement already satisfied: six>=1.9.0 in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (1.14.0)
Requirement already satisfied: numpy>=1.9.1 in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (1.18.4)
Requirement already satisfied: keras-applications>=1.0.6 in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (1.0.8)
Requirement already satisfied: keras-preprocessing>=1.0.5 in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (1.1.2)
Requirement already satisfied: scipy>=0.14 in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (1.4.1)
Requirement already satisfied: pyyaml in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (5.3.1)
Requirement already satisfied: h5py in c:\users\asus\anaconda3\anaconda\lib\site-packages (from keras) (2.10.0)
Installing collected packages: keras
Successfully installed keras-2.3.1

then I try

(base) C:\Windows\system32>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> from keras.models import sequential
Using TensorFlow backend.
2020-05-21 10:03:38.204077: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-05-21 10:03:38.210602: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\__init__.py", line 3, in <module>
    from . import utils
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\utils\__init__.py", line 26, in <module>
    from .vis_utils import model_to_dot
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\utils\vis_utils.py", line 7, in <module>
    from ..models import Model
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\models.py", line 10, in <module>
    from .engine.input_layer import Input
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\__init__.py", line 8, in <module>
    from .training import Model
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\training.py", line 14, in <module>
    from . import training_utils
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\training_utils.py", line 17, in <module>
    from .. import metrics as metrics_module
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\metrics.py", line 1850, in <module>
    BaseMeanIoU = tf.keras.metrics.MeanIoU
AttributeError: module 'tensorflow' has no attribute 'keras'
>>> from keras.models import Sequential
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\__init__.py", line 3, in <module>
    from . import utils
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\utils\__init__.py", line 26, in <module>
    from .vis_utils import model_to_dot
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\utils\vis_utils.py", line 7, in <module>
    from ..models import Model
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\models.py", line 12, in <module>
    from .engine.training import Model
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\__init__.py", line 8, in <module>
    from .training import Model
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\training.py", line 14, in <module>
    from . import training_utils
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\engine\training_utils.py", line 17, in <module>
    from .. import metrics as metrics_module
  File "C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\keras\metrics.py", line 1850, in <module>
    BaseMeanIoU = tf.keras.metrics.MeanIoU
AttributeError: module 'tensorflow' has no attribute 'keras'

I try :
  pip install --upgrade --no-deps --force-reinstall tensorflow

pip install --upgrade pip setuptools wheel

pip uninstall protobuf

pip install protobuf

pip install termcolor

**I have:
keras                     2.3.1                    pypi_0    pypi

keras-applications        1.0.8                    pypi_0    pypi

keras-preprocessing       1.1.2                    pypi_0    pypi

keyring                   21.1.1                   py36_2

kivy                      1.10.1.dev0              pypi_0    pypi

kivy-deps-glew            0.2.0                    pypi_0    pypi

kivy-deps-gstreamer       0.2.0                    pypi_0    pypi

kivy-deps-sdl2            0.2.0                    pypi_0    pypi

kivy-garden               0.1.4                    pypi_0    pypi

kiwisolver                1.2.0            py36h74a9793_0

lazy-object-proxy         1.4.3            py36he774522_0
**

I have numpy, pytorch, pip, tensorflow, and most DL, ML, CV, Ai, DS libraries

(base) C:\Users\ASUS>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import tensorflow
2020-05-22 06:23:19.327748: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-05-22 06:23:19.343057: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
>>> print(tensorflow)
<module 'tensorflow' from 'C:\\Users\\ASUS\\Anaconda3\\Anaconda\\lib\\site-packages\\tensorflow\\__init__.py'>
>>>

When I run tensorflow

(base) C:\Users\ASUS>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow.compat.v1 as tf
2020-05-22 06:18:12.900849: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-05-22 06:18:12.914907: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
>>> tf.disable_v2_behavior()
WARNING:tensorflow:From C:\Users\ASUS\Anaconda3\Anaconda\lib\site-packages\tensorflow\python\compat\v2_compat.py:96: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not supported in the long term
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.compat.v1.Session()
2020-05-22 06:20:28.305196: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library nvcuda.dll
2020-05-22 06:20:29.278356: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1561] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1050 computeCapability: 6.1
coreClock: 1.493GHz coreCount: 5 deviceMemorySize: 4.00GiB deviceMemoryBandwidth: 104.43GiB/s
2020-05-22 06:20:29.295408: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-05-22 06:20:29.305186: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cublas64_10.dll'; dlerror: cublas64_10.dll not found
2020-05-22 06:20:29.314235: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cufft64_10.dll'; dlerror: cufft64_10.dll not found
2020-05-22 06:20:29.323997: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'curand64_10.dll'; dlerror: curand64_10.dll not found
2020-05-22 06:20:29.336231: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cusolver64_10.dll'; dlerror: cusolver64_10.dll not found
2020-05-22 06:20:29.349522: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cusparse64_10.dll'; dlerror: cusparse64_10.dll not found
2020-05-22 06:20:29.362633: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudnn64_7.dll'; dlerror: cudnn64_7.dll not found
2020-05-22 06:20:29.372823: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1598] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
2020-05-22 06:20:29.392493: I tensorflow/core/platform/cpu_feature_guard.cc:143] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
2020-05-22 06:20:29.413844: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x18bf4dc2f60 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-05-22 06:20:29.424116: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
2020-05-22 06:20:29.432117: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-05-22 06:20:29.446877: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1108]
>>> print(sess.run(hello))
b'Hello, TensorFlow!'

After I Solve it
  Check my answer below

(base) C:\Users\ASUS>python
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
2020-05-29 17:59:47.814562: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_101.dll
>>> import keras
Using TensorFlow backend.
>>> from keras.models import Sequential
>>> tf.test.is_built_with_cuda()
True
>>> tf.config.list_physical_devices('GPU')
2020-05-29 18:02:56.764618: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library nvcuda.dll
2020-05-29 18:02:57.602680: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1561] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1050 computeCapability: 6.1
coreClock: 1.493GHz coreCount: 5 deviceMemorySize: 4.00GiB deviceMemoryBandwidth: 104.43GiB/s
2020-05-29 18:02:57.607142: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_101.dll
2020-05-29 18:02:57.703213: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cublas64_10.dll
2020-05-29 18:02:57.766722: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cufft64_10.dll
2020-05-29 18:02:57.797062: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library curand64_10.dll
2020-05-29 18:02:57.872961: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusolver64_10.dll
2020-05-29 18:02:57.920469: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusparse64_10.dll
2020-05-29 18:02:58.035860: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudnn64_7.dll
2020-05-29 18:02:58.148699: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1703] Adding visible gpu devices: 0
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
>>> tf.test.is_gpu_available(cuda_only=False, min_cuda_compute_capability=None)
2020-05-29 18:03:43.187834: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1561] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1050 computeCapability: 6.1
coreClock: 1.493GHz coreCount: 5 deviceMemorySize: 4.00GiB deviceMemoryBandwidth: 104.43GiB/s
2020-05-29 18:03:43.200093: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudart64_101.dll
2020-05-29 18:03:43.205083: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cublas64_10.dll
2020-05-29 18:03:43.214701: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cufft64_10.dll
2020-05-29 18:03:43.217616: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library curand64_10.dll
2020-05-29 18:03:43.229945: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusolver64_10.dll
2020-05-29 18:03:43.238134: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cusparse64_10.dll
2020-05-29 18:03:43.247848: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library cudnn64_7.dll
2020-05-29 18:03:43.256302: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1703] Adding visible gpu devices: 0
2020-05-29 18:03:43.264822: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-05-29 18:03:43.269994: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1108]      0
2020-05-29 18:03:43.271951: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1121] 0:   N
2020-05-29 18:03:43.275672: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1247] Created TensorFlow device (/device:GPU:0 with 2993 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1050, pci bus id: 0000:01:00.0, compute capability: 6.1)
True
>>>


来源: stackexchange

问:
Time complexity of string repetition (via str * int)
What's the time complexity of repeating a string in python with the String * int operator?

To be clear, I'm talking about this phenomenon:

```<code>print("a"*4)
</code>```

would output "aaaa"

I tried to find an answer myself, but can't find anything about this, and it's worse because I am unsure of what it's called... I'm just calling it string repetition for now.

答:
According to this lecture, given an integer k and a list l, k*l is of complexity O(k*N).

Since strings are iterables too, I assume the answer is the same for strings.

ContentLicense: CC BY-SA 4.0

Body:
What's the time complexity of repeating a string in python with the String * int operator?

To be clear, I'm talking about this phenomenon:

print("a"*4)

would output "aaaa"

I tried to find an answer myself, but can't find anything about this, and it's worse because I am unsure of what it's called... I'm just calling it string repetition for now.


问:
Conflict with loading up mock data for unit testing between PyCharm and unittests
I have a Python project structure as follows.

```
.
├── data
├── src
│   ├── module1
│   └── module2
└── tests
    ├── base
    ├── module1
    └── module2
```

The data directory is where I put mock data for use in unit test (e.g. CSV files). If I am inside PyCharm, inside a unit test, I can use a relative path as below and use the IDE to run a unit test (using unittests) successfully.

```<code>pd.read_csv('../../data/mock.csv')
</code>```

However, outside of PyCharm, I can try to run the following command to run the unit test.

```<code>python -m unittest tests/module1/*.py
</code>```

I will get an error that says the file does not exists. If I change the path as follows, then running the unit test from outside PyCharm works, but running the test within PyCharm fails.

```<code>pd.read_csv('./data/mock.csv')
</code>```

When I inspect the unit test configuration, I notice that the working directory is set to /Users/myusername/myproject/tests/module1. If I change the working directory to /Users/myusername/myproject, I get the following error: AssertionError: Path must be within the project.

I even tried to move the data directory into tests > module1, but the same conflict remains; now pd.read_csv('./data/mock.csv') works for PyCharm but fails for the terminal.

Any ideas on how to resolve this conflict?

答:
I solved this problem by abstracting out getting the path to mock data.

```<code>def normalize_path(resource, proj_root='root_folder'):
    path = os.getcwd() # current working directory
    tokens = path.split('/') # tokens of directory path
    index = tokens.index(proj_root) # look for where project root ends
    tokens = tokens[1:index + 1] # reconstruct the path up to the project root
    p = '/'.join(tokens)
    p = f'/{p}/{resource}' # append the resource to the project root

    return p
</code>```

In my code, now I do something like the following.

```<code>pd.read_csv(normalize_path('data/mock.csv'))
</code>```

I can execute tests from the terminal or PyCharm without any problem.

Body:
I have a Python project structure as follows.

.
├── data
├── src
│   ├── module1
│   └── module2
└── tests
    ├── base
    ├── module1
    └── module2

The data directory is where I put mock data for use in unit test (e.g. CSV files). If I am inside PyCharm, inside a unit test, I can use a relative path as below and use the IDE to run a unit test (using unittests) successfully.

pd.read_csv('../../data/mock.csv')

However, outside of PyCharm, I can try to run the following command to run the unit test.

python -m unittest tests/module1/*.py

I will get an error that says the file does not exists. If I change the path as follows, then running the unit test from outside PyCharm works, but running the test within PyCharm fails.

pd.read_csv('./data/mock.csv')

When I inspect the unit test configuration, I notice that the working directory is set to /Users/myusername/myproject/tests/module1. If I change the working directory to /Users/myusername/myproject, I get the following error: AssertionError: Path must be within the project.

I even tried to move the data directory into tests > module1, but the same conflict remains; now pd.read_csv('./data/mock.csv') works for PyCharm but fails for the terminal.

Any ideas on how to resolve this conflict?

Body:
I solved this problem by abstracting out getting the path to mock data.

def normalize_path(resource, proj_root='root_folder'):
    path = os.getcwd() # current working directory
    tokens = path.split('/') # tokens of directory path
    index = tokens.index(proj_root) # look for where project root ends
    tokens = tokens[1:index + 1] # reconstruct the path up to the project root
    p = '/'.join(tokens)
    p = f'/{p}/{resource}' # append the resource to the project root

    return p

In my code, now I do something like the following.

pd.read_csv(normalize_path('data/mock.csv'))

I can execute tests from the terminal or PyCharm without any problem.


问:
In what situation would you use "module procedure" in a submodule when creating separate module procedures?
I understand the general benefits of submodules in Fortran 2008+, but I'm having trouble understanding the benefit of one of the syntax options.

If I want to create separate module procedures (where the body of the procedure is in a submodule) I need to create an interface in the parent module. That interface must contain the subroutine or function identifier and the argument list and intent. This all makes sense.

Then the submodule contains the implementation of the procedure, but there is a choice of syntax: I can either repeat the signature for the subroutine or function, or, I can simply use the name from the interface after "module procedure." I was going to type out an example but the fortran wiki shows it perfectly.

My question is: What is the benefit of using the alternate syntax using "module procedure" instead of "module function" or "module subroutine", i.e. where the procedure type, arguments, and intent are not duplicated in the submodule file? It seems that this just complicates code maintenance, as now two files need to be open to understand the subroutine or function. Am I missing some hidden benefit here (besides saving a copy/paste)?

答: The benefit comes later in the life of the code. If you have to change the function's signature, you only have to change it in one location.</p>


问:
Display message when hovering over something with mouse cursor in Python
I have a GUI made with TKinter in Python. I would like to be able to display a message when my mouse cursor goes, for example, on top of a label or button. The purpose of this is to explain to the user what the button/label does or represents.

Is there a way to display text when hovering over a tkinter object in Python?

答:
If anyone is on Mac OSX and tool tip isn't working, check out the example in:

https://github.com/python/cpython/blob/master/Lib/idlelib/tooltip.py

Basically, the two lines that made it work for me on Mac OSX were:

```<code>    tw.update_idletasks()  # Needed on MacOS -- see #34275.
    tw.lift()  # work around bug in Tk 8.5.18+ (issue #24570)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If anyone is on Mac OSX and tool tip isn't working, check out the example in:

https://github.com/python/cpython/blob/master/Lib/idlelib/tooltip.py

Basically, the two lines that made it work for me on Mac OSX were:

    tw.update_idletasks()  # Needed on MacOS -- see #34275.
    tw.lift()  # work around bug in Tk 8.5.18+ (issue #24570)


问:
Css Grid Layout Issues ( with flexbox )
I'm trying to create a layout using the Flex structure. This is exactly the main image I wanted it to be.

This layout will also be compatible with the mobile view.

1- My Sidebar component doesn't stick to the bottom of my hero component. I used "margin-top: -200px;" for this problem. but I don't want that.

2- Between my components, I want to use margin as pictured. But because I calculate the size of each component as a percentage of "%" and they completely cover the page, if I give margin, they become wrap. What's the right way for me to do this ?

3- Do you think the flexbox settings I have applied are correct ? What would be better for me to change ?

Thank you in advance for your help.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.header {
  background-color: #59D4EB;
  text-align: center;
  height: 80px;
}

/* Main Container */

.container {
  display: flex;
  flex-flow: column nowrap;
  text-align: center;
}

/* Container */

.container-main {
  display: flex;
  flex-wrap: wrap;
}

/* Items */

.hero {
  flex: 1 0 40%;
  height: 400px;
  background-color: #D5C9E2;
}

.main-content {
  flex: 1 0 60%;
  height: 600px;
  background-color: #F5C546;
}

.sidebar {
  height: 500px;
  flex: 1 0 40%;
  background-color: #A0C263;
  /* I DONT WANT USE THİS  MARGİN-TOP */
  margin-top: -200px;
}

.extra-content {
  flex: 1 0 60%;
  background-color: #898989;
  height: 300px;
}

/* Container */

.images-posts-cont {
  display: flex;
  height: 150px;
}

/* Items */

.images {
  flex: 1 0 70%;
  background-color: #53B774;
}

.posts {
  flex: 1 0 30%;
  background-color: #F3CDDD;
}

/* Footer */

.footer {
  text-align: center;
  height: 80px;
  background-color: #F4A540;
}

@media screen and (max-width:599px) {
  .hero {
    flex: 1 0 100%;
    order: 1;
  }
  .sidebar {
    flex: 1 0 100%;
    order: 2;
  }
  .main-content {
    order: 3;
  }
  .extra-content {
    order: 4;
  }
}

;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="src/css/test.css">
  <title> Flexbox Layout</title>
</head>

<body>
  <!-- FlexBox Layout -->
  <header class="header">
    <h2>header</h2>
  </header>
  <div class="container">
    <section class="container-main">
      <div class="hero">
        <h2>hero</h2>
      </div>
      <div class="main-content">
        <h2>main-content</h2>
      </div>
      <div class="sidebar">
        <h2>sidebar</h2>
      </div>
      <div class="extra-content">
        <h2>extra content</h2>
      </div>
    </section>
    <section class="images-posts-cont">
      <div class="images">
        <h2>related images</h2>
      </div>
      <div class="posts">
        <h2>related posts</h2>
      </div>
    </section>
    <footer class="footer">
      <h2>footer</h2>
    </footer>
  </div>

</body>

</html></code>```

答:
I think you can still use flex. Just you have to wrap both components left and right with div.

left = > hero and side nav

right = > main content and extra content

I just add 2 div. Look below the code.

    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }

    .header {
      background-color: #59D4EB;
      text-align: center;
      height: 80px;
    }

    /* Main Container */

    .container {
      display: flex;
      flex-flow: column nowrap;
      text-align: center;
    }

    /* Container */

    .container-main {
      display: flex;
      flex-wrap: wrap;
    }

    /* Items */
    .left{
      width: 40%;
    }
    .right {
      width: 60%;
    }
    .hero {
      height: 400px;
      background-color: #D5C9E2;
    }

    .main-content {
      flex: 1 0 60%;
      height: 600px;
      background-color: #F5C546;
    }

    .sidebar {
      height: 500px;
      flex: 1 0 40%;
      background-color: #A0C263;
      /* I DONT WANT USE THİS  MARGİN-TOP */
    }

    .extra-content {
      flex: 1 0 60%;
      background-color: #898989;
      height: 300px;
    }

    /* Container */

    .images-posts-cont {
      display: flex;
      height: 150px;
    }

    /* Items */

    .images {
      flex: 1 0 70%;
      background-color: #53B774;
    }

    .posts {
      flex: 1 0 30%;
      background-color: #F3CDDD;
    }

    /* Footer */

    .footer {
      text-align: center;
      height: 80px;
      background-color: #F4A540;
    }

    @media screen and (max-width:599px) {
      .hero {
        flex: 1 0 100%;
        order: 1;
      }
      .sidebar {
        flex: 1 0 100%;
        order: 2;
      }
      .main-content {
        order: 3;
      }
      .extra-content {
        order: 4;
      }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>     <body>
         <!-- FlexBox Layout -->
      <header class="header">
        <h2>header</h2>
      </header>
      <div class="container">
        <section class="container-main">
          <div class="left">
          <div class="hero">
            <h2>hero</h2>
          </div>
            <div class="sidebar">
            <h2>sidebar</h2>
          </div>
          </div>
          <div class="right">
          <div class="main-content">
            <h2>main-content</h2>
          </div>
            <div class="extra-content">
            <h2>extra content</h2>
          </div>
          </div>

        </section>
        <section class="images-posts-cont">
          <div class="images">
            <h2>related images</h2>
          </div>
          <div class="posts">
            <h2>related posts</h2>
          </div>
        </section>
        <footer class="footer">
          <h2>footer</h2>
        </footer>
      </div>
    </body></code>```

Title: Css Grid Layout Issues ( with flexbox )

Body:
I'm trying to create a layout using the Flex structure. This is exactly the main image I wanted it to be.

This layout will also be compatible with the mobile view.

1- My Sidebar component doesn't stick to the bottom of my hero component. I used "margin-top: -200px;" for this problem. but I don't want that.

2- Between my components, I want to use margin as pictured. But because I calculate the size of each component as a percentage of "%" and they completely cover the page, if I give margin, they become wrap. What's the right way for me to do this ?

3- Do you think the flexbox settings I have applied are correct ? What would be better for me to change ?

Thank you in advance for your help.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.header {
  background-color: #59D4EB;
  text-align: center;
  height: 80px;
}

/* Main Container */

.container {
  display: flex;
  flex-flow: column nowrap;
  text-align: center;
}

/* Container */

.container-main {
  display: flex;
  flex-wrap: wrap;
}

/* Items */

.hero {
  flex: 1 0 40%;
  height: 400px;
  background-color: #D5C9E2;
}

.main-content {
  flex: 1 0 60%;
  height: 600px;
  background-color: #F5C546;
}

.sidebar {
  height: 500px;
  flex: 1 0 40%;
  background-color: #A0C263;
  /* I DONT WANT USE THİS  MARGİN-TOP */
  margin-top: -200px;
}

.extra-content {
  flex: 1 0 60%;
  background-color: #898989;
  height: 300px;
}

/* Container */

.images-posts-cont {
  display: flex;
  height: 150px;
}

/* Items */

.images {
  flex: 1 0 70%;
  background-color: #53B774;
}

.posts {
  flex: 1 0 30%;
  background-color: #F3CDDD;
}

/* Footer */

.footer {
  text-align: center;
  height: 80px;
  background-color: #F4A540;
}

@media screen and (max-width:599px) {
  .hero {
    flex: 1 0 100%;
    order: 1;
  }
  .sidebar {
    flex: 1 0 100%;
    order: 2;
  }
  .main-content {
    order: 3;
  }
  .extra-content {
    order: 4;
  }
}

;

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="src/css/test.css">
  <title> Flexbox Layout</title>

header

hero

main-content

sidebar

extra content

related images

related posts

footer

Body:
I think you can still use flex. Just you have to wrap both components left and right with div.

left = > hero and side nav

right = > main content and extra content

I just add 2 div. Look below the code.

    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }

    .header {
      background-color: #59D4EB;
      text-align: center;
      height: 80px;
    }

    /* Main Container */

    .container {
      display: flex;
      flex-flow: column nowrap;
      text-align: center;
    }

    /* Container */

    .container-main {
      display: flex;
      flex-wrap: wrap;
    }

    /* Items */
    .left{
      width: 40%;
    }
    .right {
      width: 60%;
    }
    .hero {
      height: 400px;
      background-color: #D5C9E2;
    }

    .main-content {
      flex: 1 0 60%;
      height: 600px;
      background-color: #F5C546;
    }

    .sidebar {
      height: 500px;
      flex: 1 0 40%;
      background-color: #A0C263;
      /* I DONT WANT USE THİS  MARGİN-TOP */
    }

    .extra-content {
      flex: 1 0 60%;
      background-color: #898989;
      height: 300px;
    }

    /* Container */

    .images-posts-cont {
      display: flex;
      height: 150px;
    }

    /* Items */

    .images {
      flex: 1 0 70%;
      background-color: #53B774;
    }

    .posts {
      flex: 1 0 30%;
      background-color: #F3CDDD;
    }

    /* Footer */

    .footer {
      text-align: center;
      height: 80px;
      background-color: #F4A540;
    }

    @media screen and (max-width:599px) {
      .hero {
        flex: 1 0 100%;
        order: 1;
      }
      .sidebar {
        flex: 1 0 100%;
        order: 2;
      }
      .main-content {
        order: 3;
      }
      .extra-content {
        order: 4;
      }
    }

     <body>
         <!-- FlexBox Layout -->
      <header class="header">
        <h2>header</h2>
      </header>
      <div class="container">
        <section class="container-main">
          <div class="left">
          <div class="hero">
            <h2>hero</h2>
          </div>
            <div class="sidebar">
            <h2>sidebar</h2>
          </div>
          </div>
          <div class="right">
          <div class="main-content">
            <h2>main-content</h2>
          </div>
            <div class="extra-content">
            <h2>extra content</h2>
          </div>
          </div>

        </section>
        <section class="images-posts-cont">
          <div class="images">
            <h2>related images</h2>
          </div>
          <div class="posts">
            <h2>related posts</h2>
          </div>
        </section>
        <footer class="footer">
          <h2>footer</h2>
        </footer>
      </div>
    </body>


问:
413 Request Entity Too Large
I use nginX/1.6 and laravel when i posted data to server i get this error 413 Request Entity Too Large. i tried many solutions as bellow

```<code>1- set client_max_body_size 100m; in server and location and http in nginx.conf.
2- set upload_max_filesize = 100m in php.ini
3- set post_max_size = 100m in php.ini
</code>```

After restarting php5-fpm and nginx the problem still not solved

答:
I am using Docker and PHP 7.4 and I faced this issue too.

Just added a line to the file *.conf inside docker/php74/ directory.

```<code>server {
    client_max_body_size 100M;
    ...
}
</code>```

Title: 413 Request Entity Too Large

Body:
I use nginX/1.6 and laravel when i posted data to server i get this error 413 Request Entity Too Large. i tried many solutions as bellow

1- set client_max_body_size 100m; in server and location and http in nginx.conf.
2- set upload_max_filesize = 100m in php.ini
3- set post_max_size = 100m in php.ini

After restarting php5-fpm and nginx the problem still not solved

Body:
I am using Docker and PHP 7.4 and I faced this issue too.

Just added a line to the file *.conf inside docker/php74/ directory.

server {
    client_max_body_size 100M;
    ...
}


问:
Unreal Engine C++ Spawn Actor Bug
I have a simple Puzzle Game.

It is a combination of multiple simple games. Since those games are rotated during the game, everything is spawned dynamically.
I have a problem with SpawnActor.

There is a class called XGame(AActor) spawned by level manager(APawn) . It is responsible for spawning actors for this specific X game.

XGame.cpp

```<code>const FVector ActorLocation = GetActorLocation();

const FVector StickLocation = FVector(0, 0, 0) + ActorLocation;
const FVector BallLocation = FVector(0, 100, 0) + ActorLocation;
const FVector CircleLocation = FVector(0, 200, 0) + ActorLocation;

UWorld* World = GetWorld();

AXStick* Stick = World->SpawnActor<AXStick>(StickLocation, FRotator(0, 0, 0));
AXBall* Ball = World->SpawnActor<AXBall>(BallLocation, FRotator(0, 0, 0));
AXCircle* Ball = World->SpawnActor<AXCircle>(CircleLocation, FRotator(0, 0, 0));
</code>```

The problem is, everytime I spawn an actor its X coordinate is increased by 68. (I don't know why 68)

For instance;

stick is spawned at 0, 0, 0

ball is spawned at 68, 100, 0

circle is spawned at 136, 200, 0

all of them are ACharacter

I would be really appreciated if anyone can help

答: I manage to get it working correctly by changing base class of Stick, Ball and Circle to AActor. Because of the fact that Character classes automatically generates a capsule component. They were colliding and spawned characters are moved by 68 each time (default capsule movement radius of character is 34.0).</p>

Title: Unreal Engine C++ Spawn Actor Bug

Body:
I have a simple Puzzle Game.

It is a combination of multiple simple games. Since those games are rotated during the game, everything is spawned dynamically.
I have a problem with SpawnActor.

There is a class called XGame(AActor) spawned by level manager(APawn) . It is responsible for spawning actors for this specific X game.

XGame.cpp

const FVector ActorLocation = GetActorLocation();

const FVector StickLocation = FVector(0, 0, 0) + ActorLocation;
const FVector BallLocation = FVector(0, 100, 0) + ActorLocation;
const FVector CircleLocation = FVector(0, 200, 0) + ActorLocation;

UWorld* World = GetWorld();

AXStick* Stick = World->SpawnActor<AXStick>(StickLocation, FRotator(0, 0, 0));
AXBall* Ball = World->SpawnActor<AXBall>(BallLocation, FRotator(0, 0, 0));
AXCircle* Ball = World->SpawnActor<AXCircle>(CircleLocation, FRotator(0, 0, 0));

The problem is, everytime I spawn an actor its X coordinate is increased by 68. (I don't know why 68)

For instance;

stick is spawned at 0, 0, 0

ball is spawned at 68, 100, 0

circle is spawned at 136, 200, 0

all of them are ACharacter

I would be really appreciated if anyone can help


问:
Switch product image on hover on WooCommerce archive page
Is there a way (maybe via functions.php) to change the product-image in woocommerce shops (archive page) on hover with the first attached gallery image of the product? I cannot find how to target both. I guess it must be sth like this:

```<code>add_action( 'woocommerce_shop_loop_item', 'change_image_on_hover', 10 );
function change_image_on_hover() {
     $product->get_gallery_image_ids();
     print 'woocommerce_gallery_image';
}
</code>```

答:
CSS can detect when the user is hovering over an image. Is it possible for you to load both images, and then just turn one off and one on when hover is detected?

The code for that would look like this:

HTML:

```<code><a id="home">
<img class="image_on" src="images/productImage.png"" />
<img class="image_off" src="images/galleryImage.png" />
</a>
</code>```

CSS:

```<code>.image_off, #home:hover .image_on{
     display:none
}
.image_on, #home:hover .image_off{
     display:block
}
</code>```

If this doesn't work, check out this thread for other solution using js/jquery

Body:
Is there a way (maybe via functions.php) to change the product-image in woocommerce shops (archive page) on hover with the first attached gallery image of the product? I cannot find how to target both. I guess it must be sth like this:

add_action( 'woocommerce_shop_loop_item', 'change_image_on_hover', 10 );
function change_image_on_hover() {
     $product->get_gallery_image_ids();
     print 'woocommerce_gallery_image';
}

Body:
CSS can detect when the user is hovering over an image. Is it possible for you to load both images, and then just turn one off and one on when hover is detected?

The code for that would look like this:

HTML:

<a id="home">
<img class="image_on" src="images/productImage.png"" />
<img class="image_off" src="images/galleryImage.png" />
</a>

CSS:

.image_off, #home:hover .image_on{
     display:none
}
.image_on, #home:hover .image_off{
     display:block
}

If this doesn't work, check out this thread for other solution using js/jquery


问:
CUDA kernel runs faster the second time it is run - why?
I am programming my first real application in CUDA, and I have come to the point where I need to know how long executions of kernels take. However, as said in the title, I do not understand why, in applications that run a kernel more than once, the time taken for the second launch of the kernel is much much shorter than the time taken for the first.

For example, in the code below:

```<code>#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <chrono>
#include <iostream>
#include <stdio.h>

void runCuda(unsigned int size);

__global__ void addKernel(const int arraySize)
{
    1 + 1;
}

void doStuff(int arraySize)
{
    auto t1 = std::chrono::high_resolution_clock::now();
    addKernel <<<(arraySize + 31) / 32, 32 >>> (arraySize);
    cudaDeviceSynchronize();
    auto t2 = std::chrono::high_resolution_clock::now();

    std::cout << "Duration: " << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << '\n';
    cudaDeviceReset();
}

int main()
{
    doStuff(1e6);
    doStuff(1e6);

    return 0;
}
</code>```

the kernel only does some basic addition, and it is called one million times. The output of the program above is usually something like:

```<code>Duration: 1072
Duration: 97
</code>```

the two numbers change, but remain consistently around 1000 and 100. The fact that the same kernel runs so much faster the second time makes no sense to me.

答: You will find that on your first run almost all of the extra time is spent on your first cudaMalloc(). This is a initialization where it is determining device and swap and memory conditions that can only partly be mitigated.</p>

Body:
I am programming my first real application in CUDA, and I have come to the point where I need to know how long executions of kernels take. However, as said in the title, I do not understand why, in applications that run a kernel more than once, the time taken for the second launch of the kernel is much much shorter than the time taken for the first.

For example, in the code below:

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include <chrono>
#include <iostream>
#include <stdio.h>

void runCuda(unsigned int size);

__global__ void addKernel(const int arraySize)
{
    1 + 1;
}

void doStuff(int arraySize)
{
    auto t1 = std::chrono::high_resolution_clock::now();
    addKernel <<<(arraySize + 31) / 32, 32 >>> (arraySize);
    cudaDeviceSynchronize();
    auto t2 = std::chrono::high_resolution_clock::now();

    std::cout << "Duration: " << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << '\n';
    cudaDeviceReset();
}

int main()
{
    doStuff(1e6);
    doStuff(1e6);

    return 0;
}

the kernel only does some basic addition, and it is called one million times. The output of the program above is usually something like:

Duration: 1072
Duration: 97

the two numbers change, but remain consistently around 1000 and 100. The fact that the same kernel runs so much faster the second time makes no sense to me.


问:
Validating elements of a 2D array
My code for making sure an element isn't over 100 or less than 0 is:

boolean test = true;
for (int i = 0; i < inArray.length; i++) {
    for (int j = 0; j < inArray[0].length; j++) {
        if (inArray[i][j] <= 1 && inArray[i][j] >= 100) {
            test = false;
        }
    }
}
return test;
```
<p>Except no matter what the input is the answer is always <code>true</code></p>
<p>My input <code>array</code> is</p>
```{12, 1331, 23, 5, 1, 3},
{22, 23, 231, 21312, 1, 3},
{23, 31, 343, 3432, 1, 3},
{42, 12, 5454, 1212, 3, 9}
```

test should = false if I input this no?

College rules mean I cannot use break; or return anywhere other than the end of the sub module.

答:
You have three problems here, two of which are critical. First, if you want to iterate over each subarray, test its length, not the length of array[0] every time. And second, integers cannot be less than 2 and over 99, so your conditional (inArray[i][j] <= 1 &&  inArray[i][j] >= 100) is never going to fire.

However, there's more at play here: if your test is purely to see whether your 2d array is valid, don't do more work than necessary. You can literally stop once you find a single bad element. Now, we could do that by adding a check to your for conditionals. E.g. we can rename your variable to valid (because you should name variables after what they represent), and then we can update your outer loop to for(int i=0; valid && i < arr.length; i++) { ... } with the corresponding valid && ... in the inner loop, too, but we're not going to. This code "does a thing" (namely it "tests for element validity" for any array-of-arrays), and code that "does a thing" should be in its own method, with a method name that describes what it does. And this makes "not doing any of the work we don't need to do" much, much easier: we just exit the function when we know we've done enough work to produce an answer.

So let's do that:

// 1st fix: this code "does soemthing". Do that as a method.
public boolean testForValidContent(int[][] arr) {
  // We don't need a variable to track things: because we're
  // returning a value, we can simply return the right value
  // at the moment we return.

  for(int i = 0; i < arr.length; i++) {
    for(int j = 0; j < arr[i].length; j++) { // 2nd fix: check the right array's length
      if(arri][j] <= 1 || arr[i][j] >= 100) { // 3th fix: OR, not AND

        // At this point we know the array is not valid, so there
        // is no point in running even a single thing more:
        return false;

      }
    }
  }

  // We checked the entire array, and everything's valid:
  return true;
}
```

Title: Validating elements of a 2D array

Body:
My code for making sure an element isn't over 100 or less than 0 is:

boolean test = true;
for (int i = 0; i < inArray.length; i++) {
    for (int j = 0; j < inArray[0].length; j++) {
        if (inArray[i][j] <= 1 && inArray[i][j] >= 100) {
            test = false;
        }
    }
}
return test;

Except no matter what the input is the answer is always true

My input array is

{12, 1331, 23, 5, 1, 3},
{22, 23, 231, 21312, 1, 3},
{23, 31, 343, 3432, 1, 3},
{42, 12, 5454, 1212, 3, 9}

test should = false if I input this no?

College rules mean I cannot use break; or return anywhere other than the end of the sub module.


问:
How to prevent a prop from being passed to the extended component?
My question is similar to this one, however I need to type a component. I have tried a multiple ways, but still getting errors.

I am not sure if the problem is in my understanding, or am I doing something wrong? Here is what I tried:

First approach works correctly but throws warning: React does not recognize the isActive prop on a DOM element

Second and Third throws TS error: No overload matches this call.

```<code>import * as React from "react";
import TextareaAutosize, { TextareaAutosizeProps } from "react-textarea-autosize";
import styled from "styled-components";

interface Props {
  isActive?: boolean;
}

interface ExtendedProps extends Props, TextareaAutosizeProps {}

const FirstTry = styled(TextareaAutosize)<Props>`
  color: ${({ isActive }) => (isActive ? "red" : "blue")};
`;

const SecondTry = styled(({ isActive, ...rest }: ExtendedProps) => (
  <TextareaAutosize {...rest} />
))`
  color: ${({ isActive }) => (isActive ? "red" : "blue")};
`;

const ThirdTry = ({ isActive, ...rest }: ExtendedProps) => {
  const Foo = styled(TextareaAutosize)<TextareaAutosizeProps>`
    color: ${isActive ? "red" : "blue"};
  `;

  return <Foo {...rest} />;
};

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <FirstTry isActive minRows={3} />
      {/* FirstTry - Warning: React does not recognize the `isActive` prop on a DOM element */}
      <SecondTry isActive minRows={3} />
      <ThirdTry isActive minRows={3} />
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

</code>```

Link to sandbox:
https://codesandbox.io/s/zen-cdn-lp8pl?file=/src/App.tsx

答:
Your second approach looks good except for one small thing that causes the error: ref prop of TextareaAutosizeProps collides with ref prop of your styled component.

ref (and key for that matter) is a tricky "prop" - you pass it to a component just like any other props yet it does not appear in your props (if you log them for example), it is handled differently.

If you look at your second example:

```<code>const SecondTry = styled(({ isActive, ...rest }: ExtendedProps) => (
  <TextareaAutosize {...rest} />
))`
  color: ${({ isActive }) => (isActive ? "red" : "blue")};
`;
</code>```

You can see that you are not styling TextareaAutosize but the anonymous function component ({ isActive, ...rest }: ExtendedProps) => .... If you pass ref to your SecondTry component it will not appear in your props ({ isActive, ...rest }: ExtendedProps). Yet when extending TextareaAutosizeProps you are also saying that there will be such a prop and it will be of type HTMLTextAreaElement.

So I can think of two solutions depending on your needs:

If you don't need the ref prop on your SecondTry you can just omit it from your props:

```<code>interface ExtendedProps extends Props, Omit<TextareaAutosizeProps, 'ref'> {}
</code>```

If you need it though you will need to use React.forwardRef function (see more about that here).

Body:
My question is similar to this one, however I need to type a component. I have tried a multiple ways, but still getting errors.

I am not sure if the problem is in my understanding, or am I doing something wrong? Here is what I tried:

First approach works correctly but throws warning: React does not recognize the isActive prop on a DOM element

Second and Third throws TS error: No overload matches this call.

import * as React from "react";
import TextareaAutosize, { TextareaAutosizeProps } from "react-textarea-autosize";
import styled from "styled-components";

interface Props {
  isActive?: boolean;
}

interface ExtendedProps extends Props, TextareaAutosizeProps {}

const FirstTry = styled(TextareaAutosize)<Props>`
  color: ${({ isActive }) => (isActive ? "red" : "blue")};
`;

const SecondTry = styled(({ isActive, ...rest }: ExtendedProps) => (
  <TextareaAutosize {...rest} />
))`
  color: ${({ isActive }) => (isActive ? "red" : "blue")};
`;

const ThirdTry = ({ isActive, ...rest }: ExtendedProps) => {
  const Foo = styled(TextareaAutosize)<TextareaAutosizeProps>`
    color: ${isActive ? "red" : "blue"};
  `;

  return <Foo {...rest} />;
};

export default function App() {
  return (

Hello CodeSandbox

      <FirstTry isActive minRows={3} />
      {/* FirstTry - Warning: React does not recognize the `isActive` prop on a DOM element */}
      <SecondTry isActive minRows={3} />
      <ThirdTry isActive minRows={3} />

Start editing to see some magic happen!

  );
}

Link to sandbox:
https://codesandbox.io/s/zen-cdn-lp8pl?file=/src/App.tsx

Body:
Your second approach looks good except for one small thing that causes the error: ref prop of TextareaAutosizeProps collides with ref prop of your styled component.

ref (and key for that matter) is a tricky "prop" - you pass it to a component just like any other props yet it does not appear in your props (if you log them for example), it is handled differently.

If you look at your second example:

const SecondTry = styled(({ isActive, ...rest }: ExtendedProps) => (
  <TextareaAutosize {...rest} />
))`
  color: ${({ isActive }) => (isActive ? "red" : "blue")};
`;

You can see that you are not styling TextareaAutosize but the anonymous function component ({ isActive, ...rest }: ExtendedProps) => .... If you pass ref to your SecondTry component it will not appear in your props ({ isActive, ...rest }: ExtendedProps). Yet when extending TextareaAutosizeProps you are also saying that there will be such a prop and it will be of type HTMLTextAreaElement.

So I can think of two solutions depending on your needs:

If you don't need the ref prop on your SecondTry you can just omit it from your props:

interface ExtendedProps extends Props, Omit<TextareaAutosizeProps, 'ref'> {}

If you need it though you will need to use React.forwardRef function (see more about that here).


问:
TFLite model overflows on GPU, ok on CPU. What are the differences internally?
On Android, I have a model that runs fine on CPU, but overflows when switching to GPU delegate ('Infinity' in the results). If I rescale the input, I can eliminate the overflow, so it seems an issue of different internal range/precision between CPU and GPU. I was under the impression that both CPU and GPU use by default 32-bit float, so the results should be identical. Does anyone know the internals of TFLite enough to provide some insight?</p>

答:
Regarding floating point precision, the TFLite GPU delegate on Android can run in two modes, which you can choose with the following method in the Options class. (copied from here)

    /**
     * Sets whether precision loss is allowed.
     *
     * @param precisionLossAllowed When `true` (default), the GPU may quantify tensors, downcast
     *     values, process in FP16. When `false`, computations are carried out in 32-bit floating
     *     point.
     */
    public Options setPrecisionLossAllowed(boolean precisionLossAllowed) {
      this.precisionLossAllowed = precisionLossAllowed;
      return this;
    }
```

<p>Since the default value for this <code>precisionLossAllowed</code> option is <code>true</code>, your model will run in FP16 mode when using GPU by default. If you want to force running in FP32 mode as in CPU, you should explicitly set this option to <code>false</code> when creating the delegate.</p>

<pre class="lang-java prettyprint-override"><code>GpuDelegate.Options gpuOptions = new GpuDelegate.Options();
gpuOptions.setPrecisionLossAllowed(false);
GpuDelegate gpuDelegate = new GpuDelegate(gpuOptions);

Interpreter.Options interpreterOptions = new Interpreter.Options();
interpreterOptions.addDelegate(gpuDelegate);
Interpreter interpreter = new Interpreter(tflite_model_file, interpreterOptions);
</code>```

This should give you the same result as in CPU mode, but result in slower execution compared to FP16 mode.

Body:
Regarding floating point precision, the TFLite GPU delegate on Android can run in two modes, which you can choose with the following method in the Options class. (copied from here)

    /**
     * Sets whether precision loss is allowed.
     *
     * @param precisionLossAllowed When `true` (default), the GPU may quantify tensors, downcast
     *     values, process in FP16. When `false`, computations are carried out in 32-bit floating
     *     point.
     */
    public Options setPrecisionLossAllowed(boolean precisionLossAllowed) {
      this.precisionLossAllowed = precisionLossAllowed;
      return this;
    }

Since the default value for this precisionLossAllowed option is true, your model will run in FP16 mode when using GPU by default. If you want to force running in FP32 mode as in CPU, you should explicitly set this option to false when creating the delegate.

GpuDelegate.Options gpuOptions = new GpuDelegate.Options();
gpuOptions.setPrecisionLossAllowed(false);
GpuDelegate gpuDelegate = new GpuDelegate(gpuOptions);

Interpreter.Options interpreterOptions = new Interpreter.Options();
interpreterOptions.addDelegate(gpuDelegate);
Interpreter interpreter = new Interpreter(tflite_model_file, interpreterOptions);

This should give you the same result as in CPU mode, but result in slower execution compared to FP16 mode.


问:
LinkedIn Video Analytics API - timeRange invalid
Using the linkedIn Video Analytics API, I want to gather analytics about my video post per day.

My request:

```<code>https://api.linkedin.com/v2/videoAnalytics?q=entity&entity=urn:li:ugcPost:6662300354706755584&type=VIEWER&timeRange=(start:1588416100,end:1590624000)&aggregation=DAY
</code>```

However, I keep receiving the following error:

```<code>{"message":"Parameter 'timeRange' is invalid","status":400}
</code>```

I tried changing the timeRange from miliseconds to epoch time, but that did not make a difference. Please, can anyone help to solve this issue here?

Thanks in advance.

答:
You could split the timeRange in two different query string params:

So, instead of:

```<code>&timeRange=(start:1588416100,end:1590624000)&...
</code>```

You could use:

```<code>&timeRange.start=1588416100&timeRange.end:1590624000&...
</code>```

So the final url could be:

```<code>https://api.linkedin.com/v2/videoAnalytics?q=entity&entity=urn:li:ugcPost:6662300354706755584&type=VIEWER&timeRange.start:1588416100&timeRange.end:1590624000&aggregation=DAY
</code>```

I've tried with success. Hope this works for you

NB: Remember that timestamp is in milliseconds

Body:
Using the linkedIn Video Analytics API, I want to gather analytics about my video post per day.

My request:

https://api.linkedin.com/v2/videoAnalytics?q=entity&entity=urn:li:ugcPost:6662300354706755584&type=VIEWER&timeRange=(start:1588416100,end:1590624000)&aggregation=DAY

However, I keep receiving the following error:

{"message":"Parameter 'timeRange' is invalid","status":400}

I tried changing the timeRange from miliseconds to epoch time, but that did not make a difference. Please, can anyone help to solve this issue here?

Thanks in advance.

Body:
You could split the timeRange in two different query string params:

So, instead of:

&timeRange=(start:1588416100,end:1590624000)&...

You could use:

&timeRange.start=1588416100&timeRange.end:1590624000&...

So the final url could be:

https://api.linkedin.com/v2/videoAnalytics?q=entity&entity=urn:li:ugcPost:6662300354706755584&type=VIEWER&timeRange.start:1588416100&timeRange.end:1590624000&aggregation=DAY

I've tried with success. Hope this works for you

NB: Remember that timestamp is in milliseconds


问:
how to install pip on windows
I've tried installing pip on windows using instructions from https://www.liquidweb.com/kb/install-pip-windows/, (which I've listed below), but when I run pip -V, I keep getting 'pip' is not recognized as an internal or external command,
operable program or batch file. Does anyone know what to do?

These were the instructions I followed:

Download get-pip.py to a folder on your computer. (right clicked and selected save link as...)

Open a command prompt and navigate to the folder containing get-pip.py.

Run the following command:
python get-pip.py

Pip is now installed!

You can verify that Pip was installed correctly by opening a command prompt and entering the following command:

pip -V

答:
In Windows 10, you need to add pip to the PATH.

This post should solve your issue: 'pip' is not recognized as an internal or external command

Title: how to install pip on windows


问:
InputMismatchError while scanning number
While trying to read a number using below code InputMismatchError is generated:

```<code>Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {

    long number = sc.nextLong(); // Error here

    if (number % 2 == 0 && number != 0) {
        System.out.println("even");
    } else if (number % 2 != 0 && number != 0) {
        System.out.println("odd");
    } else if (number == 0) {
        System.out.println("");
    }
}
</code>```

I don't understand where a mistake. Eclipse compiled program without errors.

Following is the input from console used

1234.5

答:
If the input might have some non-integers with the values, you should check if the next value is a long. If not, ignore it:

```<code>while (sc.hasNext()) {
    // Check if next is a long
    if (sc.hasNextLong()) {
        long number = sc.nextLong();

        if (number == 0) {
            System.out.println("");
        }
        else if (number % 2 == 0) {
            System.out.println("even");
        }
        else {
            System.out.println("odd");
        }
    }
    else {
        // Not a long, consume rest of line.
        // You might need to change this to sc.next() depending on requirements
        sc.nextLine();
    }
}
</code>```

Body:
While trying to read a number using below code InputMismatchError is generated:

Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {

    long number = sc.nextLong(); // Error here

    if (number % 2 == 0 && number != 0) {
        System.out.println("even");
    } else if (number % 2 != 0 && number != 0) {
        System.out.println("odd");
    } else if (number == 0) {
        System.out.println("");
    }
}

I don't understand where a mistake. Eclipse compiled program without errors.

Following is the input from console used

1234.5

Body:
If the input might have some non-integers with the values, you should check if the next value is a long. If not, ignore it:

while (sc.hasNext()) {
    // Check if next is a long
    if (sc.hasNextLong()) {
        long number = sc.nextLong();

        if (number == 0) {
            System.out.println("");
        }
        else if (number % 2 == 0) {
            System.out.println("even");
        }
        else {
            System.out.println("odd");
        }
    }
    else {
        // Not a long, consume rest of line.
        // You might need to change this to sc.next() depending on requirements
        sc.nextLine();
    }
}


问:
Laravel route middleware can:view not being called, getting 403 forbidden error
I'm using Laravel 7. I have created UserPolicy with all those resource methods.

In my route/web.php I have added another route to the UserController custom method ie.

```<code>Route::get('user/somefunction', 'UserController@somefunction')->name('user.somefunction')->middleware('can:view');
</code>```

However when I call user/somefunction using my brower, I got 403 forbidden.

I have added a log debug in my UserPolicy view function, it's not getting called at all.

Please advise.

答:
To answer my own question, has to add the model name to middleware. ie</p>

```<code>Route::get('user/somefunction', 'UserController@somefunction')->name('user.somefunction')->middleware('can:view, App\User');
</code>```

Body:
I'm using Laravel 7. I have created UserPolicy with all those resource methods.

In my route/web.php I have added another route to the UserController custom method ie.

Route::get('user/somefunction', 'UserController@somefunction')->name('user.somefunction')->middleware('can:view');

However when I call user/somefunction using my brower, I got 403 forbidden.

I have added a log debug in my UserPolicy view function, it's not getting called at all.

Please advise.

Body:
To answer my own question, has to add the model name to middleware. ie

Route::get('user/somefunction', 'UserController@somefunction')->name('user.somefunction')->middleware('can:view, App\User');


问:
django/innodb -- problem with old sessions and transactions
We just switched our MySQL database from MyIsam to Innodb, and we are seeing an odd issue arise in Django. Whenever we make a database transaction, the existing sessions do not pick it up...ever. We can see the new record in the database from a mysql terminal, but the existing django sessions (ie a shell that was already open), would not register the change. For example:

Shell 1:

```<code>>>> my_obj = MyObj.objects.create(foo="bar")
>>> my_obj.pk
1
</code>```

Shell 2 (was open before the above)

```<code>>>> my_obj = MyObj.objects.filter(pk=1)
[]
</code>```

Shell 3 (MySQL):

```<code>mysql> select id from myapp_my_obj where id = 1;
id
1
</code>```

Does anyone know why this might be happening?

EDIT: To clarify, Shell 2 was opened before Shell 1, then I make the create Shell 1, then I try to view the object that I created in Shell 2.

EDIT2: The big picture is that I have a celery task that is being passed the primary key from the object that is created. When I was using MyISAM, it found it every time, and now it throws ObjectDoesNotExist, even though I can see that the object is created in the database.

答:
Your create() command commits the transaction for the current shell, but doesn't do anything to the transaction in the second shell.

https://docs.djangoproject.com/en/dev/topics/db/transactions/

Your second thread that can't see what's done in the first because it is in a transaction of its own. Transactions isolate the database so that when a transaction is committed, everything happens at a single point in time, including select statements. This is the A in ACID. Try running

```<code>from django.db import transaction; transaction.commit()
</code>```

in the second shell. That should commit the current transaction and start a new one. You can also use transaction.rollback() to acheive the same thing if you haven't modified anything in the db in the current shell.

Edit Edit:

You may need to grab your specific db connection to make this work. Try this:

```<code>import django.db
django.db.connection._commit()
</code>```

More information about this problem here:

http://groups.google.com/group/django-users/msg/55fa3724d2754013

The relevant bit is:

```
If you want script1.py (using an InnoDB table) to see committed updates from
other transactions you can change the transaction isolation level like so:

from django.db import connection
connection.cursor().execute('set transaction isolation level read
committed')

Alternatively you can enable the database's version of auto-commit, which
"commits" queries as well as updates, so that each new query by script1 will
be in its own transaction:

connection.cursor().execute('set autocommit=1')
Either one allows script1 to see script2's updates.
```

So, the tl;dr is that you need to set your InnoDB transaction isolation to READ-COMMITTED.

Body:
We just switched our MySQL database from MyIsam to Innodb, and we are seeing an odd issue arise in Django. Whenever we make a database transaction, the existing sessions do not pick it up...ever. We can see the new record in the database from a mysql terminal, but the existing django sessions (ie a shell that was already open), would not register the change. For example:

Shell 1:

>>> my_obj = MyObj.objects.create(foo="bar")
>>> my_obj.pk
1

Shell 2 (was open before the above)

>>> my_obj = MyObj.objects.filter(pk=1)
[]

Shell 3 (MySQL):

mysql> select id from myapp_my_obj where id = 1;
id
1

Does anyone know why this might be happening?

EDIT: To clarify, Shell 2 was opened before Shell 1, then I make the create Shell 1, then I try to view the object that I created in Shell 2.

EDIT2: The big picture is that I have a celery task that is being passed the primary key from the object that is created. When I was using MyISAM, it found it every time, and now it throws ObjectDoesNotExist, even though I can see that the object is created in the database.

Body:
Your create() command commits the transaction for the current shell, but doesn't do anything to the transaction in the second shell.

https://docs.djangoproject.com/en/dev/topics/db/transactions/

Your second thread that can't see what's done in the first because it is in a transaction of its own. Transactions isolate the database so that when a transaction is committed, everything happens at a single point in time, including select statements. This is the A in ACID. Try running

from django.db import transaction; transaction.commit()

in the second shell. That should commit the current transaction and start a new one. You can also use transaction.rollback() to acheive the same thing if you haven't modified anything in the db in the current shell.

Edit Edit:

You may need to grab your specific db connection to make this work. Try this:

import django.db
django.db.connection._commit()

More information about this problem here:

http://groups.google.com/group/django-users/msg/55fa3724d2754013

The relevant bit is:

If you want script1.py (using an InnoDB table) to see committed updates from
other transactions you can change the transaction isolation level like so:

from django.db import connection
connection.cursor().execute('set transaction isolation level read
committed')

Alternatively you can enable the database's version of auto-commit, which
"commits" queries as well as updates, so that each new query by script1 will
be in its own transaction:

connection.cursor().execute('set autocommit=1')
Either one allows script1 to see script2's updates.

So, the tl;dr is that you need to set your InnoDB transaction isolation to READ-COMMITTED.


问:
How to consume Google map web services API in my flutter APP
I am new in Flutter, and I have pretty good knowledge of using Google maps APIs for native Android Apps. However, in my flutter app, I need Google Places search Auto-complete. I came across a plugin called google_maps_webservice where it consumes google maps APIs such as directions, places and geocoding using Google web services. My question is having low understanding and experiences in setting up web services for google maps API, how I can use the plugin in my flutter app? For example, if I had to use places API in android I would have enabled Goole Places SDK in cloud console and generate an API restricting for Android App. But for a flutter, both Android and iOS are going to use the same services from a web API call. what should I do? And right now I have no backend knowledge to set up a domain to use while creating the API from the console.

答:
You can import the google_maps_webservices package

```<code>import 'package:google_maps_webservice/places.dart';
</code>```

and use it in your code:

```<code>final places = GoogleMapsPlaces('<Your-API-Key>');
final response = await places.autocomplete('<What-you-are-searching-for>');

if (response.isOkay) {
  for (Prediction prediction in response.predictions) {
    print(prediction.description);
   }
}
</code>```

Some caveats:

 1. Ensure that you are using the Web API key

 2. Ensure to activate the Google Places SDK in Cloud Console.

 3. To avoid getting an OVER_QUERY_LIMIT status message, ensure that you are using a billing account.

Body:
You can import the google_maps_webservices package

import 'package:google_maps_webservice/places.dart';

and use it in your code:

final places = GoogleMapsPlaces('<Your-API-Key>');
final response = await places.autocomplete('<What-you-are-searching-for>');

if (response.isOkay) {
  for (Prediction prediction in response.predictions) {
    print(prediction.description);
   }
}

Some caveats:

 1. Ensure that you are using the Web API key

 2. Ensure to activate the Google Places SDK in Cloud Console.

 3. To avoid getting an OVER_QUERY_LIMIT status message, ensure that you are using a billing account.


问:
Another way to change the name of a table in Laravel using App\Models\XXX name
Simple question...
I can change the name of a table in a query like this:

```<code>$users = DB::table('users AS u')->select('name');
</code>```

Can i do it in some way like this?

```<code>$users = App\Models\Users::select('name')->get();
</code>```

答:
This's called table "Alias" and it's meaningless to set alias in the model, simply because you don't need to define any table name when you're using Laravel ORM.

But in query builder you can set aliases specially when you're trying to join same table multiple times:

```<code> DB::table('table_name AS alias_name');
</code>```

or in join

```<code>$query->join('table_name as alias_name', function ($builder) use ($value) {}
</code>```

Body:
Simple question...
I can change the name of a table in a query like this:

$users = DB::table('users AS u')->select('name');

Can i do it in some way like this?

$users = App\Models\Users::select('name')->get();

Body:
This's called table "Alias" and it's meaningless to set alias in the model, simply because you don't need to define any table name when you're using Laravel ORM.

But in query builder you can set aliases specially when you're trying to join same table multiple times:

 DB::table('table_name AS alias_name');

or in join

$query->join('table_name as alias_name', function ($builder) use ($value) {}


问:
How tell PHPStorm debugger, that my project has document root other than project root
I'am trying to set up PHPStorm with xdebug. Everyting launches fine, but breakpoints just do not work and have  "x" symbol on them.

I'm using openserver with PHP 5.4 and editing files directly on the local web server, so no file mapping is necessary.

I think, that my problem is that web server root is located below the project root directory (for security reasons) and PHPStorm does not that.

Project root: C:\OpenServer\domains\mysite

Web server root (configured in nginx): C:\OpenServer\domains\mysite\httpdocs

How do I tell PHPStorm, that the index.php that webserver runs is actually C:\OpenServer\domains\mysite\httpdocs\index.php, but not C:\OpenServer\domains\mysite\index.php?

答:
In my case, I tried these steps:

step 1: uncheck these two options at xdebug section

step 2: copy & paste the directory of your project at /xampp/htdocs/{your-project}


问:
Android - Unknown attribute style on a fragment tag
Can someone please explain to me why I am getting this warning in Android Studio 1.1.0:

Unknown attribute style

Full warning: The inspection highlights unknown XML attributes in Android resource files and AndroidManifest.xml

Here is the code snippet:

```<code><fragment
    android:id="@+id/frag_logo"
    tools:layout="@layout/fragment_logo"
    style="@style/FragmentLogo"/>
</code>```

The warning occurs on the style attribute.

I am using gradle and android build tools 21.1.2

答:
Activity and Fragment supports android:theme. So please try this:</p>

```<code>android:theme="@style/FragmentLogo"
</code>```

Body:
Can someone please explain to me why I am getting this warning in Android Studio 1.1.0:

Unknown attribute style

Full warning: The inspection highlights unknown XML attributes in Android resource files and AndroidManifest.xml

Here is the code snippet:

<fragment
    android:id="@+id/frag_logo"
    tools:layout="@layout/fragment_logo"
    style="@style/FragmentLogo"/>

The warning occurs on the style attribute.

I am using gradle and android build tools 21.1.2

Body:
Activity and Fragment supports android:theme. So please try this:

android:theme="@style/FragmentLogo"


问:
Docusign add note in a template and prefill it before sending the envelope
i need to enter the signer address in a template docusign as a note field and prefill it when creating the envelope and before sending it. Thanks for help.

there is my php code:

```<code>$envelope_definition = new EnvelopeDefinition([
    'status' => 'sent', 'template_id' => $this->template_id
]);
# Create the template role elements to connect the signer and cc recipients
# to the template

$signer = new TemplateRole([
    'email'             => $args['signer_email'],
    'name'              => $args['signer_name'],
    'role_name'         => 'signer'
]);
</code>```

$address_note = new Note(['selected' => 'true', 'tab_label' => 'signer_address', 'value' => $args['signer_address']]);
$signer->setTabs(new Tabs([$address_note]));
$envelope_definition->setTemplateRoles([$signer]);

and there is the configuration of note field in the dashboard docusign: note field

But the problem is when signing the document i can't see the signer address

When i try to find the tabs in the apropriate template using this php code :

```<code># create the envelope definition with the template_id
    $envelope_definition = new EnvelopeDefinition([
        'status' => 'sent', 'template_id' => $this->template_id
    ]);
    # Create the template role elements to connect the signer and cc recipients
    # to the template

    $signer = new TemplateRole([
        'email'             => $args['signer_email'],
        'name'              => $args['signer_name'],
        'role_name'         => 'signer'
    ]);

    dd($signer->getTabs());
</code>```

i got null as result.

答:
Before you make your request, check to ensure that your template contains the appropriate note field that you want to prepopulate. You can do so by making a GET request to /templates.

```<code>GET https://demo.docusign.net/restapi/v2.1/accounts/{account_ID}/templates/{template_ID}?include=recipients,tabs
</code>```

Now, To prepopulate a note field with the physical mailing address for a particular recipient, you can make a POST request to /envelopes. You will find the tabLabel from the previous step.

```<code>{
    "status": "sent",
    "templateId": "00df08bf-xxxx-xxxx-xxxx-ecaa2360c121",
    "templateRoles": [
        {
            "email": "test@test.com",
            "name": "ABC",
            "roleName": "signer",
            "routingOrder": "1",
            "tabs": {
                "noteTabs": [
                    {
                        "selected": "true",
                        "tabLabel": "userAddress",
                        "value": "theUsersAddressGoesHere"
                    }
                ]
            }
        },
        {
            "email": "test2@test.com",
            "name": "EFG",
            "roleName": "cc",
            "routingOrder": "2"
        }
    ]
}
</code>```

If you are unable to see the value of the note field when signing, you may need to change the size of the bounding box. You can do this either by editing the template in the UI or adding X/Y properties to your request.

Body:
i need to enter the signer address in a template docusign as a note field and prefill it when creating the envelope and before sending it. Thanks for help.

there is my php code:

$envelope_definition = new EnvelopeDefinition([
    'status' => 'sent', 'template_id' => $this->template_id
]);
# Create the template role elements to connect the signer and cc recipients
# to the template

$signer = new TemplateRole([
    'email'             => $args['signer_email'],
    'name'              => $args['signer_name'],
    'role_name'         => 'signer'
]);

$address_note = new Note(['selected' => 'true', 'tab_label' => 'signer_address', 'value' => $args['signer_address']]);
$signer->setTabs(new Tabs([$address_note]));
$envelope_definition->setTemplateRoles([$signer]);

and there is the configuration of note field in the dashboard docusign: note field

But the problem is when signing the document i can't see the signer address

When i try to find the tabs in the apropriate template using this php code :

# create the envelope definition with the template_id
    $envelope_definition = new EnvelopeDefinition([
        'status' => 'sent', 'template_id' => $this->template_id
    ]);
    # Create the template role elements to connect the signer and cc recipients
    # to the template

    $signer = new TemplateRole([
        'email'             => $args['signer_email'],
        'name'              => $args['signer_name'],
        'role_name'         => 'signer'
    ]);

    dd($signer->getTabs());

i got null as result.

Body:
Before you make your request, check to ensure that your template contains the appropriate note field that you want to prepopulate. You can do so by making a GET request to /templates.

GET https://demo.docusign.net/restapi/v2.1/accounts/{account_ID}/templates/{template_ID}?include=recipients,tabs

Now, To prepopulate a note field with the physical mailing address for a particular recipient, you can make a POST request to /envelopes. You will find the tabLabel from the previous step.

{
    "status": "sent",
    "templateId": "00df08bf-xxxx-xxxx-xxxx-ecaa2360c121",
    "templateRoles": [
        {
            "email": "test@test.com",
            "name": "ABC",
            "roleName": "signer",
            "routingOrder": "1",
            "tabs": {
                "noteTabs": [
                    {
                        "selected": "true",
                        "tabLabel": "userAddress",
                        "value": "theUsersAddressGoesHere"
                    }
                ]
            }
        },
        {
            "email": "test2@test.com",
            "name": "EFG",
            "roleName": "cc",
            "routingOrder": "2"
        }
    ]
}

If you are unable to see the value of the note field when signing, you may need to change the size of the bounding box. You can do this either by editing the template in the UI or adding X/Y properties to your request.


问:
JavaScript function is not running after form submission
I was trying to submit the form data to https://wallpapersforandroid.com/wallpaper-4/" in new tab and redirect the parent page to "https://www.youtube.com" after submission.
I do success to open the action page in new tab but the parent page is not redirecting
The code I used:</p>

```<code><form action="https://wallpapersforandroid.com/wallpaper-4/" method="post" target="_blank">
Type Password From Below Image: <input name="pass" type="text" />
<input id="myForm" type="submit" /><br />
<script>
  document.getElementById("myForm").onsubmit = function() {
    window.location.href = "https://www.youtube.com";
  };
</script>
</code>```

答:
If you submit the form, the current page is torn down and replaced with the result from submitting the form. If you set a new location, the current page is torn down and replaced with the page from that location. You can't do both at once; one of them wins and the other will lose.

You can submit your form via ajax and then do the redirect:

```<code>document.getElemntById("myForm").addEventListener("submit", function(e) {
    // Prevent the default form submission
    e.preventDefault();

    // Get the form data
    const data = new FormData(this);

    // Do the ajax
    fetch(this.action, {
        method: this.method,
        body: data
    })
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        }
        window.location.href = "https://www.youtube.com";
    })
    .catch(error => {
        // ...handle/report error...
    });
});
</code>```

Body:
I was trying to submit the form data to https://wallpapersforandroid.com/wallpaper-4/" in new tab and redirect the parent page to "https://www.youtube.com" after submission.
I do success to open the action page in new tab but the parent page is not redirecting
The code I used:

<form action="https://wallpapersforandroid.com/wallpaper-4/" method="post" target="_blank">
Type Password From Below Image: <input name="pass" type="text" />
<input id="myForm" type="submit" />

Body:
If you submit the form, the current page is torn down and replaced with the result from submitting the form. If you set a new location, the current page is torn down and replaced with the page from that location. You can't do both at once; one of them wins and the other will lose.

You can submit your form via ajax and then do the redirect:

document.getElemntById("myForm").addEventListener("submit", function(e) {
    // Prevent the default form submission
    e.preventDefault();

    // Get the form data
    const data = new FormData(this);

    // Do the ajax
    fetch(this.action, {
        method: this.method,
        body: data
    })
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        }
        window.location.href = "https://www.youtube.com";
    })
    .catch(error => {
        // ...handle/report error...
    });
});


问:
Column filter for "empty" value
Is there a way to add a column filter for empty values?
I see we can filter for equal, not equal, ... but I'd like to have an option to filter a column so it returns rows where the column is empty or null.</p>

答:
I had the same issue with empty cells
You should use 'Blank option'

```<code>const filterOptions = [
    'empty',
    {
        displayKey: 'blanks',
        displayName: 'Blanks',
        test: function (filterValue, cellValue) {
            return cellValue == undefined;
        },
        hideFilterInput: true,
    },
    'equals',
    'notEqual',
    'lessThan',
    'lessThanOrEqual',
    'greaterThan',
    'greaterThanOrEqual',
    'inRange'
];

columnDef = [
    {
        headerName: 'someValue', field: 'someValue',
        filter: 'agNumberColumnFilter',
        filterParams: {
            filterOptions: filterOptions
        }
    },]
</code>```

'empty' - is equal to 'Please choose option'

more inforamtion you can find here: https://www.ag-grid.com/javascript-grid-filter-provided-simple/#blank-cells-date-and-number-filters

Title: Column filter for "empty" value

Body:
I had the same issue with empty cells
You should use 'Blank option'

const filterOptions = [
    'empty',
    {
        displayKey: 'blanks',
        displayName: 'Blanks',
        test: function (filterValue, cellValue) {
            return cellValue == undefined;
        },
        hideFilterInput: true,
    },
    'equals',
    'notEqual',
    'lessThan',
    'lessThanOrEqual',
    'greaterThan',
    'greaterThanOrEqual',
    'inRange'
];

columnDef = [
    {
        headerName: 'someValue', field: 'someValue',
        filter: 'agNumberColumnFilter',
        filterParams: {
            filterOptions: filterOptions
        }
    },]

'empty' - is equal to 'Please choose option'

more inforamtion you can find here: https://www.ag-grid.com/javascript-grid-filter-provided-simple/#blank-cells-date-and-number-filters