Category Archives: Python

How to Solve Spyder Version incompatible error

1.Problem with input() in Spyder 5.1.5 (Anaconda)

Reasons for incompatible Spyder versions and solutions:
1 Upgrade to (5.3.0)
2 If anaconda is not compatible with the latest version, you can only upgrade to 5.1.5, create a new environment conda-forge packages, and enter the following codes in Anaconda Prompt:

 conda create -n spyder-cf -c conda-forge spyder
 conda activate spyder-cf
 pip install spyder==5.3.0

 

[Solved] Using Java to call jython Error: URI is not hierarchical

Due to the need to use Jython. However, a strange phenomenon is found. There is no problem with the use of IDE, but the error is reported when packaging the jar.

java.lang.IllegalArgumentException: URI is not hierarchical
        at java.io.File.<init>(File.java:418)
        at org.python.core.PrePy.getJarFileNameFromURL(PrePy.java:427)
        at org.python.core.PrePy._getJarFileName(PrePy.java:362)
        at org.python.core.PrePy.getJarFileName(PrePy.java:345)
        at org.python.core.PySystemState.doInitialize(PySystemState.java:1195)
        at org.python.core.PySystemState.initialize(PySystemState.java:1130)
        at org.python.core.PySystemState.initialize(PySystemState.java:1085)
        at org.python.core.PySystemState.initialize(PySystemState.java:1080)
        at org.python.util.PythonInterpreter.initialize(PythonInterpreter.java:63)
        at com.langtutu.ncs.api.robot.core.Test.<init>(Test.java:34)
        at com.langtutu.ncs.api.service.impl.HomestaySchedulingServiceImpl.DownOrderTest(HomestaySchedulingServiceImpl.java:90)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
        at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
        at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)

2. Problem finding

Debug and trace Jython using IDE and remote call respectively, and locate the error line of the code:

IDE debugging found that the URL is as follows: jar:file:/D:/maven/apache-maven-3.3.9/repository/org/python/jython/2.7.2/jython-2.7.2.jar!/org/python/core/PrePy.class

Remote debugging

Nesting cannot be used.

3. Solution:

Jython will be Deleted when Maven is packaged; Just load the external jar package at runtime.

eliminate:

<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<version>2.2.10.RELEASE</version>
				<configuration>
					<layout>ZIP</layout>
					<!--Removing dependencies that do not change in the production environment are separated by commas,-->
					<excludeGroupIds>
						org.python
					</excludeGroupIds>
				</configuration>
			</plugin>
		</plugins>
	</build>

function:

java -Dloader.path="lib/" -jar .\ncsapi-0.0.1-SNAPSHOT.jar

Inside lib is the jar package. At this time, the operation is completely normal

[Solved] Python requests ConnectionError Error: connection aborted BadStatusLine

Error Messages:

raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: (‘Connection aborted.’, BadStatusLine(“””, ))
Codes

data = {"host":host,"key":key,"value":value,"dns":ip} 

res = requests.post(url=url,json = data)

Method 1: add retry

requests.adapters.DEFAULT_RETRIES = 5

Method 2: add header

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'} 

res = requests.post(url=url,json = data,headers=headers)

Method 3: curl
If method 1,2 does not work, use curl command to find the following error messages:
Empty reply from server

Solution: https://stackoverflow.com/questions/48814200/connection-aborted-badstatusline-on-server

[Solved] XiaoMi Phone Uiautomator Startup Error: uiautomator2.GatewayError

check the error messages:

OSError: [WinError adb shell am instrument -w -r -e debug false -e class com.github.uiautomator.stub.Stub com.github.uiautomator.test/android.support.test.runner.AndroidJUnitRunner] uiautomator2.GatewayError(gateway error, time used 0.0s): 'https://github.com/openatx/uiautomator2/wiki/Common-issues'

It is said that app-uiautomator.apk or app-uiautomator-test.apk not installed. but if you use the following command:

 python -m uiautomator2 init

