How to get python script directory in Spyder?

The script below find the get the script directory in Spyder and set it to current working directory.

The code relies on the internal variable “_ih” and “_i1” spyder uses when running code inside the editor. They stores the cell number and the script filepath to run it in the console.

The if statement can be used to check if “_i1” has been defined to avoid an error running the script outside spyder.

import os
if '_ih' in vars() or '_ih' in globals():
    script_path = _ih[-1].split("'")[1]
    wdir = os.path.dirname(script_path)
    os.chdir(wdir)
elif '_i1' in vars() or '_i1' in globals():
    script_path = _i1.split("'")[1]
    wdir = os.path.dirname(script_path)
    os.chdir(wdir)

How to fix: Moviepy Error “AttributeError: ‘NoneType’ object has no attribute ‘stdout'”

Moviepy is a good library for editing videos on python. But it seems like there are few bugs with the library. One of them is associated with the audioclip.subclip method:

Name of Error: “AttributeError: ‘NoneType’ object has no attribute ‘stdout'”

To fix the error:

Solution 1: Upgrade the moviepy library to version 1.0.3

  • Open terminal
  • Type pip install moviepy –upgrade

Solution2: Update the source code of AudioFileClip.py

  1. Make sure you have moviepy version 1.0.1
  2. go to the moviepy directory:
    cd /usr/local/lib/python3.7/dist-packages/moviepy/
  3. edit the AudioFileClip class at line 93
  4. comment these lines:
    # def __del__(self):
    # self.close()

Reference from: https://github.com/Zulko/moviepy/issues/938

How to fix: “Could not import the PyAudio C module ‘_portaudio'”

When running PyAudio the first time, you may encounter the following error:

Could not import the PyAudio C module ‘_portaudio’.
Traceback (most recent call last):

File “generate_sine.py”, line 7, in
import pyaudio

File “pyaudio.py”, line 116, in
import _portaudio as pa

ImportError: DLL load failed: The specified module could not be found.

It seems that this is caused by failure to install the all the dependencies.

To fix this: install portaudio with the following line:

conda install -c anaconda portaudio

How to apply gradient color to matplotlib graphs with colormap?

Matplotlib in python offers some useful tools for plotting with gradient colors. Below is a script that plot a sine wave with gradient color based on its y-value. It shows the use of matplotlib.cm.get_cmap to obtain a color map and the use of matplotlib.colors.Normalize to convert a value to the gradient index used for cmap.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import Normalize


X = np.linspace(0, 10, 101)
Y = 10*np.sin(x)

cmap = cm.get_cmap('Blues', len(y))
norm = Normalize(vmin=np.min(Y),vmax=np.max(Y))

for i in range(len(X)-1):
    plt.plot(X[i:i+2], Y[i:i+2], color=cmap(norm(Y[i])))

plt.legend()
plt.grid()
plt.xlabel("x")
plt.ylabel("y")

A more comprehensive list of colormaps can be found in the matplotlib site: https://matplotlib.org/3.3.2/tutorials/colors/colormaps.html

How to fix: League of Legends high ping and ping spikes?

Sometimes, the service provider may route your traffic through an efficient path to league of legend server and that may add additional pings and ping spikes to your game.

To fix this, you can try using a VPN server that is specifically designed to optimize your gaming experience (eg. Express VPN). However, before you reach the VPN server, the traffic is still determined by your internet provider. If using a VPN server still doesn’t work, maybe your best option is to switch to a better internet provider.

How to: split PDFs into pages with pyPDF2 (writing your own PDF splitter)

The function below uses pyPDF2 to split pages in a pdf file into separate PDFs by given a path to the master PDF file.

import os
from PyPDF2 import PdfFileReader, PdfFileWriter

def pdf_splitter(path):
    fname = os.path.splitext(os.path.basename(path))[0]
 
    pdf = PdfFileReader(path)
    for page in range(pdf.getNumPages()):
        pdf_writer = PdfFileWriter()
        pdf_writer.addPage(pdf.getPage(page))
 
        output_filename = '{}_page_{}.pdf'.format(
            fname, page+1)
 
        with open(output_filename, 'wb') as out:
            pdf_writer.write(out)
 
        print('Created: {}'.format(output_filename))