Category Archives: Python

[Solved] Error: Please select a valid Python interpreter

Before that

First download Python and configure environment variables

Win11python download and environment variable configuration

Text

Reference link:
Python learning notes – error: Please select a valid Python interpreter

Question

The following error occurs when running: Please select a valid Python interpreter
the English meaning of this sentence: “please select a valid Python interpreter”

In fact, it’s because you just downloaded pychar, and you haven’t done its basic configuration yet. The error is normal ~

Solution:

First, Download python (again)

Open the DOS command line window,

ah, with ~

Then, the parser selects the problem, opens settings (Ctrl + Alt + s) or file & gt; settings, and opens the configuration box, as shown in the following figure:

Just follow the steps:

The results are shown in the figure below:

Then you can!

[Solved] AttributeError: ‘DataFrame‘ object has no attribute ‘tolist‘

 

solve the problem

return object.__getattribute__(self, name)
AttributeError: ‘DataFrame’ object has no attribute ‘tolist’

Solution ideas

Property error: ‘dataframe’ object does not have property ‘tolist’

Solution:

Remember that DataFrame does not have a tolist() method, but series.Series has a tolist() method, so it needs to be modified

take

import pandas as pd

#Read xls file
file_path='data/test1226.xls'
data_frame_xls=pd.read_excel(file_path)
data_df01 = data_frame_xls[['age']]
print(type(data_df01))
print(res)

Change to

import pandas as pd

#Read xls file
file_path='data/test1226.xls'
data_frame_xls=pd.read_excel(file_path)
data_df01 = data_frame_xls[['age']]
print(type(data_df01))

data_df01 = data_frame_xls['age']
print(type(data_df01 ))
res = data_df01 .tolist()
print(res)

Ha ha, it’s done!

[Solved] Pyg load dataset Error: attributeerror [pytorch geometry]

AttributeError: ‘GlobalStorage’ object has no attribute ‘train_mask’ Solution

 def create_masks(data):
    """
    Splits data into training, validation, and test splits in a stratified manner if
    it is not already splitted. Each split is associated with a mask vector, which
    specifies the indices for that split. The data will be modified in-place
    :param data: Data object
    :return: The modified data
    """
    if not hasattr(data, "val_mask"):

        data.train_mask = data.dev_mask = data.test_mask = None

        for i in range(20):
            labels = data.y.numpy()
            dev_size = int(labels.shape[0] * 0.1)
            test_size = int(labels.shape[0] * 0.8)

            perm = np.random.permutation(labels.shape[0])
            test_index = perm[:test_size]
            dev_index = perm[test_size:test_size + dev_size]

            data_index = np.arange(labels.shape[0])
            test_mask = torch.tensor(np.in1d(data_index, test_index), dtype=torch.bool)
            dev_mask = torch.tensor(np.in1d(data_index, dev_index), dtype=torch.bool)
            train_mask = ~(dev_mask + test_mask)

            test_mask = test_mask.reshape(1, -1)
            dev_mask = dev_mask.reshape(1, -1)
            train_mask = train_mask.reshape(1, -1)


            if data.train_mask is None:
                data.train_mask = train_mask
                data.val_mask = dev_mask
                data.test_mask = test_mask
            else:

                data.train_mask = torch.cat((data.train_mask, train_mask), dim=0)
                data.val_mask = torch.cat((data.val_mask, dev_mask), dim=0)
                data.test_mask = torch.cat((data.test_mask, test_mask), dim=0)

    else:  # in the case of WikiCS
        data.train_mask = data.train_mask.T
        data.val_mask = data.val_mask.T

    return data

AttributeError: 'GlobalStorage' object has no attribute 'train_mask'
Line 33: Change
if data.train_mask is None: to if 'train_mask' not in data:

[Solved] django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.Did you install mysqlclie

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in <module>
    import MySQLdb as Database