There are no errors, and you can see the successful installation of the above two apps, so the problem is not the failure of uiautomator app installation.

Solution:

Turn on the settings of Xiaomi mobile phone – turn on developer options – turn on USB debugging – turn on USB installation – turn on USB debugging (security settings) – turn on the application that passes USB verification (default on) – turn on wireless display authentication (optional). The key option is not to enable MIUI optimization. After operating the above settings, execute python -m uiautomator2 init (no error), and then you can execute the relevant scripts

[Solved] Win10 Install pyav Error: ERROR: Failed building wheel for avFailed to build av. ERROR: Could not build wheel

Python3. 6: In win10 environment, use the following command to install pyav:

pip install av

Failed to install pyav, here is the error message:

        ERROR: Failed building wheel for av
        Failed to build av
        ERROR: Could not build wheels for av which use PEP 517 and cannot be installed directly:

 

(C:\Users\Jayce\Anaconda3\envs\tf1.7) E:\Code\Python>pip install av
Looking in indexes: https://pypi.doubanio.com/simple
Collecting av
  Downloading https://pypi.doubanio.com/packages/00/3f/9fe21065912902a7856a69df334a67b73a51da5e08ff033fd79f15d05764/av-9.1.1.tar.gz (2.4 MB)
     |████████████████████████████████| 2.4 MB 3.2 MB/s
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Building wheels for collected packages: av
  Building wheel for av (PEP 517) ... error
  ERROR: Command errored out with exit status 1:
   command: 'C:\Users\Jayce\Anaconda3\envs\tf1.7\python.exe' 'C:\Users\Jayce\Anaconda3\envs\tf1.7\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py' build_wheel 'C:\Users\J
