Category Archives: Python

[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)

[Solved] import pyzed No Error, but import pyzed.sl report an Error (zed-pythonAPI Installing)

import pyzed No Error, but import pyzed.sl report an Error (zed-pythonAPI Installing)

reason: Python version is too high. As shown in the figure below, python 3.8+ are prone to lead to this problem

Solution: install Python 3.7

Additional notes:
if you use a virtual environment, such as anaconda, download the latest anaconda and create your own virtual environment, choose python = 3.7

[Solved] TVM operate error: TVMError: AssertionError

TVM operate error: TVMError: AssertionError

Traceback (most recent call last):
  File "tune_relay_x86.py", line 248, in <module>
    tune_and_evaluate(tuning_option)
  File "tune_relay_x86.py", line 241, in tune_and_evaluate
    lib = relay.build_module.build(mod, target=target, params=params)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/relay/build_module.py", line 468, in build
    graph_json, runtime_mod, params = bld_mod.build(
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/relay/build_module.py", line 196, in build
    self._build(mod, target, target_host, executor, runtime, workspace_memory_pools, mod_name)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/_ffi/_ctypes/packed_func.py", line 237, in __call__
    raise get_last_ffi_error()
tvm._ffi.base.TVMError: Traceback (most recent call last):
  30: TVMFuncCall
  29: tvm::relay::backend::RelayBuildModule::GetFunction(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, tvm::runtime::ObjectPtr<tvm::runtime::Object> const&)::{lambda(tvm::runtime::TVMArgs, tvm::runtime::TVMRetValue*)#3}::operator()(tvm::runtime::TVMArgs, tvm::runtime::TVMRetValue*) const
  28: tvm::relay::backend::RelayBuildModule::BuildRelay(tvm::IRModule, tvm::runtime::String const&)
  27: tvm::relay::backend::RelayBuildModule::OptimizeImpl(tvm::IRModule)
  26: tvm::transform::Pass::operator()(tvm::IRModule) const
  25: tvm::transform::Pass::operator()(tvm::IRModule, tvm::transform::PassContext const&) const
  24: tvm::transform::SequentialNode::operator()(tvm::IRModule, tvm::transform::PassContext const&) const
  23: tvm::transform::Pass::operator()(tvm::IRModule, tvm::transform::PassContext const&) const
  22: tvm::relay::transform::FunctionPassNode::operator()(tvm::IRModule, tvm::transform::PassContext const&) const
  21: _ZN3tvm7runtime13PackedFuncObj9ExtractorINS0_16PackedFuncSubObjIZNS0_15TypedPackedFuncIFNS_5relay8FunctionES6_NS_8IRModuleENS_9transform11PassContextEEE17AssignTypedLambdaIZNS5_9transform13AlterOpLayoutEvEUlS6_S7_S9_E_EEvT_EUlRKNS0_7TVMArgsEPNS0_11TVMRetValueEE_EEE4CallEPKS1_SG_SK_
  20: tvm::relay::alter_op_layout::AlterOpLayout(tvm::RelayExpr const&)
  19: tvm::relay::ForwardRewrite(tvm::RelayExpr const&, tvm::runtime::TypedPackedFunc<tvm::RelayExpr (tvm::relay::Call const&, tvm::runtime::Array<tvm::RelayExpr, void> const&, tvm::runtime::ObjectRef const&)> const&, std::function<tvm::runtime::ObjectRef (tvm::relay::Call const&)>, std::function<tvm::RelayExpr (tvm::RelayExpr const&)>)
  18: tvm::relay::MixedModeMutator::VisitExpr(tvm::RelayExpr const&)
  17: tvm::relay::MixedModeMutator::VisitLeaf(tvm::RelayExpr const&)
  16: _ZN3tvm5relay16MixedModeMutator17DispatchVisitExprERKNS_9Re
  15: tvm::relay::ExprMutator::VisitExpr(tvm::RelayExpr const&)
  14: tvm::relay::ExprFunctor<tvm::RelayExpr (tvm::RelayExpr const&)>::VisitExpr(tvm::RelayExpr const&)
  13: _ZZN3tvm5relay11ExprFunctorIFNS_9RelayExprERKS2_EE10InitVTableEvENUlR
  12: tvm::relay::ExprMutator::VisitExpr_(tvm::relay::FunctionNode const*)
  11: tvm::relay::MixedModeMutator::VisitExpr(tvm::RelayExpr const&)
  10: tvm::relay::MixedModeMutator::VisitLeaf(tvm::RelayExpr const&)
  9: _ZN3tvm5relay16MixedModeMutator17DispatchVisitExprERKNS_9Re
  8: tvm::relay::ExprMutator::VisitExpr(tvm::RelayExpr const&)
  7: tvm::relay::ExprFunctor<tvm::RelayExpr (tvm::RelayExpr const&)>::VisitExpr(tvm::RelayExpr const&)
  6: _ZZN3tvm5relay11ExprFunctorIFNS_9RelayExprERKS2_EE10InitVTableEvENUlR
  5: tvm::relay::MixedModeMutator::VisitExpr_(tvm::relay::CallNode const*)
  4: tvm::relay::ForwardRewriter::Rewrite_(tvm::relay::CallNode const*, tvm::RelayExpr const&)
  3: tvm::runtime::PackedFuncObj::Extractor<tvm::runtime::PackedFuncSubObj<tvm::runtime::TypedPackedFunc<tvm::RelayExpr (tvm::relay::Call const&, tvm::runtime::Array<tvm::RelayExpr, void> const&, tvm::runtime::ObjectRef const&)>::AssignTypedLambda<tvm::RelayExpr (*)(tvm::relay::Call const&, tvm::runtime::Array<tvm::RelayExpr, void> const&, tvm::runtime::ObjectRef const&)>(tvm::RelayExpr (*)(tvm::relay::Call const&, tvm::runtime::Array<tvm::RelayExpr, void> const&, tvm::runtime::ObjectRef const&))::{lambda(tvm::runtime::TVMArgs const&, tvm::runtime::TVMRetValue*)#1}> >::Call(tvm::runtime::PackedFuncObj const*, tvm::runtime::TVMArgs, tvm::runtime::TVMRetValue*)
  2: tvm::RelayExpr tvm::relay::LayoutRewriter<tvm::relay::alter_op_layout::AlterTransformMemorizer>(tvm::relay::Call const&, tvm::runtime::Array<tvm::RelayExpr, void> const&, tvm::runtime::ObjectRef const&)
  1: tvm::relay::alter_op_layout::AlterTransformMemorizerNode::CallWithNewLayouts(tvm::relay::Call const&, tvm::Attrs, std::vector<tvm::RelayExpr, std::allocator<tvm::RelayExpr> > const&)
  0: tvm::runtime::PackedFuncObj::Extractor<tvm::runtime::PackedFuncSubObj<TVMFuncCreateFromCFunc::{lambda(tvm::runtime::TVMArgs, tvm::runtime::TVMRetValue*)#2}> >::Call(tvm::runtime::PackedFuncObj const*, tvm::runtime::TVMArgs, tvm::runtime::TVMRetValue*)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/_ffi/_ctypes/packed_func.py", line 81, in cfun
    rv = local_pyfunc(*pyargs)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/relay/op/nn/_nn.py", line 112, in alter_op_layout_dense
    return topi.nn.dense_alter_layout(attrs, inputs, tinfos, out_type)
  File "/home/lizhenxu/anaconda3/lib/python3.8/site-packages/decorator.py", line 231, in fun
    return caller(func, *(extras + args), **kw)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/target/generic_func.py", line 286, in dispatch_func
    return dispatch_dict[k](*args, **kwargs)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/topi/x86/dense_alter_op.py", line 51, in _alter_dense_layout
    _, outs = relay.backend.te_compiler.select_implementation(
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/relay/backend/te_compiler.py", line 201, in select_implementation
    outs = impl.compute(attrs, inputs, out_type)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/relay/op/op.py", line 126, in compute
    return _OpImplementationCompute(self, attrs, inputs, out_type)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/_ffi/_ctypes/packed_func.py", line 237, in __call__
    raise get_last_ffi_error()
  3: TVMFuncCall
  2: tvm::runtime::PackedFuncObj::Extractor<tvm::runtime::PackedFuncSubObj<tvm::relay::{lambda(tvm::runtime::TVMArgs, tvm::runtime::TVMRetValue*)#4}> >::Call(tvm::runtime::PackedFuncObj const*, tvm::runtime::TVMArgs, tvm::runtime::TVMRetValue*)
  1: tvm::relay::OpImplementation::Compute(tvm::Attrs const&, tvm::runtime::Array<tvm::te::Tensor, void> const&, tvm::Type const&)
  0: tvm::runtime::PackedFuncObj::Extractor<tvm::runtime::PackedFuncSubObj<TVMFuncCreateFromCFunc::{lambda(tvm::runtime::TVMArgs, tvm::runtime::TVMRetValue*)#2}> >::Call(tvm::runtime::PackedFuncObj const*, tvm::runtime::TVMArgs, tvm::runtime::TVMRetValue*)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/_ffi/_ctypes/packed_func.py", line 81, in cfun
    rv = local_pyfunc(*pyargs)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/relay/op/strategy/generic.py", line 833, in _compute_dense
    return [topi_compute(*args)]
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/autotvm/task/topi_integration.py", line 164, in wrapper
    cfg = DispatchContext.current.query(tgt, workload)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/autotvm/task/dispatcher.py", line 76, in query
    ret = self._query_inside(target, workload)
  File "/home/lizhenxu/ZJJ/tvm_0.9/tvm/python/tvm/autotvm/task/dispatcher.py", line 421, in _query_inside
    assert wkl == workload
TVMError: AssertionError

Run the official website code tune_relay_x86.py report the error above.

Solution: delete the .log file that was generated by running this code before

Pytorch Error: error: identifier “AT_CHECK“ is undefined [How to Solve]

These two days, run a mask RCNN series of network code, and execute the command Python 3 setup A bunch of such errors are received during py build development, as follows:

.../detectron2/layers/csrc/deformable/deform_conv.h(136): error: identifier "AT_CHECK" is undefined

.../detectron2/layers/csrc/deformable/deform_conv.h(184): error: identifier "AT_CHECK" is undefined

.../detectron2/layers/csrc/deformable/deform_conv.h(234): error: identifier "AT_CHECK" is undefined

.../detectron2/layers/csrc/deformable/deform_conv.h(284): error: identifier "AT_CHECK" is undefined

.../detectron2/layers/csrc/deformable/deform_conv.h(341): error: identifier "AT_CHECK" is undefined

.../detectron2/layers/csrc/deformable/deform_conv_cuda.cu(155): error: identifier "AT_CHECK " is undefined

.../detectron2/layers/csrc/deformable/deform_conv_cuda.cu(338): error: identifier "AT_CHECK " is undefined

.../detectron2/layers/csrc/deformable/deform_conv_cuda.cu(503): error: identifier "AT_CHECK " is undefined

.../detectron2/layers/csrc/deformable/deform_conv_cuda.cu(696): error: identifier "AT_CHECK " is undefined

.../detectron2/layers/csrc/deformable/deform_conv_cuda.cu(823): error: identifier "AT_CHECK " is undefined

.../detectron2/layers/csrc/deformable/deform_conv_cuda.cu(953): error: identifier "AT_CHECK " is undefined

11 errors detected in the compilation of ".../detectron2/layers/csrc/deformable/deform_conv _cuda.cu".

Solution:

Replace all AT_CHECK in deform_conv_cuda.cpp with TORCH_CHECK

or macro definition:

#ifndef AT_CHECK
#define AT_CHECK TORCH_CHECK 
#endif

[Solved] Pyinstaller Package and Run Error: RuntimeError: Unable to open/read ui device

Just made a Python program to calculate body mass index BMI, and used Pyside6 to draw the user interface. When using auto-py-exe ( auto-py-to-exe is based on pyinstaller, compared to pyinstaller, it has more GUI interface, which makes it easier to use. for simplicity). After packaging, click main.exe, but it prompts an error: RuntimeError: Unable to open/read ui device. Repeated debugging does not know where the problem is.

At first, I thought there was a problem with the loading UI statement in the main program (main.py). I repeatedly modified the main program, and finally found that it was not the problem of the program.

class Stats():
    def __init__(self):
	    # loading UI file
        self.ui = QUiLoader().load(".\\cac_BMI.ui") 

Finally, I found that I needed to put the UI file into the packaged executable folder.

Put the UI file and the main program in the same folder, which is convenient for the main program to call.

Then double-click main.exe, has been able to successfully open the program user interface, and the problem has been successfully solved.

[DL Common Issue] RuntimeError: CUDA error 59: Device-side assert triggered

Problem: Run into a CUDA error during training
Solutions:
This error occurs due to the following two reasons:

    Inconsistency between the number of labels/classes and the number of output unitsThe input of the loss function may be incorrect

In my case the error occurs as the loss function is not correctly chosen : change to nn.BCELoss() from nn.CrossEntropyLoss()
Reference: https://towardsdatascience.com/cuda-error-device-side-assert-triggered-c6ae1c8fa4c3

[Solved] hydra Install Error: AttributeError: module ‘hydra‘ has no attribute ‘main‘

AttributeError: module ‘hydra’ has no attribute ‘main’

Error:

1. use the following command to install hydra:pip install hydra,an error is reported:AttributeError: module 'hydra' has no attribute 'main'


Solution:

2. Uninstall the installed hydra: pip uninstall hydra
3. Instead of using the following command: pip install hydra-core --upgrade, It will be install fine!

[Solved] IDA Start Error: Unexcepted fatal error while intitailizing Python runtime…

When I opened IDA today, It suddenly appeared:

it startled me. What’s going on? Calm down and analyze it. I’m going to open it in the same directory as IDA. See what error reports:

the result can’t be opened, and then I directly open idat64.exe,

there should be a problem with the python path. Open the environment variable and add the following to the user environment variable:

PYTHONHOME  #EVI PATH
C:/Program File/python  #PATH

Then save and open IDA to use

Python pyqt5 ui Generate .py File Error [How to Solve]

Anaconda has been configured several times before, and there are similar problems: record it here for later viewing.

 from PyQt5 import QtCore
ImportError: DLL load failed: the specified module cannot be found.

 

Traceback (most recent call last):
  File "D:\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "D:\Anaconda3\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "D:\Anaconda3\lib\site-packages\PyQt5\uic\pyuic.py", line 26, in <module>
    from PyQt5 import QtCore
ImportError: DLL load failed: the specified module cannot be found.

The configuration is as follows:

The problem is that the module cannot be found, but pyqt itself can run. Then I looked at the installed library and found that pyqt is 5.92, not pyqt5. That’s why.

Uninstall pyqt first:

Or use PIP uninstall pyqt;

Then install pyqt5. Use pip to install here. Pycharm’s installation tool is not found.

Installation command:

pip install PyQt5

Run again, OK!