Category Archives: Python

[Solved] Pygame Install Error: Command errored out with exit status 255: hg clone –noupdate -q https://bitbucket.o

report errors:

ERROR: Command errored out with exit status 255: hg clone –noupdate -q https://bitbucket.org/pygame/pygame /private/var/folders/jt/s0hr2mwx2f91p9xjm0r09vqr0000gn/T/pip-req-build-17brj_ kp Check the logs for full command output.

context:

Learn Python Programming: from introduction to practice. When you start the example practice in Chapter 12, you need to install the pyGame environment. You always report errors according to the methods in the book and cannot install normally.

terms of settlement:

Do not use the method in the book:
PIP3 install — user Hg+ https://bitbucket.org/pygame/pygame

Direct use

pip3 install pygame

I’m really good at installing it successfully

[Solved] Can’t reconnect until invalid transaction is rolled back

The reason is that there is no call

session.rollback()

Solution:

@contextmanager
    def session_scope(self):
        self.db_engine = create_engine(self.db_config, pool_pre_ping=True) # echo=True if needed to see background SQL        
        Session = sessionmaker(bind=self.db_engine)
        session = Session()
        try:
            # this is where the "work" happens!
            yield session
            # always commit changes!
            session.commit()
        except:
            # if any kind of exception occurs, rollback transaction
            session.rollback()
            raise
        finally:
            session.close()

Another form:

        try:
        	......
            ......
            ......
            ......
        except Exception:
            import traceback
            traceback.print_exc()
            db.session.rollback()
            pass
        finally:
            db.session.close()
            pass

[Solved] Error: [email protected]: wrong number of arguments (given 1, expected 0)

First, let’s talk about the problems I encountered. Brew install & lt; formula> Error reporting:

(venv_mac)  haypin@HaypinsMBP  /usr/local/Cellar  brew install cmake
Error: [email protected]: wrong number of arguments (given 1, expected 0)

Even if I quit the previous virtual environment, I opened the debugging information and found:

(venv_mac)  ✘ haypin@HaypinsMBP  /usr/local/Cellar  brew install --debug cmake
/usr/local/Homebrew/Library/Homebrew/brew.rb (Formulary::FormulaLoader): loading /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/Formula/sphinx-doc.rb
/usr/local/Homebrew/Library/Homebrew/brew.rb (Formulary::FormulaLoader): loading /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/Formula/[email protected]
Error: [email protected]: wrong number of arguments (given 1, expected 0)

Executable/usr/local/homebrew/library/homebrew/brew.rb (formulary:: formulaloader): always loading/usr/local/homebrew/library/taps/homebrew/homebrew core/formula/ [email protected] , which reports an error Python 3.9 parameter transfer error.

It is said on the Internet that brew install cmake can solve the problem, but I still report this error on the premise that cmake has been installed. There is no way but to reinstall homebrew and hope for a new homebrew core/ [email protected] It can be executed normally

(venv_mac)  ✘ haypin@HaypinsMBP  /usr/local/Cellar  /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
Warning: The Ruby Homebrew uninstaller is now deprecated and has been rewritten in
Bash. Please migrate to the following command:
  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/uninstall.sh)"

^C

It is found that the script for uninstalling homebrew has expired. It is recommended to use:

/bin/bash -c “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/uninstall.sh )”

Then use this:

(venv_mac)  ✘ haypin@HaypinsMBP  /usr/local/Cellar  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/uninstall.sh)"
Warning: This script will remove:
/Users/haypin/Library/Caches/Homebrew/
/Users/haypin/Library/Logs/Homebrew/
/usr/local/Caskroom/
/usr/local/Cellar/
/usr/local/bin/brew -> /usr/local/bin/brew
Are you sure you want to uninstall Homebrew?This will remove your installed packages! [y/N] y
==> Removing Homebrew installation...
Warning: Failed to delete /usr/local/Caskroom
rm: /usr/local/Caskroom: Permission denied
Warning: Failed to delete /usr/local/Cellar
rm: /usr/local/Cellar: Permission denied
==> Removing empty directories...
==> /usr/bin/sudo /usr/bin/find /usr/local/bin /usr/local/etc /usr/local/include /usr/local/lib /usr/local/opt /usr/local/sbin /usr/local/share /usr/local/var /usr/local/Caskroom /usr/local/Cellar /usr/local/Homebrew /usr/local/Frameworks -name .DS_Store -delete
==> /usr/bin/sudo /usr/bin/find /usr/local/bin /usr/local/etc /usr/local/include /usr/local/lib /usr/local/opt /usr/local/sbin /usr/local/share /usr/local/var /usr/local/Caskroom /usr/local/Cellar /usr/local/Homebrew /usr/local/Frameworks -depth -type d -empty -exec rmdir {} ;
==> Homebrew uninstalled!
The following possible Homebrew files were not deleted:
/usr/local/.com.apple.installer.keep
/usr/local/Frameworks/
/usr/local/Homebrew/
/usr/local/bin/
/usr/local/etc/
/usr/local/go/
/usr/local/include/
/usr/local/lib/
/usr/local/mysql -> /usr/local/mysql
/usr/local/mysql-8.0.21-macos10.15-x86_64/
/usr/local/opt/
/usr/local/sbin/
/usr/local/share/
/usr/local/var/
You may wish to remove them yourself.