ayce\AppData\Local\Temp\tmpctqsnqx6'
       cwd: C:\Users\Jayce\AppData\Local\Temp\pip-install-hi4s2fdw\av_03c9287622cf4da7918135c5be424e7b
  Complete output (38 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-3.6
  creating build\lib.win-amd64-3.6\av
  copying av\about.py -> build\lib.win-amd64-3.6\av
  copying av\datasets.py -> build\lib.win-amd64-3.6\av
  copying av\deprecation.py -> build\lib.win-amd64-3.6\av
  copying av\__init__.py -> build\lib.win-amd64-3.6\av
  copying av\__main__.py -> build\lib.win-amd64-3.6\av
  creating build\lib.win-amd64-3.6\av\audio
  copying av\audio\__init__.py -> build\lib.win-amd64-3.6\av\audio
  creating build\lib.win-amd64-3.6\av\codec
  copying av\codec\__init__.py -> build\lib.win-amd64-3.6\av\codec
  creating build\lib.win-amd64-3.6\av\container
  copying av\container\__init__.py -> build\lib.win-amd64-3.6\av\container
  creating build\lib.win-amd64-3.6\av\data
  copying av\data\__init__.py -> build\lib.win-amd64-3.6\av\data
  creating build\lib.win-amd64-3.6\av\filter
  copying av\filter\__init__.py -> build\lib.win-amd64-3.6\av\filter
  creating build\lib.win-amd64-3.6\av\sidedata
  copying av\sidedata\__init__.py -> build\lib.win-amd64-3.6\av\sidedata
  creating build\lib.win-amd64-3.6\av\subtitles
  copying av\subtitles\__init__.py -> build\lib.win-amd64-3.6\av\subtitles
  creating build\lib.win-amd64-3.6\av\video
  copying av\video\__init__.py -> build\lib.win-amd64-3.6\av\video
  running build_ext
  building 'av.buffer' extension
  creating build\temp.win-amd64-3.6
  creating build\temp.win-amd64-3.6\Release
  creating build\temp.win-amd64-3.6\Release\src
  creating build\temp.win-amd64-3.6\Release\src\av
  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe /c logo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\Jayce\Anaconda3\envs\tf1.7\include -IC:\Users\Jayce\Anaconda
3\envs\tf1.7\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Wi
ndows Kits\8.1\include\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\um" "-IC:\Program Files (x86)\Windows Kits\8.1\include\winrt" /Tcsrc\av\buffer.c /Fobuild\temp.win-amd6
4-3.6\Release\src\av\buffer.obj
  buffer.c
  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\link.exe logo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\Jayce\Anaconda3
\envs\tf1.7\libs /LIBPATH:C:\Users\Jayce\Anaconda3\envs\tf1.7\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\LIB\amd64" "/LIBPATH:C:\Program Files (x86)\
Windows Kits\10\lib\10.0.10240.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\8.1\lib\winv6.3\um\x64" avformat.lib avcodec.lib avdevice.lib avutil.lib avfilter.lib swscale.li
b swresample.lib /EXPORT:PyInit_buffer build\temp.win-amd64-3.6\Release\src\av\buffer.obj /OUT:build\lib.win-amd64-3.6\av\buffer.cp36-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.6\Rele
ase\src\av\buffer.cp36-win_amd64.lib
  LINK : fatal error LNK1181: cannot open input file 'avformat.lib'
  error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1181
  ----------------------------------------
  ERROR: Failed building wheel for av
Failed to build av
ERROR: Could not build wheels for av which use PEP 517 and cannot be installed directly

This is because installing without a version number will install the latest version of pyav, which is not suitable for Python 3 6, so you need to compile it yourself, and you need to install ffmpeg for your own compilation, which leads to compilation errors because there is no ffmpeg.

1. Either install ffmpeg by yourself and compile it;

2. Or go straight to find the whl file of Python 3.6, direct installation;

I directly found the latest support for Python 3 on the mirror website Pyav of 6 is 8.0.3. Download and install:

Or add the version number of Python 3.6 in the PIP command:

pip install av==8.0.3

[Solved] jupyter notebook Error: 500 : Internal Server Error

1. Problem Description:
the Jupiter notebook can open the directory page, but it cannot open normally .ipynb file, as shown in the figure below, reports an error:

after consulting the data, we know that the error is caused by the incompatibility between nbconvert and pandoc
2. Solution:
enter the following command to install and upgrade nbconvert

pip install --upgrade --user nbconvert

After successfully installing nbconvert, start jupyter notebook again and open .ipynb file normally in the browser.

[Solved] mmdet install error: ERROR: Could not build wheels for pycocotools

x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -fPIC -I/usr/local/lib/python3.8/dist-packages/numpy/core/include -I./common -I/usr/include/python3.8 -c pycocotools/_mask.c -o build/temp.linux-x86_64-3.8/pycocotools/_mask.o -Wno-cpp -Wno-unused-function -std=c99
      pycocotools/_mask.c:4:10: fatal error: Python.h: No such file or directory
       #include "Python.h"
                ^~~~~~~~~~
      compilation terminated.
      error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for pycocotools
Failed to build pycocotools
ERROR: Could not build wheels for pycocotools, which is required to install pyproject.toml-based projects

The python version I use is 3.8 (replaced according to your version).

Solution:

Execute sudo apt install python3.8-dev

[Solved] PyQt: RuntimeError: wrapped C/C++ object has been deleted & has no attribute of flush in python

After redirecting the command line output to the UI interface in the previous article, an error will be reported when closing the UI interface

Has no attribute of flush in Python or

PyQt: RuntimeError: wrapped C/C++ object has been deleted

The solution is to add a function in the class to which the command line output is redirected:

class ButtonOne(QThread):
    _signalForText = pyqtSignal(str)
 
    def __init__(self):
        super(ButtonOne, self).__init__()
 
    def write(self, text):
        self.signalForText.emit(text)
 
    def run(self):
 
        for i in range(15):
            time.sleep(1)
            print(i)
        print('end')
 
    @property
    def signalForText(self):
        return self._signalForText
    
    def flush(self):
        pass

This can be solved.

The added functions are:

def flush(self):
    pass

[Solved] fit function error: KeyError: ‘squared_error‘

critical code

param_grid_simple = {"criterion": ["squared_error","poisson"]
                     , 'n_estimators': [*range(20,100,5)]
                     , 'max_depth': [*range(10,25,2)]
                     , "max_features": ["log2","sqrt",16,32,64,"auto"]
                     , "min_impurity_decrease": [*np.arange(0,5,10)]
                    }
search = GridSearchCV(estimator=reg
                     ,param_grid=param_grid_simple
                     ,scoring = "neg_mean_squared_error"
                     ,verbose = True
                     ,cv = cv
                     ,n_jobs=-1)
search.fit(X,y)                  

Error reporting information

~/anaconda3/lib/python3.8/site-packages/sklearn/ensemble/_forest.py in _parallel_build_trees(tree, forest, X, y, sample_weight, tree_idx, n_trees, verbose, class_weight, n_samples_bootstrap)
    166                                                         indices=indices)
    167 