ModuleNotFoundError: No module named 'MySQLdb'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/delta/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "/home/delta/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    autoreload.check_errors(django.setup)()
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/delta/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/delta/.local/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
    app_config.import_models()
  File "/home/delta/.local/lib/python3.6/site-packages/django/apps/config.py", line 301, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/delta/.local/lib/python3.6/site-packages/django/contrib/auth/models.py", line 3, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/home/delta/.local/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 48, in <module>
    class AbstractBaseUser(models.Model):
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/models/base.py", line 122, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/models/base.py", line 326, in add_to_class
    value.contribute_to_class(cls, name)
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/models/options.py", line 207, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/connection.py", line 15, in __getattr__
    return getattr(self._connections[self._alias], item)
  File "/home/delta/.local/lib/python3.6/site-packages/django/utils/connection.py", line 62, in __getitem__
    conn = self.create_connection(alias)
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/utils.py", line 204, in create_connection
    backend = load_backend(db['ENGINE'])
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/home/delta/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 20, in <module>
    ) from err
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?

One of the reasons for this error when starting the Django project is:

Because pymysql is not installed or not configured,

Pymysql is not installed. It needs to be built into the environment and executed

import pymysql
pymysql.install_as_MySQLdb()

Done!

[Solved] Error(s) in loading state_dict for GeneratorResNet

**

Error (s) in loading state_dict for GeneratorResNet

**
cause of the problem: check whether we use dataparallel for multi GPU during training. The model generated by this method will automatically add key: module
observe the error message:
you can find that the key values in the model are more modules

Solution:
1. Delete the module

    gentmps=torch.load("./saved_models/generator_%d.pth" % opt.epoch)
    distmps = torch.load("./saved_models/discriminator_%d.pth" % opt.epoch)
    from collections import OrderedDict
    new_gens = OrderedDict()
    new_diss = OrderedDict()
    for k, v in gentmps.items():
        name = k.replace('module.','') # remove 'module.'
        new_gens[name] = v #The value corresponding to the key value of the new dictionary is a one-to-one value.
    for k, v in distmps.items():
        name = k.replace('module.','') # remove 'module.'
        new_diss[name] = v #The value corresponding to the key value of the new dictionary is a one-to-one value.
    generator.load_state_dict(new_gens)
    discriminator.load_state_dict(new_diss)

NameError: name ‘xrange‘ is not defined [How to Solve]

The reason is that my Python version is Python 3.8, while the xrange() function is in Python 2.0 For a function in X, in Python 3, the implementation of range () is the same as that of xrange (), so there is no special xrange (). Therefore, when this problem is encountered, there are two methods to solve it.

Solution:

1: if you want to run the program in Python 3, change all xrange() functions to range().

2: put the program with this problem in Python 2.X version of the environment can be run

[Solved] socketio.exceptions.ConnectionError: OPEN packet not returned by server

Error Messages:
Exception in thread Thread-3:
Traceback (most recent call last):
  File "/home/comz/anaconda3/envs/arcface/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/home/comz/anaconda3/envs/arcface/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "usb_camera.py", line 140, in <lambda>
    Process(target=lambda: asyncio.run(upload_loop())).start()
  File "/home/comz/anaconda3/envs/arcface/lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/home/comz/anaconda3/envs/arcface/lib/python3.7/asyncio/base_events.py", line 587, in run_until_complete
    return future.result()
  File "usb_camera.py", line 51, in upload_loop
    await sio.connect(url)
  File "/home/comz/anaconda3/envs/arcface/lib/python3.7/site-packages/socketio/asyncio_client.py", line 117, in connect
    raise exceptions.ConnectionError(exc.args[0]) from None
socketio.exceptions.ConnectionError: OPEN packet not returned by server

Solution:

pip install python-engineio==3.14.2 python-socketio==4.6.0

[Solved] deepin python Message: unknown error: cannot find Chrome binary

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
try:
   # browser = webdriver.Chrome('Here is the path to chrome')
    s = Service(r"/opt/apps/cn.google.chrome/files/chrome")
    driver = webdriver.Chrome(service=s)
    driver.get('https://www.baidu.com')
except Exception as e:
    print(e)

When running this code, an error is reported. You need to put the chrome file and chromedriver in the same directory

Just add the path