I didn’t use sudo, so/usr/local/cashroom and/usr/local/cell were not deleted. I forgot that CWD was in/usr/local/cell. Finally, I prompted that a possible homebrw file had not been deleted, so I deleted it manually:

(venv_mac)  ✘ haypin@HaypinsMBP  /usr/local  sudo rm -r Homebrew

Then reinstall homebrew according to the latest installation script on the official website:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

This is the installation script of the official website. It uses foreign sources. The download speed is very slow and may fail. Just execute it a few more times. The domestic sources are very unfriendly when upgrading brew later. The error I reported in Python 3.9 this time is homebrew 2.4.9. Even if brew update is still 2.4.9, it will not be upgraded to the latest 3.2.0, so although slow down, I still want to use foreign sources.

Zshrc reports an error after changing the Tsinghua source:

(venv_mac)  haypin@HaypinsMBP  ~/cmake_tutorial  source ~/.zshrc
compinit:503: no such file or directory: /usr/local/share/zsh/site-functions/_brew_cask

 

Then I found that the cmake official website has a DMG installation package that can be installed to/applications, so I downloaded and installed it from the cmake official website. If there is a need to upgrade later, I will directly the whole RM – R  / Applications/cmake.app and then download the latest cmake-3.21.0-macos-universal.dmg installation. Of course, add the path/applications/cmake.app/contents/bin/ to the path.

I was frightened by the mistake reported by the brew install cmake. In the future, the software that I can download from the official website will go to the official website.

[Solved] ValueError: Connection error, and we cannot find the requested files in the cached path…

error:

self.tokenizer = CamembertTokenizer.from_pretrained(“camembert-base”)
resolved_vocab_files[file_id] = cached_path(
output_path = get_from_cache(
raise ValueError(
ValueError: Connection error, and we cannot find the requested files in the cached path. Please try again or make sure your Internet connection is on.

Solution.
When running the command line type

TRANSFORMERS_OFFLINE=1  python test.py
sh file is:
TRANSFORMERS_OFFLINE=1  \ python test.py

When running the code
Refer to the official website at
Reason for error reporting.

Firewalled environments
Some cloud and intranet setups have their GPU instances firewalled to the outside world, so if your script is trying to download model weights or datasets it will first hang and then timeout with an error message like:
ValueError: Connection error, and we cannot find the requested files in the cached path.
Please try again or make sure your Internet connection is on.
One possible solution in this situation is to use the “offline-mode”.

Solution: Offline mode

It’s possible to run 🤗 Transformers in a firewalled or a no-network environment.
Setting environment variable TRANSFORMERS_OFFLINE=1 will tell 🤗 Transformers to use local files only and will not try to look things up.
Most likely you may want to couple this with HF_DATASETS_OFFLINE=1 that performs the same for 🤗 Datasets if you’re using the latter.

Sns.distplot Error: ‘Rectangle‘ object has no property ‘normed‘” [How to Solve]

Problem Description:
rectangular ‘object has no property’ normalized ‘in seaborn.distplot, but the normalized parameter is not used
reason:
the normalized parameter has been deprecated. The hist () histogram is built into plot, and the normalized parameter is the default parameter of hist
solution:
in Anaconda – > lib–> site-packages-> seaborn–> In distributions.py, change
hist around line 214 of the file_ kws.setdefault("normed", norm_ Hist)
is hist_ kws.setdefault("density", norm_ Hist)
restart

Python environment error, bad interpreter: there is no file or directory

[xxxx@gs-server-7214 ~]$ /opt/anaconda3/bin/jupyter notebook
-bash: /opt/anaconda3/bin/jupyter: /opt/anaconda3/bin/python: Bad interpreter: No that file or directory
[xxxx@gs-server-7214 ~]$ /opt/anaconda3/bin/python3
Python 3.6.10 |Anaconda, Inc.| (default, May  8 2020, 02:54:21)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
[1]+  Stop               /opt/anaconda3/bin/python3

    1. create a soft connection
    1. Jupiter has been installed through

/opt/anaconda3/bin/python3 - M PIP install Jupiter

    1. , and python can also be started under the full path, but the error is reported as above when starting Jupiter under the full path. The reason is that the default interpreter path of anaconda is/opt/anaconda3/bin/python, but there is no such file, Create a soft connection Python to point to the actual interpreter Python 3.6, as follows

- & gt</ Code> indicates soft connection </ OL>

[xxxx@gs-server-7214 bin]$ ll |grep python
-rwxrwxr-x 1 root root      237 10月 24 2019 ipython
-rwxrwxr-x 1 root root      237 10月 24 2019 ipython3
lrwxrwxrwx 1 root root        9 7月  16 16:31 python -> python3.6
lrwxrwxrwx 1 root root        9 8月  28 2020 python3 -> python3.6
-rwxrwxr-x 1 root root 11947112 5月   8 2020 python3.6
lrwxrwxrwx 1 root root       17 8月  28 2020 python3.6-config -> python3.6m-config
lrwxrwxrwx 1 root root        9 8月  28 2020 python3.6m -> python3.6
-rwxrwxr-x 1 root root     3477 8月  28 2020 python3.6m-config
lrwxrwxrwx 1 root root       17 8月  28 2020 python3-config -> python3.6m-config

2. Set the environment variable
and modify the . Bash in your user directory_ Profile file, add environment variable, export path =/opt/anaconda3/bin: $path , colon is separatorsource .bash_ Profile makes the environment variable effective, so you can start jupyter by directly entering jupyter notebook in your user directory.

[Solved] Selenium error: staleelementreferenceexception exception

StaleElementReferenceException

Problem reporting and solution

Problem reporting error

# clcik to the next page
web.find_element_by_xpath('//*[@id="nexthehe"]').click()

the element is no longer attached to the DOM : the element is no longer attached to the dom

Solution:

The element is no longer attached to the dom

Analyze the cause

It is possible that elements that are no longer attached to the DOM tree are guided (for example, document. Documentelement)

But the page content is not loaded and cannot be found

resolvent:

Still, looking for the element again

try:
    # clcik to the next page
    web.find_element_by_xpath('//*[@id="nexthehe"]').click()
    # time.sleep(1)
except Exception:
    print('failed to next page')
    web.find_element_by_xpath('//*[@id="nexthehe"]').click()

Python Redis: How to batch fuzzy Delete Keys

The method is as follows:

    # redis connection, chain refers to the test environment Redis environment
    r = redis.Redis(host='localhost', port=7622, db=0, decode_responses=True)

    item_list = r.keys(pattern='*app_access##qa_press_test*')
    
    # need to determine if there is a matching value, if not, it will report an error, so need to determine the processing
    if len(item_list):
        # Batch delete all cached application keys
        r.delete(*r.keys(pattern='app_access*'))
        logger.info("clear success...")
    else:
        logger.warn("with no data need to delete...")

PS: there is a detail to note here, that is, deleting directly without matching data will report an error, which needs to be handled

Note: conn.keys (‘test ‘) returns a list matching the corresponding pattern. Through the * sign, you can see that the parameters in the delete () method use variable parameters, that is, you can pass in a variable number of key values and delete them all.

[Solved] RuntimeError: No application found. Either work inside a view function or push an application contex

Python + Flash + Flash Sqlalchemy to realize MySQL database operation

Write test cases in Python to realize MySQL query

The test cases are as follows:

class MySQLTest(unittest.TestCase):

  def test_queryAll(self):
      uas = db.session.query(UserAgent).all()
      self.assertIsNotNone(uas)

      for ua in uas:
        print("\n")
        print(ua)


if __name__ == '__main__':
  unittest.main()

1、 Problem description

Error message below

RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

If no application is found, either work in the view function or push the application context

The first reaction should be related to writing test cases in Java Web applications, and the application context cannot be found


2、 Problem analysis

The test case starts a thread to execute database operation separately, which is independent of the flash application. It is unable to obtain the configuration information of the flash application context (including database connection information), so it is necessary to push the application context (inject context object)

This is why it works in the view function, which runs in the web container of flash.


3、 Solution

Python uses the with statement to manage context

The with statement is essentially context management
1. Context management protocol. Inclusion method__ enter__() And exit (), which support the protocol object to implement these two methods
2. The context manager defines the runtime context to be established when executing the with statement, and is responsible for executing the entry and exit operations in the context of the with statement block
3. Execute when entering the context__ enter__ Method. If the as var statement is set, the VaR variable accepts__ enter__() Method returns a value
4. If an exception occurs during runtime, exit the context manager. Call manager__ exit__ method.

Push the application context, that is, at the top where the thread starts executing code,
add with app.app_ context():

class MySQLTest(unittest.TestCase):

  def test_queryAll(self):
    with app.app_context():
      uas = db.session.query(UserAgent).all()
      self.assertIsNotNone(uas)

      for ua in uas:
        print("\n")
        print(ua)


if __name__ == '__main__':
  unittest.main()

4、 Result verification

Add with app.app_Context():
just write your own program logic, and the test case runs successfully

Python 2.7: How to Install PIP

Python2 is no longer supported after PIP 2.1. Here you can use scripts to automatically download the highest supported version of PIP

1. Python2.7 the latest version of PIP installation file get-pip.py can be obtained by streaming

2. Install the file through Python 2.7

In the scripts folder, execute the following command to pull the get-pip.py file

curl https://bootstrap.pypa.io/pip/2.7/get-pip.py -o get-pip.py

After downloading, execute the file to install the latest version of PIP supported by python2.7

python get-pip.py

You can see that the PIP version of automatic installation is 20.3

.4