--> 168         tree.fit(X, y, sample_weight=curr_sample_weight, check_input=False)
    169     else:
    170         tree.fit(X, y, sample_weight=sample_weight, check_input=False)

~/anaconda3/lib/python3.8/site-packages/sklearn/tree/_classes.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
   1240         """
   1241 
-> 1242         super().fit(
   1243             X, y,
   1244             sample_weight=sample_weight,

~/anaconda3/lib/python3.8/site-packages/sklearn/tree/_classes.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
    334                                                          self.n_classes_)
    335             else:
--> 336                 criterion = CRITERIA_REG[self.criterion](self.n_outputs_,
    337                                                          n_samples)
    338 

KeyError: 'squared_error'

analysis

KeyError error will be caused when accessing a key that is not in dict, then the parameter of criterion is squared_error may not exist. Since the parameter value is known, it is speculated that there may be a problem with your own sklearn version. Check your version of sklearn is 0.23, while the official version has already been above 1.0.

Solution:

See the official document of sklearn

scikit-learn 1.1. dev0
scikit-learn 0.23.2

You can see that different versions of the criterion parameter have different values, which can be considered

1. Change the value to the value of the corresponding version, such as’ MSE ‘.

2. Change the version of sklearn directly.

Because the official document says, “MSE” is in V1.0 has been deprecated and will be removed in version 1.2. “Squared_error” is equivalent. Therefore, the method of upgrading sklearn is adopted.

pip install scikit-learn==1.0.1

[Solved] RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at

When we upload our code to the server to run, we encounter the following problems:

THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=50 error=100 : no CUDA-capable device is detected
Traceback (most recent call last):
  File "HyperAttentionDTI_main.py", line 185, in <module>
    model = AttentionDTI(hp).cuda()
  File "/usr/local/lib/python3.7/site-packages/torch/nn/modules/module.py", line 304, in cuda
    return self._apply(lambda t: t.cuda(device))
  File "/usr/local/lib/python3.7/site-packages/torch/nn/modules/module.py", line 201, in _apply
    module._apply(fn)
  File "/usr/local/lib/python3.7/site-packages/torch/nn/modules/module.py", line 223, in _apply
    param_applied = fn(param)
  File "/usr/local/lib/python3.7/site-packages/torch/nn/modules/module.py", line 304, in <lambda>
    return self._apply(lambda t: t.cuda(device))
  File "/usr/local/lib/python3.7/site-packages/torch/cuda/__init__.py", line 197, in _lazy_init
    torch._C._cuda_init()
RuntimeError: cuda runtime error (100) : no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:50

It’s because our graphics card settings are wrong, because we know whether we have a graphics card or not, otherwise we won’t report the wrong graphics card problem

Solution:

Let’s look at the program code we executed and check the CUDA part. I set my graphics card to 6. We don’t have so many graphics cards to use. I checked the location of my graphics card, which is No. 0. Therefore, we set the first line of the following code to 0!

os.environ["CUDA_VISIBLE_DEVICES"] = "6"
if __name__ == "__main__":
    """select seed"""
    SEED = 1234
    random.seed(SEED)
    torch.manual_seed(SEED)
    torch.cuda.manual_seed_all(SEED)
    # torch.backends.cudnn.deterministic = True

[Solved] main.py: error: the following arguments are required:

Error “main. Py: error: the following arguments are required:”

1. Check the error message first

As shown in the figure below,
main.py: error: the following arguments are required: -- task, -- dataset, -- param
generally speaking, the three parameters I set task, dataset, param have problems
find the place where I set the parameters and find that these three parameters have the attribute required=True

parser.add_argument("--task", default='uabsa', type=str, required=True,
                    help="The name of the task, selected from: [uabsa, aste, tasd, aope]")
parser.add_argument("--dataset", default='rest14', type=str, required=True,
                    help="The name of the dataset, selected from: [laptop14, rest14, rest15, rest16]")
parser.add_argument("--model_name_or_path", default='t5-base', type=str,
                    help="Path to pre-trained model or shortcut name")
parser.add_argument("--paradigm", default='annotation', type=str, required=True,
                    help="The way to construct target sentence, selected from: [annotation, extraction]")

2. Solutions

Method 1:

1.Run–> Edit Configurations

2. main.py (corresponding error report file), fill in the corresponding -- task "uabsa" -- dataset "rest14" -- param "Annotation", here are the error report parameters and the corresponding default values
for example, here — the default of task is “uabsa”, note: it is double quotation marks instead of single quotation marks, and there may be problems with single quotation marks Click OK after filling in.

Method 2: if method 1 and other methods do not work (simple, but not recommended)

Find the set generation of three variables and delete required=True in the code.
initially

parser.add_argument("--task", default='uabsa', type=str, required=True,
                    help="The name of the task, selected from: [uabsa, aste, tasd, aope]")
parser.add_argument("--dataset", default='rest14', type=str, required=True,
                    help="The name of the dataset, selected from: [laptop14, rest14, rest15, rest16]")
parser.add_argument("--model_name_or_path", default='t5-base', type=str,
                    help="Path to pre-trained model or shortcut name")
parser.add_argument("--paradigm", default='annotation', type=str, required=True,
                    help="The way to construct target sentence, selected from: [annotation, extraction]")

After deletion

parser.add_argument("--task", default='uabsa', type=str,
                    help="The name of the task, selected from: [uabsa, aste, tasd, aope]")
parser.add_argument("--dataset", default='rest14', type=str, 
                    help="The name of the dataset, selected from: [laptop14, rest14, rest15, rest16]")
parser.add_argument("--model_name_or_path", default='t5-base', type=str,
                    help="Path to pre-trained model or shortcut name")
parser.add_argument("--paradigm", default='annotation', type=str,
                    help="The way to construct target sentence, selected from: [annotation, extraction]")

[Solved] uiautomatorviewer Error: Error obtaining UI hierarchy

1. Problem reappearance: when learning appium framework and using uiautomatorviewer to locate Android App controls, directly selecting [device screenshot] will report an error:

2. Solution:

Create a new bat file with the following contents:

adb shell uiautomator dump /sdcard/screen.uix
adb pull /sdcard/screen.uix D:/uiscreen/screen.uix
adb shell screencap -p /sdcard/screen.png
adb pull /sdcard/screen.png D:/uiscreen/screen.png

In fact, these commands can also be directly input in CMD, but they need to be input every time, which is more troublesome. All commands can be written into bat files and run directly to obtain interface information.

3. Select the path of the picture and uix file in uiautomatorviewer:

My frame is too small. I can’t click the path of the second uix at all. The solution is to press the tab key, locate the button to select the file, and then enter can select it normally.

4. Then you can load the interface and locate the elements normally.