Tag Archives: python

[Solved] ValueError: Error when checking input: expected conv2d_input to have 4 dimensions

Error Messages:

ValueError: Error when checking input: expected conv2d_input to have 4 dimensions, but got array with shape (150, 150, 3)
Codes:

image = mpimg.imread("./ima/b.jpg")
image = image/255
classe = model.predict(image, batch_size=1)

Reason:
the input format is incorrect
solution:
standardize the dataset

Specific solutions:

image = mpimg.imread("./ima/b.jpg")
image = image.reshape(image.shape(1,150,150,3)/255
classe = model.predict(image, batch_size=1)

[Solved] This error might have occurred since this system does not have Windows Long Path support enabled.

This error might have occurred since this system does not have Windows Long Path support enabled.

pip install rife_ncnn_vulkan_python
WARNING: Ignoring invalid distribution -ip (d:\python3.8\lib\site-packages)
WARNING: Ignoring invalid distribution -ip (d:\python3.8\lib\site-packages)
Collecting rife_ncnn_vulkan_python
Using cached rife-ncnn-vulkan-python-1.1.2.post3.tar.gz (21.5 MB)
ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: ‘C:\Users\Administrator\AppData\Local\Temp\pip-install-ti2fh5nq\rife-ncnn-vulkan-python_464f213e18974938aa0e4a998e825356\rife_ncnn_vulkan_python/rife-ncnn-vulkan/src/ncnn/glslang/Test/baseResults/spv.WorkgroupMemoryExplicitLayout.MixBlockNonBlock_Errors.comp.out’
HINT: This error might have occurred since this system does not have Windows Long Path support enabled. You can find information on how to enable this at https://pip.pypa.io/warnings/enable-long-paths

 

Solution:

OSError: [WinError 1455] The page file is too small to complete the operation. Error loading…

Complete error oserror: [winerror 1455] the page file is too small to complete the operation. Error loading “C:\ProgramData\Anaconda3\lib\site-packages\torch\lib\shm.dll” or one of its dependencies.

Scenario: Running the reid-strong-baseline model

Reason: The model is too large, and the system allocated paging memory is too small to train

Environment: windows10, cuda version: 11.1, pytorch version: 1.11.0+cu113

(1) Query your CUDA version:

nvidia-smi

(2) Query your own version of pytorch

import torch
print(torch.__version__)

Solution: Right-click Properties->Advanced System Settings->Advanced->Settings->Advanced->Programs->Change->Uncheck “Automatically manage…” (Define initial size and maximum size) (set here according to the actual available space, as large as possible) -> click “Settings” -> OK -> reboot

If the error is still reported after reboot, the possible reasons are: (1) the custom size is still too small (for example, I set 10G at the beginning, but still reported an error, and subsequently modified to 100G (100000M) to run successfully) (2) the batch_size is too large, you can adjust the size appropriately (for example, reduce 64 to 16)

[Solved] vpython: AttributeError: ‘box‘ object has no attribute ‘idx‘

vpython : AttributeError: ‘box‘ object has no attribute ‘idx‘

Problem description

1. Problem Description:

After importing the VPython library, the errors reported after using the sphere class or box class in the VPython library are as follows:

the main error statement is the underlined part: attributeerror: 'box' object has no attribute 'IDX' (changing box to sphere is the same).

After debugging, it is found that the specific errors are as follows:

2. Solution

  1. Make sure vpython is installed
  2. Check the third-party libraries of the project environment for the packages autobahn and txaio, e.g. mine are autobahn version is 22.4.2, txaio version is 22.2.1.
  3. Lower the version of audobahn. If I lower the version to 22.3.2

Success!!!!!!!

[Solved] Geopy library Error: Configurationerror Error

Geopy library Error: Configuration Error

Error details

geopy.exc.ConfigurationError: 
Using Nominatim with default or sample `user_agent` "geopy/2.2.0" is strongly discouraged, as it violates Nominatim's ToS https://operations.osmfoundation.org/policies/nominatim/ and may possibly cause 403 and 429 HTTP errors. Please specify a custom `user_agent` with `Nominatim(user_agent="my-application")` or by overriding the default `user_agent`: `geopy.geocoders.options.default_user_agent = "my-application"`.

Solution:
This error is because the default value of UA is bad. Just specify user-agent as a unique string. For example
, when BuyiXiao initializes Nominatim, specify user-agent.

geolocator = Nominatim(user_agent='BuyiXiao')

[Solved] RuntimeError: Error(s) in loading state_dict for BertForTokenClassification

RuntimeError: Error(s) in loading state_dict for BertForTokenClassification

problem:
RuntimeError: Error(s) in loading state_dict for BertForTokenClassification:size mismatch for bert.embeddings.word_embeddings.weight: copying a param with shape torch.Size([21128, 768]) from checkpoint, the shape in current model is torch.Size([119547, 768]).
Solution:
The parameters of torch are not consistent with the mod
My original code was

model = AutoModelForTokenClassification.from_pretrained("bert-base-multilingual-cased", num_labels=len(label_names))

Just reinstall pytorch

conda install pytorch==1.7.1

[Solved] Windows pycrypto Install Error: ERROR: Failed building wheel for pycrypto

Windows will report an error when installing pycrypto.

Here are some errors

Collecting pycrypto
  Downloading http://mirrors.aliyun.com/pypi/packages/60/db/645aa9af249f059cc3a368b118de33889219e0362141e75d4eaf6f80f163/pycrypto-2.6.1.tar.gz (446 kB)
     |████████████████████████████████| 446 kB 344 kB/s
Building wheels for collected packages: pycrypto
  Building wheel for pycrypto (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: 'd:\ProgramData\Anaconda3\envs\d2t\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\zm\\AppData\\Local\\Temp\\pip-install-trmr6taw\\pycrypto_e1aaae9b5afb410691bac391ddb2c59f\\setup.py'"'"'; __file__='"'"'C:\\Users\\zm\\AppData\\Local\\Temp\\pip-install-trmr6taw\\pycrypto_e1aaae9b5afb410691bac391ddb2c59f\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\zm\AppData\Local\Temp\pip-wheel-egkss95d'
       cwd: C:\Users\zm\AppData\Local\Temp\pip-install-trmr6taw\pycrypto_e1aaae9b5afb410691bac391ddb2c59f\
  Complete output (183 lines):

The solution is:

1. Enter VC directory: C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC

2. Execute vcvarsall.bat

3. Execute set CL=-FI”%VCINSTALLDIR%\INCLUDE\stdint.h”

Install it (I install it in the env of anaconda, so I enter env first)

https://blog.csdn.net/zm274310577/article/details/124927922

[Solved] error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows

Error: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows

I’m on windows, and when running an image motion blur algorithm from the cv-python library, this error is suddenly reported.
Searching for similar problems has said that the path to read the image is wrong, and reinstalling a higher version of the cv library, but not all of them are useless.
All the functions under the cv2 class are not working.

Solution:
First:

pip uninstall opencv-python 

Then:

pip install opencv-python

Just reinstall this package. I don’t know the cause. The problem occurred after I installed the evaluations package. It should be caused by the conflict between versions
stackoverflow: https://stackoverflow.com/questions/67120450/error-2unspecified-error-the-function-is-not-implemented-rebuild-the-libra

[Solved] pymysql.err.ProgrammingError: (1064, ‘You have an error in your SQL syntax;

[Solved] pymysql.err.ProgrammingError: (1064, ‘You have an error in your SQL syntax;

Purpose

Use pymysql to insert data into the MySQL database.

Abnormal information

code

sql_test = '''INSERT INTO "es_site" ("id", "site_name", "site_role", "url", "password", "username") VALUES (1, 'test', 'test', 'https://test.com', 'passwd', 'estest');'''
cur.execute(sql_test)
conn.commit()
cur.close()
conn.close()

Solution

The field name in sql cannot be enclosed in quotation marks. Just remove the quotation marks of the field and table name

[Solved] PyCharm pytest-html Install Error: Try to run this command from the system terminal. Make sure that you use

PyCharm pytest-html Install Error: Try to run this command from the system terminal. Make sure that you use

Exception prompt:
try to run this command from the system terminal Make sure that you use the correct version of ‘pip’ installed for your Python interpreter located at ‘E:\python\Program\Scripts\python.exe’.

Solution:
Switch the pycharm interpreter and reconfigure it again.

[Solved] Vite build & Flask Error: Failed to load module script. Strict MIME type checking is enforced

Vite build & Flask Error: Failed to load module script. Strict MIME type checking is enforced


Stack Overflow

questions

I have this HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link
        rel="stylesheet"
        href="../../../static/css/style.css"
        type="text/css" />
    <link
        rel="stylesheet"
        href="../../../static/css/user_header.css"
        type="text/css" />

    <!--suppress HtmlUnknownTarget -->
    <link rel="shortcut icon" href="/favicon.png">

    <script type="module" src="../../../static/js/node_connect.js" ></script>  <-- Error
    <script src="../../../static/lib/jquery.min.js"></script>
    <script src="../../../static/lib/selfserve.js"></script>   

</head>

The problem is node_connect.jsfile. Start the flash web tool locally (Python 3.7.2), and the console will report the following error when opening the page:

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain".
Strict MIME type checking is enforced for module scripts per HTML spec.

Check Title:

Content-Type: text/plain; charset=utf-8

However, in production (when starting through gunicorn), it gives:

Content-Type: application/javascript; charset=utf-8

I guess the web server (APACHE) serves them in the production case, but another thing is that when testing other pages of the web tool, they all work and load JavaScript files correctly (even if their content type is text/plain text). However, the difference is that I notice that in the type.

This applies to my situation:

<script src="../../static/js/translator/library/materialize.js"></script>

Or this:

<script type="application/javascript" src="../../static/js/translator/library/materialize.js"></script>

Of course, I tried this for the problematic JavaScript . File and received the following error (which means it is now loaded):

Uncaught SyntaxError: Cannot use import statement outside a module

According to my research, this basically means that I need to set the type to module (but this will make the browser reject .js files).

Who can help me solve this problem?

best answer:

The problem is caused by flash how to guess the content type of each static file
Import mimetypes from flash and call mimeType, encoding = mimetypes guess_type (download_name) this module creates a database of known MIME types from multiple sources and uses it to return MIME types
Linux and MacOS: look at the mimetypes.py files:

knownfiles = [
    "/etc/mime.types",
    "/etc/httpd/mime.types",                    # Mac OS X
    "/etc/httpd/conf/mime.types",               # Apache
    "/etc/apache/mime.types",                   # Apache 1
    "/etc/apache2/mime.types",                  # Apache 2
    "/usr/local/etc/httpd/conf/mime.types",
    "/usr/local/lib/netscape/mime.types",
    "/usr/local/etc/httpd/conf/mime.types",     # Apache 1.2
    "/usr/local/etc/mime.types",                # Apache 1.3
    ]

But in windows, it will look in the registry:

with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr:
    for subkeyname in enum_types(hkcr):
        try:
            with _winreg.OpenKey(hkcr, subkeyname) as subkey:
                # Only check file extensions
                if not subkeyname.startswith("."):
                    continue
                # raises OSError if no 'Content Type' value
                mimetype, datatype = _winreg.QueryValueEx(
                    subkey, 'Content Type')
                if datatype != _winreg.REG_SZ:
                    continue
                self.add_type(mimetype, subkeyname, strict)

So to solve the problem, flask thinks JS file is actually a problem of text/plain , just open regedit and adjust this registry key to application/javaScript .

solutions for vite:

Find the registry value, double-click content type to change it to Application/JavaScript , and then restart the computer

if not, please see if your suffix is simple .js, if it is .1242342.js , must be changed to pure .JS suffix can take effect

In order to completely eradicate the disadvantages of modifying files, we can change the configuration file of vite , and modify the name of the output JS file by using the custom packaging option rollupOptions.

Reference: vite2 how to set the file name after packaging

Other configuration items of vite.config.js are shown on the official website. Click here to view more configuration items on the official website.

Python: How to Disable InsecureRequestWarning error

Python Disable InsecureRequestWarning error

Send HTTPS requests using Python 3 requests. When SSL authentication is turned off (verify = false):

import requests
response = requests.get(url='http://127.0.0.1:12345/test', verify=False)

Error Messages:

InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings

Solution:

#python3
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

#python2
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

PS: as shown below, disable_warnings() will disable all warning types.

def disable_warnings(category=exceptions.HTTPWarning):
    """
    Helper for quickly disabling all urllib3 warnings.
    """
    warnings.simplefilter("ignore", category)