code:
with open("input.csv", "r") as input_file:
    header = input_file.readline()[:-1] #this is to remove trailing '\n'
    header += ",Table exists?"
    output_lines = [header]

    for line in input_file:
         output_lines.append(line[:-1])
         if 'table' in line.split(",")[3]:
             output_lines[-1]+=",table exists"
         else:
             output_lines[-1]+=",No table found"

with open("output.csv", "w") as output_file:
    output_file.write("\n".join(output_lines))

rawDescription: Appending results of an element related if function to the last column of a csv


code:
def tofloat(b16):
  sign = -1 if b16 & 0x8000 else +1
  expo = ( b16 & 0x7C00 ) >> 10
  prec = b16 & 0x03FF
  if expo == 0:
    return sign * (2.0 ** -24) * prec
  elif expo == 0x1F:
    return sign * float('inf')
  prec |= 0x0400
  return sign * (2.0 ** (expo - 25)) * prec

rawDescription: binary16 in Python

description: Binary16 in Python


code:
import subprocess
taskname = '...'
task = 'taskkill /im ' + taskname + ' /f'
subprocess.check_call(task, shell=True)

rawDescription: Ending external programs with Python

description: Ending external programs with Python


code:
l = len(myArray)

#create start and end indices for each slice
slices = ((i * l // 10, (i + 1) * l // 10) for i in xrange(0, 10))

#build (small, big) pairs
pairs = [(myArray[a:b], myArray[:a] + myArray[b:]) for a, b in slices]

for small, big in pairs:
    pass

rawDescription: How to equally partitioning an array into predefined size and loop folding in Python

description: Equally partitioning an array into predefined size and loop folding in Python


code:
mystr = 'abcde'
mystr[1:] # Remove the first
mystr[1:-1] # Remove the first and the last
mystr[2:-2] # Remove the first two and the last two

rawDescription: how do i remove the first characters of a string [python]

description: Remove the first characters of a string [python]


code:
import urllib.request
import urllib.parse
params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
params = params.encode('utf-8')
f = urllib.request.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
print(f.read().decode('utf-8'))

rawDescription: How to click check boxes, put text in text boxes and click buttons using Python 3.x (which does not have the mechanize library)?

description: Click check boxes, put text in text boxes and click buttons using Python 3.x (which does not have the mechanize library)


code:
from random import randint
x = randint(1,100)
print(x) #This is just here for testing
name = str(input("Hello there, my name's Jarvis. What's your name?"))
print("Hello there ",name," good to see you!")
attempt = 1
not_found = True
while not_found:
    num = int(input("I'm thinking of a number between 1 and 100. can you guess which one it is?"))
    if num == x:
        print("Good job! it took you ",attempt," tries!")
        not_found = False
    elif num > x: #Don't need the equals
        print("Too high!")
    elif num < x: #Don't need the equals
        print("Too low!")
    else:
        print("ERROR MESSAGE!")
    attempt = attempt + 1

rawDescription: While loop for the script below

description: While loop for the script below


code:
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.art3d as art3d
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')

N = 100
theta = np.linspace(0, 2*np.pi, N, endpoint=False)
x = np.cos(theta)
y = np.sin(theta)
z = range(N)
for xi, yi, zi in zip(x, y, z):
    line=art3d.Line3D(*zip((xi, yi, 0), (xi, yi, zi)), marker='o', markevery=(1, 1))
    ax.add_line(line)
ax.set_xlim3d(-1, 1)
ax.set_ylim3d(-1, 1)
ax.set_zlim3d(0, N)
plt.show()

rawDescription: Is there a matplotlib counterpart of Matlab "stem3"?


code: body.append(paragraph([('This is italic text', 'i')]))

rawDescription: Trying to use the docx.py project written by olebole and having no luck


code:
import sys
script_path = "otherscript.py"
old_argv, sys.argv = sys.argv,[script_path, "arg1", "arg2"]
namespace = dict(globals())
if globals() is not locals():
    namespace.update(locals())
with open(script_path, 'r') as infile:
    exec(compile(infile.read(), script_path, 'exec'), namespace)
sys.argv = old_argv

rawDescription: What is the best way in Python to execute a script while maintaining namespace and passing args


code:
import skflow
from sklearn import datasets, metrics

iris = datasets.load_iris()
classifier = skflow.TensorFlowLinearClassifier(n_classes=3)
classifier.fit(iris.data, iris.target)
score = metrics.accuracy_score(classifier.predict(iris.data), iris.target)
print("Accuracy: %f" % score)

rawDescription: Classification with CNN/LSTM/RNN

description: Classification with CNN/LSTM/RNN


rawDescription: How to display items in a list in a label using tkinter

description: Display items in a list in a label using tkinter


code:
import sqlite3
def create_insert_string(table_name,input_dictionary,conn_db):
    #validate connection
    c = conn_db.cursor()
    #Check if the table is existing in the database if not throw error
    table_exist=c.execute('SELECT COUNT(*) FROM sqlite_master WHERE type=\'table\' AND name=\''+table_name+'\'');
    if table_exist.fetchone()[0]==0:
        return 'Error'
    insert_str = 'INSERT INTO '+table_name+' ( '
    count=0;
    for keys in input_dictionary.keys():
        if count == 0:
           insert_str=insert_str+ ' '+keys
        else:
           insert_str=insert_str+ ', '+keys
        count=count+1
    count=0;
    insert_str=insert_str+' ) VALUES ( '
    for keys in input_dictionary.keys():
        if count == 0:
           insert_str=insert_str+ ' :'+keys
        else:
           insert_str=insert_str+ ', :'+keys
        count=count+1
    insert_str=insert_str+' )'
    return insert_str
# Main Program
conn = sqlite3.connect('C:\\PYTHON_SCRIPTS\\test.db')
dict={'column1':'value1','column2':'value2'}
insert_string=create_insert_string('test',dict,conn)
print(insert_string)
c = conn.cursor()
c.execute(insert_string,dict)
conn.commit()
c.close()

rawDescription: python sqlite insert libraries of varying size into table

description: Python sqlite insert libraries of varying size into table


rawDescription: How can I select 2 different random rows from a table?

description: Select 2 different random rows from a table


code:
import storm

class SplitSentenceBolt(storm.BasicBolt):
    def process(self, tup):
        words = tup.values[0].split(" ")
        for word in words:
          storm.emit([word])

SplitSentenceBolt().run()

rawDescription: How to call script on tuple in shellbolt

description: Call script on tuple in shellbolt


code:
with open('/path/to/src.py', 'rb') as f:
    for five_tuple in tokenize.tokenize(f.readline):
        print(five_tuple.type)
        print(five_tuple.string)
        print(five_tuple.start)
        print(five_tuple.end)
        print(five_tuple.line)

rawDescription: Tokenize python source code examples (in Python)


code:
for row in board:
    print(row)

rawDescription: rows in battleship 5x5 grid not displaying accurately

description: Rows in battleship 5x5 grid not displaying accurately


code:
import pyinotify,subprocess
def onChange(ev):
    cmd = ['/bin/echo', 'File', ev.pathname, 'changed']
    subprocess.Popen(cmd).communicate()
wm = pyinotify.WatchManager()
wm.add_watch('file.watched', pyinotify.IN_MODIFY, onChange)
notifier = pyinotify.Notifier(wm)
notifier.loop()

rawDescription: how to make pyinotify to run a program on any modification over a file?

description: Make pyinotify to run a program on any modification over a file


code:
if isinstance(string, six.binary_type):
    string = string.decode('utf-8')

rawDescription: Best way to automatically decode bytes

description: Automatically decode bytes


rawDescription: Traversing 2D line in Numpy?

description: Traversing 2D line in Numpy


code:
from tkinter import *
import random
from tkinter import ttk

main = Tk()
frame = Frame(main)
buttonframe = Frame(frame)
text = Text(main, height=10, width=20)

def complex_password():
    password2 = []
    password2.append(random.choice((captial)))
    count = 0
    x = ""
    while count != 12:
        roll = random.randint(1,4)
        if roll == 1 or roll == 2:
            password2.append(random.choice((letters)))
            count +=1
        if roll == 3 or roll == 4:
            number = random.randint(0,9)
            number = str(number)
            password2.append(number)
            count +=1
        if count == 12:
            password2 = x.join(password2)
            text.insert(INSERT, password2)
            text.insert(INSERT, "\n")

def simple_password():
    y = ""
    password1 = []
    password1.append(random.choice((words)))
    password1.append(random.choice((words)))
    number = random.randint(1,99)
    num = str(number)
    password1.append(num)
    password1 = y.join(password1)
    text.insert(INSERT, password1)
    text.insert(INSERT, "\n")

def clear_text():
    dele = text.delete(1.0, END)

label = Label(frame, text="Password Generator!!")
simple = Button(buttonframe, text="Simple", command=simple_password)
complex = Button(buttonframe, text="Complex", command=complex_password)
clear = Button(buttonframe, text="Clear", command=clear_text)

text.grid(row=2, column=2)
label.grid(row=1, column=2, columnspan=1)
simple.grid(row=2, column=1)
complex.grid(row=2, column=2)
clear.grid(row=2, column=3)
frame.grid(column=2, row=1)
buttonframe.grid(row=2, column=2)

main.configure(bg="blue3")
frame.configure(bg="blue3")

words = ['Dog', 'Cat', 'Mouse', 'Fire', 'Ice', 'Basket', 'Tree', 'Tiger',      'Lion', 'Flash', 'Super', 'Light', 'Zoom',
     'Speed', 'Pants', 'Shirt', 'Hat', 'Suit', 'Berry', 'Yogurt', 'Epic',   'Keyboard', 'Toe', 'Car', 'Truck', 'Bike', 'Motor', 'Hammer', 'Pizza', 'Heart', 'Arm',
     'Joint', 'Sawg', 'New', 'Carrots', 'Baby', 'Kiss', 'Backspace', 'Enter', 'Alt', 'Print', "Down", 'Up', 'Question', 'Rain', 'Forest',
     'Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Purple', 'Brown', 'Black', 'Indigo', 'Grey', 'Shadow', 'Eye', 'Brick', 'Twig',
     'Gangster', 'Thug', 'Chains', 'Gold', 'Silver', 'Bronze', 'Platinum', 'Titanium', 'Exploding', 'Ladybug', 'Grass',
     'Monkey', 'Rhino', 'Comma', 'Hair', 'Shark', 'Fish']
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
captial = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

main.mainloop()

rawDescription: Trouble with formatting Tkinter python 3


code:
a="[u'Sugar', u'Rice', u'Bleach']"
import ast
ast.literal_eval(a)
ast.literal_eval(a)[1]

rawDescription: Parse CSV containing list in a column

description: Parse CSV containing list in a column


code: numpy.logical_and.reduce(d[1:] == d[0])

rawDescription: Element-wise equality in 3-D array with arbitrarily sized axes


code:
import math
def multiplier(x, y):
    dist = x - y
    return 1 + dist/math.sqrt(1+dist**2)

rawDescription: Calculating multiplier based on distance between 2 numbers


code:
import webbrowser
import pyinotify

class ModHandler(pyinotify.ProcessEvent):
    # evt has useful properties, including pathname
    def process_IN_CLOSE_WRITE(self, evt):
            webbrowser.open(URL)

handler = ModHandler()
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm, handler)
wdd = wm.add_watch(FILE, pyinotify.IN_CLOSE_WRITE)
notifier.loop()

rawDescription: How can I "watch" a file for modification / change?


code:
def parse(tokens, i=0):
    """parse: tuple(String) * int -> (Node, int)
    From an infix stream of tokens, and the current index into the
    token stream, construct and return the tree, as a collection of Nodes,
    that represent the expression.

    NOTE:  YOU ARE NOT ALLOWED TO MUTATE 'tokens' (e.g. pop())!!!  YOU
        MUST USE 'i' TO GET THE CURRENT TOKEN OUT OF 'tokens'
    """
    if tokens[i] == '+':
        return mkAddNode(parse(tokens, i+1), parse(tokens, i+1))
    elif tokens[i] == '-':
        return mkSubtractNode(parse(tokens, i+1), parse(tokens, i+1))

rawDescription: Recursive parsing instead of using pop

description: Recursive parsing instead of using pop


code:
for key in ['value', 'value_1', 'value_2']:
    report[key] = data.get(key, None) # or just data.get(key), since None is the default

rawDescription: What's the best possible way to do this kind of dict matching in python?


code:
if(leftHalf[i] < rightHalf[j]):
    alist[k] = leftHalf[j]
    i += 1; k += 1
else:
    alist[k] = rightHalf[j]
    j += 1; k += 1

rawDescription: Unable to reason why the code is not behaving as expected in a simple while loop


code:
triang = tr.Triangulation(x, y)
mask = np.all(np.where(isbad[triang.triangles], True, False), axis=1)
triang.set_mask(mask)
colplt = mp.tricontourf(triang, z)
mp.colorbar()

rawDescription: Set mask for matplotlib tricontourf

description: Set mask for matplotlib tricontourf


code: my_thing = [x for x in things if x[2]=="Blurgle"][0]

rawDescription: Retrieving a tuple from a collection of tuples based on a contained value


code:
def sort_columns(column_list):
    # Create a list of tuples: (question position, column name)
    sort_list = [(int(col.split('_')[2]), col) for col in column_list]

    # Sorts by the first item in each tuple, which is the question position
    sort_list.sort()

    # Return the column names in the sorted order:
    return [x[1] for x in sort_list]

# Now, you should be able to reorder the DataFrame like so:
demo_pivot = demo_pivot.loc[:, sort_columns(demo_pivot.columns)]

rawDescription: Sorting DF by a column with multiple values


code:
df = pd.read_csv(filename, dtype={'emotion':np.int32, 'pixels':str, 'Usage':str})

def makeArray(text):
    return np.fromstring(text,sep=' ')

df['pixels'] = df['pixels'].apply(makeArray)

rawDescription: Read a csv with numpy array using pandas


code:
games = soup.find_all('section', class_='game')

list_of_games = []
for game in games:
    if game.find("div", class_="final") is None:
        continue
    # rest of the code

rawDescription: Beautiful Soup: Only target elements if a specific child has a certain class


code:
import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()

rawDescription: How to unpack 7-Zip.gz (.gz) with Python?

description: Unpack 7-Zip.gz (.gz) with Python


code:
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

#Init data
data = numpy.random.random((10, 10))

#Create plotting frame
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

#Plot data
im = ax1.imshow(data)

#Only required for the small spacing between figure and colorbar
divider = make_axes_locatable(ax1)
cax = divider.append_axes("right", size = "5%", pad = 0.05)

#Set colorbar, including title and padding
cbar = fig.colorbar(im, cax = cax)

cbar_title = "number density"
plt.text(1.2, .5, cbar_title,  fontsize=20, verticalalignment='center', rotation = 90, transform = ax1.transAxes)

fig.tight_layout()

rawDescription: How to keep constant spacing after `tight_layout()`?

description: Keep constant spacing after `tight_layout()`


code:
def censor(text, word):
    length_of_word = len(word)
    word_now_censored = '*' * length_of_word
    wordlist = text.split()
    new_words_list = []
    for item in wordlist:
        if item == word:
            new_words_list.append(word_now_censored)
        else:
            new_words_list.append(item)

    return " ".join(new_words_list)

rawDescription: Codecademy Practice Makes Perfect 10/15 (Word Censoring)


code:
Model._get_collection().aggregate([
    { '$group' :
        { '_id' : { 'carrier' : '$carrierA', 'category' : '$category' },
          'count' : { '$sum' : 1 }
        }
    }
])

rawDescription: Flask-MongoEngine & PyMongo Aggregation Query


code:
# Here are the two data streams.
train_data = tf.Variable(999)
test_data = tf.Variable(1000)

# This selects which stream to use.
select_test = tf.placeholder(dtype=bool,shape=[],name='select_test')
data = tf.cond(
    select_test,
    lambda:test_data,
    lambda:train_data
)

# Here is the model.
model = data-500;

init = tf.initialize_all_variables()
with tf.Session():
    init.run()

    # You just have to feed `select_test` when you evaluate the model.
    print(model.eval({select_test:False})) #499
    print(model.eval({select_test:True})) #500

rawDescription: Feeding tensors for training vs validation data


code: your_new_string = re.sub(r'\[subscript=(.+?)\]', r'<sub>\1</sub>', your_old_string)

rawDescription: Searching for multiple strings

description: Searching for multiple strings


code:
import _io
import io
_io
io
_io.TextIOWrapper

rawDescription: What's the difference between '_io' and 'io'?


rawDescription: Converting from list of tuples to list of lists of tuples


code:
def myPostOrder(root, par=None):
    if root:
        root.parent = par
        myPostOrder(root.left, root)
        myPostOrder(root.right, root)

rawDescription: Update parent pointers in a binary tree

description: Update parent pointers in a binary tree


code:
def hash_test(hasher):
    hasher.update('a hash test'.encode('utf-8'))
    print(hasher.hexdigest())

hashes = {'sha256': hashlib.sha256(), 'sha1': hashlib.sha1()}

hash_type = input('Do you want to try sha1, or sha256?')
hasher = hashes[hash_type]
hash_test(hasher)

rawDescription: How to decrease the code size when there is some same code

description: Decrease the code size when there is some same code


code:
df['epoch']= df.index.map(lambda x: (np.datetime64(pd.to_datetime(x)).astype('uint64')/1e6))
start_epoch = df.epoch.iloc[0]
df['epochdelta']= df['epoch'] - start_epoch
df['newindex'] = pd.to_datetime((df.epochdelta * 3.5 + start_epoch),unit='s')

rawDescription: Python: Rescale time-series in pandas by non-integer scale-factor


code:
send_mail(
    subject,
    message,
    from_email,
    recipient_list,
    fail_silently=False,
    auth_user=None,
    auth_password=None,
    connection=None)

rawDescription: Django sending email

description: Django sending email


code:
if form.is_valid():
    c = form.cleaned_data["category"]
    category = Category.objects.filter(name=c).first()
    if not category:
        category = Category.objects.create(name=c)
    product = form.save(commit=False)
    product.category = category
    product.save()

rawDescription: Django form for a model create object of another model


code:
import pandas as pd
import multiprocessing as mp

LARGE_FILE = "yourfile.csv"
CHUNKSIZE = 100000 # processing 100,000 rows at a time

def process_frame(df):
        # process data frame
        return len(df)

if __name__ == '__main__':
        reader = pd.read_csv(LARGE_FILE, chunksize=CHUNKSIZE)
        pool = mp.Pool(4) # use 4 processes

        funclist = []
        for df in reader:
                # process each data frame
                f = pool.apply_async(process_frame,[df])
                funclist.append(f)

        result = 0
        for f in funclist:
                result += f.get(timeout=10) # timeout in 10 seconds

rawDescription: How can I load a csv file wich is too big in iPython?

description: Load a csv file wich is too big in iPython


code:
import Tkinter as Tk
import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)

# setup 5 output pin
GPIO.setup(11, GPIO.OUT)
# setup 2 output pin
GPIO.setup(14, GPIO.OUT)
# setup 1 output pin
GPIO.setup(15, GPIO.OUT)

# set low output states on start
GPIO.output(11, GPIO.LOW)
GPIO.output(14, GPIO.LOW)
GPIO.output(15, GPIO.LOW)

# setup 5 input pin
GPIO.setup(25, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
# setup 2 input pin
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
# setup 1 input pin
GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)

# setup window toggle pin
GPIO.setup(22, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)

# out functions light certain led a number of times
def fiveTimes_out():
    #1
    GPIO.output(11, GPIO.HIGH)
    time.sleep(0.200)
    GPIO.output(11, GPIO.LOW)
    time.sleep(0.200)
    #2
    GPIO.output(11, GPIO.HIGH)
    time.sleep(0.200)
    GPIO.output(11, GPIO.LOW)
    time.sleep(0.200)
    #3
    GPIO.output(11, GPIO.HIGH)
    time.sleep(0.200)
    GPIO.output(11, GPIO.LOW)
    time.sleep(0.200)
    #4
    GPIO.output(11, GPIO.HIGH)
    time.sleep(0.200)
    GPIO.output(11, GPIO.LOW)
    time.sleep(0.200)
    #5
    GPIO.output(11, GPIO.HIGH)
    time.sleep(0.200)
    GPIO.output(11, GPIO.LOW)
    time.sleep(0.200)

def twoTimes_out():
    #1
    GPIO.output(14, GPIO.HIGH)
    time.sleep(0.200)
    GPIO.output(14, GPIO.LOW)
    time.sleep(0.200)
    #2
    GPIO.output(14, GPIO.HIGH)
    time.sleep(0.200)
    GPIO.output(14, GPIO.LOW)
    time.sleep(0.200)

def oneTimes_out():
    #1
    GPIO.output(15, GPIO.HIGH)
    time.sleep(0.200)
    GPIO.output(15, GPIO.LOW)
    time.sleep(0.200)

########################################################################
class OtherFrame(Tk.Toplevel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        Tk.Toplevel.__init__(self)
        self.geometry("640x480+0+0")
        self.configure(background = 'yellow')

        self.title("otherFrame")

########################################################################
class MyApp(object):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):

        """Constructor"""
        self.root = parent
        self.root.title("Main frame")
        self.frame = Tk.Frame(parent)
        self.frame.pack()

        btn = Tk.Button(self.frame, text = "Other Window", command = self.openFrame)
        btn.pack()

        btn2 = Tk.Button(self.frame, text = "Function test", command = twoTimes_out)
        btn2.pack()

        titleLabel = Tk.Label(text = "My Label")
        titleLabel.place(x = 40, y = 60)

        insertLabel = Tk.Label(text = "Label")
        insertLabel.place(x = 170, y = 110)

        self.log = Tk.Text(state = 'normal', width = 70, height = 10, wrap = 'none')
        self.log.place(x = 40, y = 160)

        thanksLabel = Tk.Label(text = "Thank You!")
        thanksLabel.place(x = 70, y = 350)

        self.log.insert('1.0', 'here is my text to insert')

    #----------------------------------------------------------------------
    def hide(self):
        """"""
        self.root.withdraw()

    #----------------------------------------------------------------------
    def openFrame(self):
        """"""
        self.hide()
        subFrame = OtherFrame()
        handler = lambda: self.onCloseOtherFrame(subFrame)
        btn = Tk.Button(subFrame, text = "Close", command = handler)
        btn.pack()
        secondPageLabel = Tk.Label(text = "HI")
        secondPageLabel.place(x = 170, y = 110)

    #----------------------------------------------------------------------
    def onCloseOtherFrame(self, otherFrame):
        """"""
        otherFrame.destroy()
        self.show()

    #----------------------------------------------------------------------
    def show(self):
        """"""
        self.root.update()
        self.root.deiconify()

    # in functions check if buttons are pushed and run specific functions
    # also write messages to log

    def check_five(self):
        if (GPIO.input(25) == GPIO.HIGH):
            fiveTimes_out()
            self.log.insert('1.0', '5 button down')
        else:
            self.log.insert('1.0', '5 button up')
        root.after(10, self.check_five)

    def check_two(self):
        if (GPIO.input(24) == GPIO.HIGH):
            twoTimes_out()
            self.log.insert('1.0', '2 button down')
        else:
            self.log.insert('1.0', '2 button up')
        root.after(10, self.check_five)

    def check_one(self):
        if (GPIO.input(23) == GPIO.HIGH):
            oneTimes_out()
            self.log.insert('1.0', '1 button down')
        else:
            self.log.insert('1.0', '1 button up')
        root.after(10, self.check_five)

    # check if window toggle button is pushed
    # you reference self in check_toggle, so check_toggle should probably be a method.
    def check_toggle(self):
        if (GPIO.input(22) == GPIO.HIGH):
            self.openFrame()
        root.after(10, check_toggle)

#----------------------------------------------------------------------
if __name__ == "__main__":
    root = Tk.Tk()

    root.geometry("640x480+0+0")
    root.configure(background = 'red')
    app = MyApp(root)
    root.after(10, app.check_five)
    root.after(10, app.check_two)
    root.after(10, app.check_one)
    root.after(10, app.check_toggle)
    root.mainloop()

rawDescription: Tkinter change widgets in a class from external function?


rawDescription: How to draw contour map?

description: Draw contour map


code:
input_tuple = (1,2,3)
instance_1 = InputStuff(*input_tuple)

rawDescription: Pass multiple arguments in form of tuple


code: import sklearn.datasets

rawDescription: How to use "import" in python?

description: Use "import" in python


code:
import re
regex = r'Downstream line rate: (\d\d*) kbps
'
re.search(regex, "Downstream line rate: 6736 kbps
").group(1)

rawDescription: Extracting strings from html file using Python (beautifulsoup?)


code:
class UserModel(Base):
    __tablename__ = "users"

    id = Column(Integer, autoincrement=True, primary_key=True)
    nickname_str = Column(String, unique=True)

    @hybrid_property
    def nickname(self):
        return self.nickname_str or str(self.id)

    @nickname.expression
    def nickname(self):
        return case(
            [(self.nickname_str != None, self.nickname_str)],
            else_=cast(self.id, String)
        ).label('nickname')

    @nickname.setter
    def nickname(self, value):
        self.nickname_str = value

rawDescription: How can I use autoincrementing column value as default value for another not nullable column?

description: Use autoincrementing column value as default value for another not nullable column


code:
def convert(value):
    number, multiplier = value.split()
    if multiplier == 'bytes':
        multiplier = 1
    elif multiplier == 'KB':
        multiplier = 2**10
    elif multiplier == 'MB':
        multiplier = 2**20
    elif multiplier == 'GB':
        multiplier = 2**30
    else:
        raise RuntimeError('Unknown unit %r in %r' % (multiplier, value))

    return float(number) * multiplier

rawDescription: How smart sort in QTablewidget

description: How smart sort in QTablewidget


code:
import math # You need this to perform extra math function, it is already built in

def histogram(lst): # Defining a function
    rounded_list = [(int(math.ceil(i / 10.0)) * 10) for i in lst]
    # Rounding every value to the nearest ten

    d = {} # New dictionary

    for v in xrange(min(rounded_list),max(rounded_list)+10,10):
        d[v] = 0
    # Creating a dictionary with every ten value from minimum to maximum

    for v in rounded_list:
            d[v] += 1
    # Counting all the values

    for i in sorted(list(d.keys())):
        print ("\t".join([str(i),str(d[i])]))
    # Printing the output

a = [10,30,12.5,70,76,90,96,55,44.5,67.8,76,88]

#Calling the function
histogram(a)

rawDescription: Data for Histogram in Python

description: Data for Histogram in Python


code:
BASE_URL = 'link_to_the_page'
for link in br.links(url_regex='/academic/utility/AcademicRecord.jsp?'):
    modified_link = ...
    link.absolute_url = mechanize.urljoin(BASE_URL, modified_link)
    br.follow_link(link)

rawDescription: Changing the link in python mechanize

description: Changing the link in python mechanize


code:
if self.cbo.GetValue() == 'special value':
    self.special_entry = True
else:
    self.special_entry = False

rawDescription: WxPython perform action for a specific choice of ComboBox-Selection


code:
def catalan(n):
    num, div = 1, 1
    for x in range(n + 2, 2*n + 1):
        num *= x
    for x in range(2, n + 1):
        div *= x
    return num / div

rawDescription: Determining time complexity of recursive function


rawDescription: Django MySQL Exact Word Match With iRegex Search


code:
from __future__ import absolute_import
import json #this imports standard lib json
import mypackage.json as my_json #import custom json module

rawDescription: Import default python package that was overwritten by another package with the same name


code:
@pytest.mark.timeout(300)
def test_foo():
   pass

rawDescription: limit the maximum running time for unit test

description: Limit the maximum running time for unit test


rawDescription: getting unique values from a list of dict

description: Getting unique values from a list of dict


rawDescription: How to delete a Parquet file on Spark?

description: Delete a Parquet file on Spark


code:
def select_decorator(select_method):

  def select_wrapper( self , *args, **kwargs):
     intersect = kwargs.has_key('intersect') and kwargs['intersect']
     if intersect:
        # Special init code for intersect == True
        select_method( self , *args , **kwargs)
     else:
        # Normal call path for intersect == False
        select_method( self , *args , **kwargs)
  return select_wrapper

rawDescription: Decorate python method with optional argument


code:
import socket
def bound_socket(*a, **k):
    sock = socket.socket(*a, **k)
    if socket.AF_INET6 in a:
        if not socket.has_ipv6:
            raise ValueError("There's no support for IPV6!")
        else:
            address = [addr for addr in socket.getaddrinfo(source_ip, None)
                        if socket.AF_INET6 == addr[0]] # You ussually want the first one.
            if not address:
                raise ValueError("Couldn't find ipv6 address for source %s" % source_ip)
            sock.bind(address[0][-1])
    else:
        sock.bind((source_ip, 0))
    return sock

rawDescription: Bind IPv6 address to Python socket as source ip address


code:
import re
filename = 'stamped_file_name_085373'
filename = re.sub(r"_\d{6}$", "", filename)
filename

rawDescription: Regular Expression: Remove Time-Stamp from File-Name


code:
import subprocess
import sys

scriptname  = 'foo'
procs = subprocess.check_output(['ps', '-xa']).splitlines()
count = len([l for l in procs if 'python' in l and scriptname in l])
if count > 3:
    sys.exit()

rawDescription: Python process control?

description: Python process control


rawDescription: How to specify the output labels to keras lstm

description: Specify the output labels to keras lstm


code: matches = [a for a in myArray if a in myStr]

rawDescription: Check if string contains more than one element from array in Python


code:
class Octal:
    def __init__(self):
        with open("Number Lists/random_numbers3.txt") as fp:
            self.numberList = map(lambda x:int(x,8), fp)
    def get_list(self):
        return self.numberList

if __name__=="__main__":
    o = Octal()
    print(o.get_list())

rawDescription: Algorithm for converting octal numbers to decimal?


code:
from itertools import tee, izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

for v, w in pairwise(a):
    ...

rawDescription: Iterate through pairs of items in a Python list


code:
ax = plt.gca()
ax.ticklabel_format(useOffset=False)

rawDescription: Matplotlib yaxis range display using absolute values rather than offset values?


code:
import sys

var = None

def set_var(v):
    sys.modules[__name__].var = v

def get_var():
    return var

rawDescription: How to refer to the local module in Python?

description: Refer to the local module in Python


code:
def get_site_content():
    def get_response(response):
        content = response.info()['Content-Type']
        charset = content[content.rfind('=') + 1:] # ugly hack, check orderly
        return response.read().decode(charset)

    cj = http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    data = urllib.parse.urlencode({ "log" : "1", "j_username" : USERNAME, "j_password" : PASSWORD })
    opener.open("url", data)
    data = urllib.parse.urlencode({ "months" : "0" })
    resp = opener.open("url2", data)
    return get_response(resp)

rawDescription: how to publish photos to facebook without using facebook sdk but only by POST to the URL ..?

description: Publish photos to facebook without using facebook sdk but only by POST to the URL ..


code:
s='dasdasdsafs[image : image name : image]vvfd gvdfvg dfvgd'
re.sub(r'\[image.+image\]','',s)

rawDescription: Find and remove a string starting and ending with a specific substring in python


code:
idx = np.random.choice(np.arange(len(x)), 1000, replace=False)
x_sample = x[idx]
y_sample = y[idx]

rawDescription: Python random sample of two arrays, but matching indices


code:
s = "foo bar baz"
l = s.split()
l == ['foo', 'bar', 'baz']
l.insert(2, "qux")
l == ['foo', 'bar', 'qux', 'baz']

rawDescription: Python - why list method returns nothing?


code:
import matplotlib.pyplot as plt

plt.pcolor(data, cmap=plt.cm.OrRd)
plt.yticks(np.arange(0.5,10.5),range(0,10))
plt.xticks(np.arange(0.5,10.5),range(0,10))
plt.colorbar()
plt.gca().invert_yaxis()
plt.gca().set_aspect('equal')
plt.show()

rawDescription: Python Pylab pcolor options for publication quality plots


code: d = date.today() - timedelta(days_to_subtract)

rawDescription: Converting '4 days ago' etc. to the actual dates


code:
def unique(arr):
    index = 0
    s = set()
    for i in range(len(arr)):
        if arr[i] not in s:
            arr[index] = arr[i]
            index += 1
            s.add(arr[i])
    arr[index:] = []

rawDescription: Remove duplicates from array and maintain order - O(n) time and return same reference


code:
import csv
log=open("sync_de.log",'r')
out=open("fn.csv",'w')
csv = csv.writer(out)

#  to store the list
out_list = []

for eachline in log:
   # your code
   if blabla:
      out_list.append([filename, start, end])

# write the csv
csv.writerows(out_list)

rawDescription: BitTorrent Sync log parsing using Python


code:
moduleNames = ['sys', 'os', 're', 'unittest']
moduleNames
modules = map(__import__, moduleNames)

rawDescription: Dynamic module import in Python

description: Dynamic module import in Python


code:
def count_iterable(i):
    return sum(1 for e in i)

rawDescription: Is there any built-in way to get the length of an iterable in python?


code: C = sorted(list(set(B) - set(A)))

rawDescription: Excluding common element from list python


rawDescription: How to make a color from a number

description: Make a color from a number


code:
#!/usr/bin/python2.7

import codecs
import shutil

with codecs.open("input_file.utf8.txt", encoding="utf-8") as input_file:
    with codecs.open(
            "output_file.utf16.txt", "w", encoding="utf-16") as output_file:
        shutil.copyfileobj(input_file, output_file)

rawDescription: Changing encoding in csv file through python UTF-8 to UTF-16


code:
for number in a:
    h = number // 10000
    m = (number // 100) - (h * 100)
    s = number % 100
    t = time(h,m,s)
    # then do whatever you want with t

rawDescription: Python time from a 6 digit number

description: Python time from a 6 digit number


rawDescription: Order Query in Django Model

description: Order Query in Django Model


code:
x = sorted( degree_frequencies.keys( ) )
y = [ degree_frequencies[ k ] for k in x ]
plt.loglog( x, y )

rawDescription: Create loglog plot of histogram data in xy style - python matplotlib


code:
for a_class in list_of_unique_classes:
    y_this_class = (y_all_class==a_class)
    model_to_tune = RandomForestClassifier(random_state=0,class_weight='auto')
    model_tuned = GridSearchCV(model_to_tune, param_grid=params, scoring='f1',n_jobs=2)
    model_tuned.fit( X, y_this_class )

    # Save the best parameters for this class

rawDescription: GridSearchCV for multi-label classification for each label separately


code: regex = re.compile(r'\b(?:%s)\b' % '|'.join(words))

rawDescription: Exact match for words

description: Exact match for words


code: subprocess.check_output(['git', 'diff', '--name-only', currentBranch + '..' + compBranch])

rawDescription: Python: Get a list of changed files between two commits or branches


code:
today = datetime.datetime.now()
next_year = datetime.datetime(year=today.year+1, month=1, day=1)
next_year

rawDescription: Get January 1st of next year

description: Get January 1st of next year


code:
import ctypes
from ctypes import wintypes
import time

user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

# msdn.microsoft.com/en-us/library/dd375731
VK_TAB  = 0x09
VK_MENU = 0x12

# C struct definitions

wintypes.ULONG_PTR = wintypes.WPARAM

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

    def __init__(self, *args, **kwds):
        super(KEYBDINPUT, self).__init__(*args, **kwds)
        # some programs use the scan code even if KEYEVENTF_SCANCODE
        # isn't set in dwFflags, so attempt to map the correct code.
        if not self.dwFlags & KEYEVENTF_UNICODE:
            self.wScan = user32.MapVirtualKeyExW(self.wVk,
                                                 MAPVK_VK_TO_VSC, 0)

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

# Functions

def PressKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode,
                            dwFlags=KEYEVENTF_KEYUP))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def AltTab():
    """Press Alt+Tab and hold Alt key for 2 seconds
    in order to see the overlay.
    """
    PressKey(VK_MENU)   # Alt
    PressKey(VK_TAB)    # Tab
    ReleaseKey(VK_TAB)  # Tab~
    time.sleep(2)
    ReleaseKey(VK_MENU) # Alt~

if __name__ == "__main__":
    AltTab()

rawDescription: Generate keyboard events

description: Generate keyboard events


code:
corners = cv2.cvtColor(thinned, cv2.COLOR_GRAY2BGR)
threshold = 0.1*corners_image.max()
corners [corners_image>threshold] = [0,0,255]
cv2.imshow('corners', corners)

rawDescription: How to properly detect corners using Harris detector with OpenCV?

description: Properly detect corners using Harris detector with OpenCV


code:
bb = np.empty((b.size, 21), dtype=int)
for i,v in enumerate(b):
    bb[i] = v+np.arange(-10,11)

np.delete(a, bb.flat)  # looks like .flat is optional

rawDescription: Creating an array without certain ranges


code:
from mock import patch
import exampleModule

def func():
    ls = []
    exampleModule.send(ls)

with patch('exampleModule.send') as send:
    func()
    assert send.called

rawDescription: Python unit testing functions by using mocks


code: n = int(raw_input())

rawDescription: Text Based RPG Functioning Error?

description: Text Based RPG Functioning Error


code: encodedImage = base64.b64encode(open('path/to/your/image.ext', 'rb').read())

rawDescription: write images to csv files with python

description: Write images to csv files with python


code:
class Player:
   def __init(self):
       self.score=0
   def collision():
      if player_rect.coliderect(baddie_rect):
           self.score +=1

class main():
    player = Player()
    player.collision()
    print(player.score)

rawDescription: Incrementing a score from another class python


code: ['<option value="id=%s+%s">%s - %s</option>' % (x, y, x, y) for x, y in zip(numlist, numlist2)]

rawDescription: Trying to insert variables from two lists into strings - how do I do it?


code: rddstr = rddfloat( (unicode(x[0]), str(x[1]), str(x[2])) )

rawDescription: Pyspark RDD: convert to string

description: Pyspark RDD: convert to string


code:
def solve(k, s, p):
  seat1 = s[0]
  best = -1
  unlucky = (0, -1) # min(accum), position
  accum = 1

  # process all persons between start of the array and the seat #1 position
  for i, pos in enumerate(p):
    if pos <= seat1:
      best = i+1
      accum -= 1
    else:
      break

  if accum < 0:
    unlucky = (accum, 1)

  # process all seats/persons in reverse direction
  i = k
  j = k-1
  while i >= 0 and p[i] > seat1:
    if s[j] >= p[i]: # a seat
      accum += 1
      j -= 1
    else: # a person
      accum -= 1
      i -= 1

    if best == -1 and accum == 0:
      best = i+2 # +1 because indexing starts with 0 & +1 because of pre-decrement

    if accum < unlucky[0]:
      unlucky = (accum, i+2)

  return (best, unlucky[1])

print(solve(3, [2,5,8], [3,4,6,8]))

rawDescription: Time complexity on simulation exercise

description: Time complexity on simulation exercise


code: reader = csv.DictReader(inFile)

rawDescription: Referring to CSV header string to adjust column format


code:
class MyList(list):
  pass

m = MyList((1, 2, 3))
len(m)
m.foo = 42
m.foo

rawDescription: need a simple way to add meta information/class to a python list/tuple variable?

description: Need a simple way to add meta information/class to a python list/tuple variable


code:
def get_context_data(self, **kwargs):
    context = super(sspView, self).get_context_data(**kwargs)
    context['message'] = 'Hello, context!'
    return context

rawDescription: How to pass a variable to template in Django

description: Pass a variable to template in Django


code:
from collections import defaultdict
lis = [['Jan', 'Jim'], ['Feb', 'Maggie'], ['Jan', 'Chris'], ['Sept', 'Joey'],['key', 'value']]
dic = defaultdict(list)
for k, v in lis:
    dic[k].append(v)
dic['Jan']
dic['Feb']
dic['Sept']

rawDescription: Adding elements from a list of lists into dictionary in Python


code:
# Using xor:
not bool(a ^ b)

# Simple substraction:
not bool(a - b)

rawDescription: Determining if two values are equal, without using comparison operators (==, <=, >=, <, >)


code:
import logging
selenium_logger = logging.getLogger('selenium.webdriver.remote.remote_connection')
# Only display possible problems
selenium_logger.setLevel(logging.WARNING)

rawDescription: Turning off logging in Selenium (from Python)


code:
base = 2 # change to change the rate at which you go through the levels
levels = 30
finalPoints = 2000
scale = levels/math.log(finalPoints, base)
level = math.floor(scale*math.log(points, base))

rawDescription: Python ranking algorithm with 30 levels

description: Python ranking algorithm with 30 levels


code:
def f7(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

rawDescription: How do you remove duplicates from a list in Python whilst preserving order?

description: Remove duplicates from a list in Python whilst preserving order


rawDescription: How to convert a binary representation of a string back to the original string in Python?

description: Convert a binary representation of a string back to the original string in Python


code:
def pythagorus(a: int, b: int) -> int:
    """ calculate a**2 + b**2

    ... usage example, etc ...
    """
    return math.sqrt(a**2 + b**2)

rawDescription: Adding help text for Python module in Docstring


code:
import sip
...

class Window(QtGui.QMainWindow):
    ...

    def populateFrame(self):
        self.deleteLayout(self.frame.layout())
        layout = QtGui.QVBoxLayout(self.frame)
        ...

    def deleteLayout(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
                else:
                    self.deleteLayout(item.layout())
            sip.delete(layout)

rawDescription: Remove everything from a frame in pyqt

description: Remove everything from a frame in pyqt


code:
import numpy
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def GaussSum(x,*p):
    n=len(p)/3
    A=p[:n]
    w=p[n:2*n]
    c=p[2*n:3*n]
    y = sum([ A[i]*numpy.exp(-(x-c[i])**2./(2.*(w[i])**2.))/(2*numpy.pi*w[i]**2)**0.5 for i in range(n)])
    return y

params = [1.,1.,-3.]; #parameters for a single gaussian
#params=[1.,1.,1.,2.,-3.,0.]; #parameters for the sum of two gaussians
xdata=numpy.arange(-6,6,0.01)
ydata = numpy.array([GaussSum(x,*params) for x in xdata])

popt,pcov = curve_fit(GaussSum,xdata,ydata,p0=params)

rawDescription: python - curve_fit is seemingly unable to fit sum of gaussians

description: Python - curve_fit is seemingly unable to fit sum of gaussians


code:
class Truc(models.Model):
    name = models.CharField(max_length=50, unique=True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    machin_object = generic.GenericForeignKey('content_type', 'object_id')

rawDescription: Django - Multiple optional ForeignKey

description: Django - Multiple optional ForeignKey


code:
def retrieve_download_path(feed):
    # Read the config files.
    config = configparser.ConfigParser()
    config.read((CONFIG_FILENAME_GLOBAL, CONFIG_FILENAME_USER))

    # Resolve the section (configparser doesn't fallback to DEFAULT if the entire section is missing).
    section = feed if config.has_section(feed) else config.default_section

    # Extract the download path.
    download_path = config.get(section, 'Download directory', fallback='~/Downloads')

    # Expand the user directory.
    return os.path.expanduser(download_path)

rawDescription: Sourcing different config files

description: Sourcing different config files


code: my_array, my_variable = my_function()

rawDescription: Python: Can a function return an array and a variable?


code: self.board = [[self.get_empty_cell() for j in range(width)] for i in range(height)]

rawDescription: When returning dictionaries, does python act like JavaScript?


code:
import matplotlib.pyplot as plt
from numpy.random import rand
import numpy as np

f, axarr = plt.subplots(2, sharex=True)

axarr[0].bar(np.arange(1,11), rand(10), align='center', alpha=0.4)
axarr[1].bar(np.arange(1,11), rand(10), align='center', alpha=0.4)

axarr[1].tick_params(axis='x', pad=30)

plt.setp(plt.xticks()[1], rotation=45)

plt.show()

rawDescription: Rotate x tick labels using subplots

description: Rotate x tick labels using subplots


code:
a = [dict1, dict2, dict3]
b = [dict1, dict2, dict4, dict5, dict6]

c = dicts_from_a_not_in_b = [x for x in a if x not in b]
d = dicts_from_b_not_in_a = [x for x in b if x not in a]

rawDescription: Python - Compare two lists of dict and return dicts from one list


code:
import fileinput
import glob
import sys

for line in fileinput.input(glob.glob('*.mod'), inplace=True):
    sys.stdout.write(line.replace('sit', 'SIT'))
    if fileinput.filelineno() == 32:
        #adds new line and text to line 32
        sys.stdout.write('TextToInsertIntoLine32' '\n')

rawDescription: How to modify all text files in folder with Python Script

description: Modify all text files in folder with Python Script


code:
class Member(models.Model):
  name = models.CharField(max_length=256)
  unit = models.ManyToManyField(Unit, through='Membership')
  unit_denorm = models.ForeignKey(Unit)

class Membership(models.Model):
  member = models.ForeignKey(Member)
  unit = models.ForeignKey(Unit)
  start = models.DateField(default=date.today)
  stop = models.DateField(blank=True, null=True)

  def save(self, *args, **kwargs):
    if not self.stop:
      self.member.unit_denorm = self.unit
      self.member.save()
    super(Membership, self).save(*args, **kwargs)

class Unit(models.Model):
  name = models.CharField(max_length=256)

rawDescription: Putting in extra restrictions when filtering on foreignkey in django-admin


code:
class YourOperator(bpy.types.Operator):
    bl_idname = "youroperatorname"
    bl_label = "Your Operator"

    _updating = False
    _calcs_done = False
    _timer = None

    def do_calcs(self):
        # would be good if you can break up your calcs
        # so when looping over a list, you could do batches
        # of 10 or so by slicing through it.
        # do your calcs here and when finally done
       _calcs_done = True

    def modal(self, context, event):
        if event.type == 'TIMER' and not self._updating:
            self._updating = True
            self.do_calcs()
            self._updating = False
        if _calcs_done:
            self.cancel(context)

        return {'PASS_THROUGH'}

    def execute(self, context):
        context.window_manager.modal_handler_add(self)
        self._updating = False
        self._timer = context.window_manager.event_timer_add(0.5, context.window)
        return {'RUNNING_MODAL'}

    def cancel(self, context):
        context.window_manager.event_timer_remove(self._timer)
        self._timer = None
        return {'CANCELLED'}

rawDescription: Blender Python scripting, trying to prevent UI lock up while doing large calculations


code:
class BooksViewSet(viewsets.ModelViewSet):

    permission_classes = [TokenHasScope]
    required_scopes = ['books']

    def get_queryset(self):
        # Replace this queryset with the books you want to query for.
        # You can use self.request to access parameters.
        return Book.objects.all()

rawDescription: get the request of an authorized client in the API side?

description: Get the request of an authorized client in the API side


rawDescription: How to submit HTTP authentication (Flask BASIC Auth) with Selenium to ChromeDriver

description: Submit HTTP authentication (Flask BASIC Auth) with Selenium to ChromeDriver


인하공업전문대학

formatted_address: 253 Yonghyeon-dong, Nam-gu, Incheon, South Korea

status: OK

rawDescription: Google Maps API: JSON response for location with non-English name


code:
import Tkinter
from Tkinter import *

def decrypt(key, cyphertext):
    # do decryption
    return "Decrypted "+key+cyphertext

def callback(cyphertextEntry, keyEntry, output):
    cyphertext = cyphertextEntry.get()
    key = keyEntry.get()
    decrypted = decrypt(key, cyphertext)
    output.set(decrypted)

top = Tkinter.Tk()
frame1 = Frame(top)
frame1.pack()
frame2 = Frame(top)
frame2.pack()
frame3 = Frame(top)
frame3.pack()
frame4 = Frame(top)
frame4.pack()
L1 = Label(frame1, text="Cypher")
L1.pack(side=LEFT)
E1 = Entry(frame1, bd=5)
E1.pack(side=LEFT)
L2 = Label(frame2, text="Key")
L2.pack(side=LEFT)
E2 = Entry(frame2, bd=5)
E2.pack(side=LEFT)
B1 = Tkinter.Button(frame3, text="Decrypt", command=lambda: callback(E1, E2, v))
B1.pack()
L2 = Label(frame4, text="Output")
L2.pack()
v = StringVar()
L3 = Label(frame4, textvariable=v)
L3.pack(side=LEFT)

top.mainloop()

rawDescription: Adding simple gui to my simple python code


code:
dir_to_serve = os.path.abspath(dir_to_serve) # get full path
if not dir_to_serve.startswith(media_dir): # maybe settings.MEDIA_DIR here?
    return # don't ever serve this

# code to serve from path

rawDescription: Safest and most efficient way retrieve and serve files/images from folder?


code:
proc = subprocess.Popen(["fetch.py", "--cookies=/tmp/tmp-cookies"],
                       stdout=PIPE, stderr=PIPE)
stdout, stderr = proc.communicate()
return stdout

rawDescription: Calling subprocess.call hangs when I set the stdout


code: uuslug(self.title, instance=self, filter_dict={'site': self.site})

rawDescription: Manage slug for django

description: Manage slug for django


code:
sites = hxs.select('//ul/li')
items = []

for site in sites:
    item = Website()
    # this extracts a list, so i guess .extract()[0] is expected
    item['name'] = site.select('a/text()').extract()
    # '//a[...]' maybe you expect that this gets the links within the `site`, but it actually get the links from the entire page; you should use './/a[...]'.
    # And, again, this returns a list, not a single url.
    item['url'] = site.select('//a[contains(@href, "http")]/@href').extract()

rawDescription: How can scrapy crawl more urls?

description: How can scrapy crawl more urls


code:
from PyQt4 import QtGui, QtCore
import sys, os

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    toolButton = QtGui.QToolButton()
    toolButton.setText('Select')
    toolMenu = QtGui.QMenu()
    for i in range(3):
        checkBox = QtGui.QCheckBox(str(i), toolMenu)
        checkableAction = QtGui.QWidgetAction(toolMenu)
        checkableAction.setDefaultWidget(checkBox)
        toolMenu.addAction(checkableAction)
    toolButton.setMenu(toolMenu)
    toolButton.setPopupMode(QtGui.QToolButton.InstantPopup)
    toolButton.show()
    sys.exit(app.exec_())

rawDescription: Keep menu open after clicking on the button it is launched with


code:
def get_email_address():
    #the code to open up a window that gets the email address
    Email = input
    return Email

def get_email_username():
    #the code to open up a window that gets email username
    Email_Username = input
    return Email_Username

#same for the email recipient and email password

def send_email():
    # variables from the other def's
    email_address = get_email_address()
    email_username = get_email_username()

    #code to send email

rawDescription: Calling a variable from one function to another function in Python


code:
doc = doc.decode("utf-8")
print(doc)
tokens = nltk.WordPunctTokenizer().tokenize(doc.decode("utf-8"))
for t in tokens:
    print(t, end=" ")
print()

rawDescription: Something missing with NLTK and tokenize


code:
from sklearn.svm import SVC
def predict(dataset):
    X = ... # features, extract from dataset
    y = ... # labels, extract from dataset
    clf = SVC() # create classifier
    clf.fit(X, y) # train
    return clf

rawDescription: Supervised Machine Learning, producing a trained estimator


rawDescription: What does numpy's percentile function do exactly?


code:
content = [1, 2, 3]
csvfile = "my/file/path"
existing = list(csv.reader(open(csvfile))) if os.path.exists(csvfile) else []
#first you have to read in your existing rows/cols
cols = zip(*existing)
#then you transpose it to get your columns
cols.append(content) #add your new content

with open(csvfile, 'w') as output:
    writer = csv.writer(output, dialect = "excel")
    for item in zip(*cols): #change columns back to rows
        writer.writerow(item)

rawDescription: How to write list to specific location in CSV file?

description: Write list to specific location in CSV file


code:
with open("file1.txt") as f, open("file2.txt") as f1:
    items  = set(line.rstrip() for line in f)
    filtered = [line for line in f1 if "  ".join(line.split()[::4]) in items]
    with open("file2.txt","w") as f3:
        f3.writelines(filtered)

rawDescription: remove uncommon string words in two files

description: Remove uncommon string words in two files


rawDescription: Regular expression to match C's multiline preprocessor statements


code:
import pandas as pd

# Just some values.
df = pd.DataFrame({
    'a': np.random.rand(5),
    'b': np.random.rand(5),
    'c': np.random.rand(5)})

# Now for the plots.

# Plot a values at 1.
plot(df.a, [1] * 5, '+');
# Plot b values at 2.
plot(df.b, [2] * 5, '+');
# Plot c values at 3.
plot(df.c, [3] * 5, '+');
# Ensure extreme points visible.
ylim(0, 4)
# Set the ticks to 'a', 'b', and 'c'.
yticks([1, 2, 3], ['a', 'b', 'c']);

rawDescription: Plotting a scatter plot of a dataframe

description: Plotting a scatter plot of a dataframe


code:
import glob
import os
files = []
for name in os.listdir(args.source):
    if os.path.isdir(name):
        files.append(glob.glob(os.path.join(args.source, name + "/*.proj"))) # match any files ending with .proj

rawDescription: How to look for a specific file in first level directories in Python

description: Look for a specific file in first level directories in Python


code:
def partition(L):
    if len(L) <= 1:
        return [L]

    partitions = [[L[0]] + p for p in partition(L[1:])]
    for i in xrange(1, len(L)):
        partitions.extend([[(L[0], L[i])] + p for p in partition(L[1:i]+L[i+1:])])

    return partitions

rawDescription: python - split a list in pairs and unique elements

description: Python - split a list in pairs and unique elements


code:
import random
num = int(input('Your number: '))
numC = random.randint(1, 100)
tries = 1
lowerLimit=1
upperLimit=100
while numC != num:
  if numC > num:
    print(numC, 'Less')
    upperLimit = numC+1
  else:
    print(numC, 'More')
    lowerLimit = numC-1
  tries += 1
  numC = random.randint(lowerLimit, upperLimit)
print(numC, 'Computer guessed your number with', tries, 'tries')

rawDescription: Rational guessing of a chosen number in a given range


code:
import re

a_pattern = re.compile("query\:(.+?)\,")
re.findall(a_pattern, 'query:text_you_want_to_extract,')

rawDescription: How To Deal With Un-Format Json Data In Python?


rawDescription: Django schedule a "one time" task based on datetime model attribute


code:
import netCDF4
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt

def u_v_components(u,v,angle):
        """ Rotate the u, v vectors from model grid to east/north coords """
        u_east = (np.cos(angle)*u - np.sin(angle)*v)
        v_north = (np.sin(angle)*u + np.cos(angle)*v)
        return u_east, v_north

# Setting the map
scale  = 0.6
width  = 1800000
height = 2300000
lat_0  = 70.8
lon_0  = 25
fig, ax = plt.subplots(figsize = (10, 10))
m = Basemap(width=width*scale,height=height*scale,
        resolution='i',projection='stere',\
        lat_ts=70,lat_0=lat_0,lon_0=lon_0)

m.fillcontinents(color='#aaaaaa',lake_color='#cccccc')
m.drawcountries(linewidth=0.2)
m.drawmapboundary(fill_color='#cccccc')

m.drawparallels(np.arange(-80.,81.,5.),labels=[False,True,True,False])
m.drawmeridians(np.arange(-180.,181.,10.),labels=[True,False,False,True])

dataurl = '/Users/JDMac/norkyst_800m_surfcurr_MAY-JUL_2010_NordNorge_middel.nc'
data = netCDF4.Dataset(dataurl)

# I moved the angle and grid operations out of the loop since they
# only need to be done once.
#angle array in dataset
angle = data.variables['angle'][:,:]

#gridlons and gridlats tell us the lon and lat of each
# point in the grid. This is necessary for drawing on
# the map.
gridlons = data.variables['lon'][:,:]
gridlats = data.variables['lat'][:,:]

X, Y = m(gridlons, gridlats)

YY = np.arange(0, Y.shape[0], 10)
XX = np.arange(0, X.shape[1], 10)
points = np.meshgrid(YY, XX)

#current u-v component [time, depth, lon, lat]
u = data.variables['u'][0,0,:,:]
v = data.variables['v'][0,0,:,:]

#rotate current u-v components from model grid to east-north coordinates
u_east, v_north = u_v_components(u,v,angle)

#pytagoras' theorem to calculate the current velocity and direction
# Calculate speed for time step 0, then maintain this array to
# consistently colorize your vector plot.
speed = np.sqrt(u_east**2 + v_north**2)

# Iterate through the time steps, subsetting the data
# by time step as you go.
# I don't know what the time dimension in your dataset is named,
# so you may have to change it.
for time in range(data.dimensions['time'].size):
    #current u-v component [time, depth, lon, lat]
    u = data.variables['u'][time,0,:,:]
    v = data.variables['v'][time,0,:,:]

    #rotate current u-v components from model grid to east-north coordinates
    u_east, v_north = u_v_components(u,v,angle)

    # Added the cmap kwarg which will define what colormap is
    # used to color the arrows. Depending on your version of
    # matplotlib, jet or viridis is the default if cmap is not specified.
    m.quiver(X[points], Y[points],
                     u_east[points], v_north[points],
                     speed[points],
                     cmap=plt.cm.get_cmap('viridis'))

    # I recommend using the Basemap colorbar method
    # unless for some reason you need more control over all
    # of the colorbar properties. The colorbar method allwos you to
    # manipulate the relative size of the colorbar, the padding
    # between it and the axes, as well as the location on the map.
    cb = m.colorbar(mappable=plt.cgi(),
                       location='right')
    cb.set_label('Strømhastighet i m/s')

    plt.tight_layout()

    # Give each output file a unique filename
    # bbox_inches='tight' will remove as much whitespace as it can
    plt.savefig('current{}.png'.format(time),
                            bbox_inches='tight',
                            dpi = 300)
    # Clear the figure before re-use
    plt.clf()

# Garbage collection should close any open figures and datasets, but
# it's good practice to do so explicitly
plt.close('all')
data.close()

rawDescription: Basemap: save figure with several time-steps and to unique file name


code:
from fnmatch import fnmatch
import os

folder_path = '/home/Desktop/project'
all_files = os.listdir(folder_path)
content_file = 'Hello World'
_date = '20140911'
_pattern = _date + '*'
for file_name in all_files:
    if fnmatch(file_name, _pattern):
        with open(os.path.join(folder_path, file_name), 'wb') as f:
           f.write(content_file)

rawDescription: Python, open a file when the name is not fully known


code:
from collections import defaultdict
blah = defaultdict(list)
for item in db_results:
    blah[item.product_id].append(item)

rawDescription: groupby iterator not adding to list in dictionary comprehension

description: Groupby iterator not adding to list in dictionary comprehension


code:
import wx
import wx.lib.buttons

import SpeedMeter as SM
from math import pi, sqrt

class MyFrame(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "SpeedMeter Demo ;-)",
                         wx.DefaultPosition,
                         size=(400,400),
                         style=wx.DEFAULT_FRAME_STYLE |
                         wx.NO_FULL_REPAINT_ON_RESIZE)
        panel = wx.Panel(self)

        self.SpeedWindow = SM.SpeedMeter(panel,
                                          extrastyle=SM.SM_DRAW_HAND |
                                          SM.SM_DRAW_SECTORS |
                                          SM.SM_DRAW_MIDDLE_TEXT |
                                          SM.SM_DRAW_SECONDARY_TICKS |
                                          SM.SM_DRAW_PARTIAL_FILLER |
                                          SM.SM_DRAW_SHADOW
                                          )

        # We Want To Simulate A Clock. Somewhat Tricky, But Did The Job
        self.SpeedWindow.SetAngleRange(pi/2, 5*pi/2)

        intervals = range(0, 13)
        self.SpeedWindow.SetIntervals(intervals)

        colours = [wx.SystemSettings_GetColour(0)]*12
        self.SpeedWindow.SetIntervalColours(colours)

        ticks = [str(interval) for interval in intervals]
        ticks[-1] = ""
        ticks[0] = "12"
        self.SpeedWindow.SetTicks(ticks)
        self.SpeedWindow.SetTicksColour(wx.BLUE)
        self.SpeedWindow.SetTicksFont(wx.Font(11, wx.SCRIPT, wx.NORMAL, wx.BOLD, True))
        self.SpeedWindow.SetNumberOfSecondaryTicks(4)

        # Set The Colour For The External Arc
        self.SpeedWindow.SetArcColour(wx.BLUE)

        self.SpeedWindow.SetHandColour(wx.BLACK)

        self.SpeedWindow.SetMiddleText("0 s")
        self.SpeedWindow.SetMiddleTextColour(wx.RED)

        # We Set The Background Colour Of The SpeedMeter OutSide The Control
        self.SpeedWindow.SetSpeedBackground(wx.WHITE)

        # Set The Colour For The Shadow
        self.SpeedWindow.SetShadowColour(wx.Colour(128, 128, 128))

        self.SpeedWindow.SetSpeedValue(0.0)

        # These Are Cosmetics For our SpeedMeter Control

        # Create The Timer For The Clock
        self.timer = wx.PyTimer(self.ClockTimer)
        self.currvalue = 0

        bsizer2 = wx.BoxSizer(wx.VERTICAL)

        hsizer2 = wx.BoxSizer(wx.HORIZONTAL)
        stattext2 = wx.StaticText(panel, -1, "A Simple Clock", style=wx.ALIGN_CENTER)

        button2 = wx.Button(panel, -1, "Stop")
        self.stopped = 0
        button2.Bind(wx.EVT_BUTTON, self.OnStopClock)
        button2.SetToolTip(wx.ToolTip("Click To Stop/Resume The Clock"))

        hsizer2.Add(button2, 0, wx.LEFT, 5)
        #hsizer2.Add(stattext2, 1, wx.EXPAND)
        #hsizer2.Add(self.helpbuttons[1], 0, wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT, 5)

        bsizer2.Add(self.SpeedWindow, 1, wx.EXPAND)
        bsizer2.Add(hsizer2, 0, wx.EXPAND)
        panel.SetSizer(bsizer2)
        self.timer.Start(1000)

    def ClockTimer(self):
        if self.currvalue >= 59:
            self.currvalue = 0
        else:
            self.currvalue = self.currvalue + 1

        self.SpeedWindow.SetMiddleText(str(self.currvalue) + " s")
        self.SpeedWindow.SetSpeedValue(self.currvalue/5.0)

    def OnStopClock(self, event):

        btn = event.GetEventObject()

        if self.stopped == 0:
            self.stopped = 1
            self.timer.Stop()
            btn.SetLabel("Resume")
        else:
            self.stopped = 0
            self.timer.Start()
            btn.SetLabel("Stop")

if __name__ == "__main__":

    app = wx.PySimpleApp()
    frame = MyFrame()
    frame.Show()
    #frame.Maximize()

    app.MainLoop()

rawDescription: Countdown timer in python/wxpython

description: Countdown timer in python/wxpython


code:
try:
     utxt = txt.decode('ascii')
except:
     # txt contains non "english" characters
     ...

rawDescription: Removing Non English Sub headings and Paragraphs


code:
import sys

from PySide.QtCore import *
from PySide.QtGui import *

class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.line_edit = QLineEdit()
        layout.addWidget(self.line_edit)

        self.label = QLabel()
        layout.addWidget(self.label)

        self.line_edit.textChanged.connect(self.line_edit_text_changed)

        self.show()

    def line_edit_text_changed(self, text):
        self.label.setText(text)

app = QApplication(sys.argv)
mw = MainWindow()
app.exec_()

rawDescription: How to get text from lineEdit in Pyside?

description: Get text from lineEdit in Pyside


rawDescription: Convert 3-Element List of Tuples to Dictionary


rawDescription: how to merge a number of lists in to one list

description: Merge a number of lists in to one list


rawDescription: json.dumps(): escaping forward slashes

description: Json.dumps(): escaping forward slashes


code:
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)

rawDescription: Qt Stylesheets - how to remove dead space


code:
people = [
    [['name', 'John'], ['age', 21]],
    [['name', 'Ann'],  ['age', 45]],
    [['name', 'Tom'],  ['age', 32]],
]

for person in people:
  # person is like [['name', 'Ann'],  ['age', 45]] here
  for (name, value) in person:
    # unpack [field_name, field_value] to name = field_name, value = field_value
    # so name is like 'name' (or 'age') and value is like 'Ann' (or 45)
    if name == 'name': print(value)

rawDescription: How does this for loop work?

description: How does this for loop work


code:
import contextlib
import datetime
import urllib2

with contextlib.closing(urllib2.urlopen(urllib2.Request(
        "http://www.w3schools.com/html/",
        headers={"If-Modified-Since": last_access_time}))) as u:
    if u.getcode() != 304:
        cached_html = lxml.html.parse(u)
        last_access_time = datetime.datetime.now()
html = cached_html

rawDescription: Accessing an html file from cache memory


rawDescription: How to pad till end-of-day in pandas?

description: Pad till end-of-day in pandas


code:
number_unique = 1  # The number of variables that should be unique between runs

model += objective
model += constraint1
model += constraint2
model += constraint3

for i in range(1,5):
    model.solve()
    selected_vars = []
    for p in vars:
         if p_vars[p].value() != 0:
             selected_vars.append(p)
    print_results()

    # Add a new constraint that the sum of all of the variables should
    # not total up to what I'm looking for (effectively making unique solutions)
    model += sum([p_vars[p] for p in selected_vars]) <= 10 - number_unique

rawDescription: Multiple solutions when doing ILP

description: Multiple solutions when doing ILP


code: framename = driver.find_element_by_xpath("//frame[contains(@name, 'results_frame')]").get_attribute("name")

rawDescription: retrieve dynamic frame names w/ Selenium WebDriver and Python?

description: Retrieve dynamic frame names w/ Selenium WebDriver and Python


code: from __future__ import absolute_import

rawDescription: How to import standard library instead of same-named module in module path

description: Import standard library instead of same-named module in module path


code:
x.__enter__()
try:
    ...
finally:
    x.__exit__()

rawDescription: How to use __del__ in a reliable way?

description: Use __del__ in a reliable way


code:
import sys
from PyQt4 import QtGui, QtCore

class mymainwindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setWindowFlags(
            QtCore.Qt.WindowStaysOnTopHint |
            QtCore.Qt.FramelessWindowHint |
            QtCore.Qt.X11BypassWindowManagerHint
            )
        self.setGeometry(QtGui.QStyle.alignedRect(
            QtCore.Qt.LeftToRight, QtCore.Qt.AlignCenter,
            QtCore.QSize(220, 32),
            QtGui.qApp.desktop().availableGeometry()))

    def mousePressEvent(self, event):
        QtGui.qApp.quit()

app = QtGui.QApplication(sys.argv)
mywindow = mymainwindow()
mywindow.show()
app.exec_()

rawDescription: Creating a transparent overlay with qt

description: Creating a transparent overlay with qt


code:
name, age = input("Enter name and age: ").split()
print("Your name is {this} and your age is {that}".format(this=name, that=age))

rawDescription: (new) python questions about user input

description: (new) python questions about user input


code:
from __future__ import print_function
from collections import Counter
import random

cntr = Counter()
for _ in range(50):
    rnd = random.randint(1, 10)
    cntr.update([rnd])
    print(rnd)

for value, count in cntr.most_common():
    print("%d was generated %d times" % (value, count))

rawDescription: Storing occurence of random number

description: Storing occurence of random number


code: ("".join(s) for s in product(alphabet, repeat=n) if s[:n//2]!=s[n//2:])

rawDescription: Python 3: Generate not all permutations, but all non-repetitive combinations of length r?


code:
import fileinput
import sys

for line in fileinput.input(filename, inplace=True):
    if line.strip() == 'swift-ring-builder account.builder add zZONE-STORAGE_LOCAL_NET_IP:6002/DEVICE 100':
        sys.stdout.write(
            'swift-ring-builder account.builder add z1-10.0.0.2:6002/sda 100\n'
            'swift-ring-builder container.builder add z1-10.0.0.2:6001/sda 100\n'
            'swift-ring-builder object.builder add z1-10.0.0.2:6000/sda 100\n'
        )
    else:
        sys.stdout.write(line)

rawDescription: Replace a single line pattern by multiple lines in python using sed


rawDescription: Why only one line goes to zero when several lines are plotted with semilogx function python


code: (fine / np.repeat(coarse, 2)).reshape(-1, 2)

rawDescription: Concurrently reading numpy arrays in parallel


code: booleans= [[l[0]]+[1 if i is None else 0 for i in l[1:4]]+l[4:] for l in my_list]

rawDescription: slicing a list for list comprehension but keeping sliced values

description: Slicing a list for list comprehension but keeping sliced values


rawDescription: how to get a single result from a SQLite query in python?

description: Get a single result from a SQLite query in python


code:
from django.db import models
from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec,DateFieldFilterSpec
from django.utils.encoding import smart_unicode
from django.utils.translation import ugettext as _
from datetime import datetime

class IsLiveFilterSpec(DateFieldFilterSpec):
    """
    Adds filtering by future and previous values in the admin
    filter sidebar. Set the is_live_filter filter in the model field attribute
    'is_live_filter'.    my_model_field.is_live_filter = True
    """

    def __init__(self, f, request, params, model, model_admin):
        super(IsLiveFilterSpec, self).__init__(f, request, params, model,
                                               model_admin)
        today = datetime.now()
        self.links = (
            (_('Any'), {}),
            (_('Yes'), {'%s__lte' % self.field.name: str(today),
                       }),
            (_('No'), {'%s__gte' % self.field.name: str(today),
                    }),

        )

    def title(self):
        return "Is Live"

# registering the filter
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'is_live_filter', False),
                               IsLiveFilterSpec))

rawDescription: Custom Filter in Django Admin on Django 1.3 or below


code:
window = wx.Frame(None, -1, '')
window.AssociateHandle(hwnd)
dc = wx.WindowDC(window)

rawDescription: wxPython wxDC object from win32gui.GetDC

description: WxPython wxDC object from win32gui.GetDC


rawDescription: Accessing variables by their names in a tuple


code:
def write(data):
    """
    The producer will write data by calling this method.

    The implementation must be non-blocking and perform whatever
    buffering is necessary.  If the producer has provided enough data
    for now and it is a L{IPushProducer}, the consumer may call its
    C{pauseProducing} method.
    """

rawDescription: Twisted Producer deferred write

description: Twisted Producer deferred write


code: df[df.apply(lambda x: min(x) == max(x), 1)]

rawDescription: Get rows that have the same value across its columns in pandas


code:
class Notebook(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=200, help_text='Maximum 250 characters')
    slug = models.SlugField(unique=True)
    last_modified = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.title

class Page(models.Model):
    notebook = models.ForeignKey(Notebook)
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique_for_date='pub_date')
    tags = TaggableManager()
    pub_date = models.DateTimeField(default=datetime.datetime.now)

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        instance = super(Page, self).save(*args, **kwargs)
        self.notebook.save()
        return instance

rawDescription: django updating foreignKey field before saving

description: Django updating foreignKey field before saving


rawDescription: Splitting an unspaced string of decimal values - Python


code:
flength = file_len(file)
length.append(flength)

rawDescription: Python 2.7 - how to count lines in files and use the results further


code:
df["charge"] = df.groupby(["Item"]).cumcount()
df.pivot_table("Cost", index="Item", columns="charge", aggfunc=lambda x: x)

rawDescription: Most Efficient way to get index of item within a group in pandas dataframe


code:
from matplotlib.ticker import FormatStrFormatter
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%g'))

rawDescription: Trimming trailing xticks zeros with matplotlib


code:
import requests

url = "http://www.imdb.com/title/tt0089218/"
headers = {"Accept-Language": "en-US,en;q=0.5"}
r = requests.get(url, headers=headers)

rawDescription: Python change Accept-Language using requests


code:
import re
import pandas
import warnings

myfile = 'your_input_file_here.txt'
target_type = str  # The desired output type

with warnings.catch_warnings(record=True) as ws:
    warnings.simplefilter("always")

    mydata = pandas.read_csv(myfile, sep="|", header=None)
    print("Warnings raised:", ws)
    # We have an error on specific columns, try and load them as string
    for w in ws:
        s = str(w.message)
        print("Warning message:", s)
        match = re.search(r"Columns \(([0-9,]+)\) have mixed types\.", s)
        if match:
            columns = match.group(1).split(',') # Get columns as a list
            columns = [int(c) for c in columns]
            print("Applying %s dtype to columns:" % target_type, columns)
            mydata.iloc[:,columns] = mydata.iloc[:,columns].astype(target_type)

rawDescription: pandas read_csv converting mixed types columns as string

description: Pandas read_csv converting mixed types columns as string


code:
class ParamDict(dict):
    def __getitem__(self, key):
        val = dict.__getitem__(self, key)
        return callable(val) and val(self) or val

params = ParamDict({
    'a': 5,
    'b': lambda self: 2**self['a']
    })

rawDescription: Python self referential dictionary with class


code:
def delete_keys_from_dict(dict_del, lst_keys):
    for k in lst_keys:
        try:
            del dict_del[k]
        except KeyError:
            pass
    for v in dict_del.values():
        if isinstance(v, dict):
            delete_keys_from_dict(v, lst_keys)

    return dict_del

rawDescription: Elegant way to remove fields from nested dictionaries


code:
def is_prime(n):
    i = 2
    while (i * i <= n):
        if (n % i == 0):
            return False
        i += 1
    return True

rawDescription: isPrime function (list + % operator)

description: IsPrime function (list + % operator)


code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.treewidget = QTreeWidget(self)
        self.treewidget.setHeaderLabels(['a'])
        self.treewidget.setDragEnabled(True)
        self.treewidget.setAcceptDrops(True)
        self.treewidget.setDropIndicatorShown(True)
        self.treewidget.resize(300,300)
        self.titems = []
        for i in xrange(100):
            if not i%10:
                pitem = QTreeWidgetItem(self.treewidget,["Parent %d"%i])
                self.titems.append(pitem)
            else:
                item = QTreeWidgetItem(pitem,["Child of %d"%i])
                self.titems.append(item)
        self.show()

app = QApplication(sys.argv)
w = MainWindow()
app.exec_()

rawDescription: Text tree in Python GUI

description: Text tree in Python GUI


code:
"a".lower
"a".lower()
"a".lower == "a"
"a".lower() == "a"

rawDescription: Python while loop is not functioning correctly (beginner)


code:
import tarfile
import io
import os

def get_file_progress_file_object_class(on_progress):
    class FileProgressFileObject(tarfile.ExFileObject):
        def read(self, size, *args):
          on_progress(self.name, self.position, self.size)
          return tarfile.ExFileObject.read(self, size, *args)
    return FileProgressFileObject

class TestFileProgressFileObject(tarfile.ExFileObject):
    def read(self, size, *args):
      on_progress(self.name, self.position, self.size)
      return tarfile.ExFileObject.read(self, size, *args)

class ProgressFileObject(io.FileIO):
    def __init__(self, path, *args, **kwargs):
        self._total_size = os.path.getsize(path)
        io.FileIO.__init__(self, path, *args, **kwargs)

    def read(self, size):
        print("Overall process: %d of %d" %(self.tell(), self._total_size))
        return io.FileIO.read(self, size)

def on_progress(filename, position, total_size):
    print("%s: %d of %s" %(filename, position, total_size))

tarfile.TarFile.fileobject = get_file_progress_file_object_class(on_progress)
tar = tarfile.open(fileobj=ProgressFileObject("a.tgz"))
tar.extractall()
tar.close()

rawDescription: Python tarfile progress output?

description: Python tarfile progress output


code:
time = 0
while time < 100:
   gold += level
   if gold > 20 * level:
      level +=1
      time += 10
   time += 1

rawDescription: in python for loop,, jump over values

description: In python for loop,, jump over values


code:
#---------------------------------------------------------79th-column-mark--->|
cmd_folder = os.path.realpath(
    os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))

rawDescription: Python - How to style this line of code?

description: Python - How to style this line of code


code:
file1 = part.get_filename()
fileEncode = file[1]

rawDescription: How to get python part.get_filename() , Encoding type?

description: Get python part.get_filename() , Encoding type


code:
# reindex with interval 12 months (M: month, S: beginning of the month)
df_reindexed = df.reindex(pd.date_range(start='20120101', end='20350101', freq='12MS'))

# method=linear works because the intervals are equally spaced out now
df_interpolated = df_reindexed.interpolate(method='linear')

rawDescription: interpolate values between sample years with Pandas

description: Interpolate values between sample years with Pandas


code:
for i in range(len(Names)):
    exec("def " + Names[i] + "(" + Args + "): " + Bodies[i]) #create locally
    globals()[Names[i]] = locals()[Names[i]]                           #assign to global space

rawDescription: Function creation at runtime in Python

description: Function creation at runtime in Python


code:
def get_queryset(self):
    category = self.request.query_params['category']
    ingredient_ids = self.request.query_params['ingredients[]'] # [] because getting multiple values for a same key
    recipe_ids = RecipeIngredients.objects.filter(ingredient_id__in=ingredient_ids).values_list('recipe_id', flat=True)
    return Recipe.objects.filter(recipe_id__in=recipe_ids, category=category)

rawDescription: One Filter for Two models

description: One Filter for Two models


code:
pathToBmp = "imagename or image directory"
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, pathToBmp ,
                                      0)

rawDescription: create an button on desktop

description: Create an button on desktop


code:
from collections import Counter
c = Counter("abcbi")
d = Counter("acbb")
c.subtract(d)
if all(v >= 0 for k, v in c.items()):
    print("All items exist")

rawDescription: Check if all elements in list1 exist in list2 python


code:
f = open('/tmp/list.txt','w')
f.write(list)
f.close()  # Make sure to close the file before call sub-process.
           # Otherwise, file content will not visible to sub-process.

process = subprocess.Popen('oscommand --file={}'.format(f.name),
                           shell=True, stdout=subprocess.PIPE)

rawDescription: Reference file during subprocess (Python)


code:
clauses = [
    (User.username == 'something'),
    (User.something == 'another thing'),
    ...
]
User.select().where(reduce(operator.or_, clauses))

rawDescription: python peewee dynamically or clauses

description: Python peewee dynamically or clauses


code:
class MyClearableInput(ClearableFileInput):
    template_with_initial = '%(initial_text)s: %(initial)s %(clear_template)s
%(input_text)s: %(input)s'
    template_with_clear = '%(clear)s %(clear_checkbox_label)s'
    url_markup_template = '{1}'

rawDescription: Django iterate over ClearableFileInput widget field


code:
from __future__ import absolute_import
# Import uncertainties.math
from . import math as local_math
import math as sys_math

rawDescription: How to access a standard-library module in Python when there is a local module with the same name?

description: Access a standard-library module in Python when there is a local module with the same name


code:
matrix=numpy.genfromtxt(path,delimiter=',') # Read the numpy matrix with images in the rows
c=matrix[0]
c=c.reshape(120, 165) # this is the size of my pictures
im=plt.imshow(c)
for row in matrix:
    row=row.reshape(120, 165) # this is the size of my pictures
    im.set_data(row)
    plt.pause(0.02)
plt.show()

rawDescription: Displaying Numpy Matrix as Video

description: Displaying Numpy Matrix as Video


code:
def archive_calc(self, rev_num, primary_field):
    model_a = Calc.objects.get(calc_details__calc_serial_number = primary_field, revision_number = rev_num)
    model_b = CalcArchive()

    object_list_annual = model_a.calcreview_set.filter(calc__calc_details = primary_field)
    object_list_ageing = model_a.calcitem_set.filter(calc__calc_details = primary_field)

    for obj in object_list_annual:
        obj.calc_id = self.object.id
        obj.save()
    for obj in object_list_ageing:
        obj.calc_id = self.object.id
        obj.save()

    for field in model_a._meta.fields:
        setattr(model_b, field.name, getattr(model_a, field.name))
    model_b.pk = None
    model_b.current_revision = False
    model_b.save()

    model_a.delete()

rawDescription: Copy fields from one instance to another in Django


code: numpy.maximum.accumulate(a, axis=1)

rawDescription: numpy array iteration to track maximum number so far

description: Numpy array iteration to track maximum number so far


code:
import sys, time
for i in range(100):
    time.sleep(0.1)
    sys.stdout.write('%d %% Completed \r' % (i,))
    sys.stdout.flush()

rawDescription: Replace printed statements in Python 2.7


code:
@classmethod
def setUpClass(cls):
    plant.StuffFactory() #plant stuff with FactoryBoy
    # you may possibly want to flush the session, so everything has proper IDs etc.
    DBSession.flush()
    # let the transaction continue for the duration of the test

@classmethod
def tearDownClass(cls):
    # let the database make everything as if nothing happened
    transaction.rollback()

rawDescription: Transaction manager revert/rollback last commit


rawDescription: Plot with many y-axis in different scales: how to tight figure


code:
import pandas as pd
df = pd.read_csv("C:\<my_directory_path>\data.txt",header=None)

rawDescription: Force Python Pandas DataFrame( read_csv() method) to avoid/not consider first row of my csv/txt file as header


code:
proc = subprocess.Popen(
    ['C:/Program Files/GNU/GnuPG/gpg.exe',
    '--batch', '--passphrase-fd', '0',
    '--output ', 'c:/docume~1/usi/locals~1/temp/tmptlbxka.txt',
    '--decrypt', 'test.txt.gpg',],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
   stderr=subprocess.STDOUT,
)
stdout_value, stderr_value = proc.communicate('bosco')

rawDescription: Python - Subprocess - How to call a Piped command in Windows?


code:
from django.db import models
from django.core import exceptions
import re

MONEY_REGEX_PATTERN = re.compile('^\$?-?0*(?:\d+(?!,)(?:\.\d{1,2})?|(?:\d{1,3}(?:,\d{3})*(?:\.\d{1,2})?))$')

def MoneyValidator(value):
    """Will validate a string value against a money regular expression"""
    if not MONEY_REGEX_PATTERN.match(value):
        raise exceptions.ValidationError('{v} is not a valid dollar amount'.format(v=value))

class MyMoneyField(models.CharField):

    """Custom field for handling values from PostgreSQL's money data type"""

    def __init__(self, *args, **kwargs):
        kwargs['validators'] = [MoneyValidator]
        kwargs['max_length'] = 20
        super(MyMoneyField, self).__init__(*args, **kwargs)

rawDescription: Django models and PostgreSQL money type

description: Django models and PostgreSQL money type


code:
import krbV

def has_ticket():
    '''
    Checks to see if the user has a valid ticket.
    '''
    ctx = krbV.default_context()
    cc = ctx.default_ccache()
    try:
        princ = cc.principal()
        retval = True
    except krbV.Krb5Error:
        retval = False

    return retval

rawDescription: python: validate kerberos ticket

description: Python: validate kerberos ticket


code:
cipher = M2Crypto.EVP.Cipher(alg="aes_128_cbc", key = aes_key, iv = aes_iv, op = 1)
encrypted_contents_file = open(outfile_name, "w")

while True:
    buf = fin.read(1024)
    if not buf:
        break
    encrypted_contents_file.write(cipher.update(buf))

encrypted_contents_file.write( cipher.final() )

rawDescription: Encrypt file using M2Crypto

description: Encrypt file using M2Crypto


code:
MONTH_NUMS = {
    '1 Month': 1,
    '3 Months Prom': 3,
    '3 Month': 3,
    '4 Month Promo': 4,
    '6 Months': 6,
}

def month_to_num(ind):
    return MONTH_NUMS.get(df.loc[ind, 'Contract Type'], 12)

rawDescription: Switch-case like structure in python

description: Switch-case like structure in python


code:
# migrate_prod.py
DB_MIGRATION_URI = "mysql+mysqldb://user:password@instance_id/db_name?ssl_key=path/client-key.pem&ssl_cert=path/client-cert.pem&&ssl_ca=path/server-ca.pem"

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from models import *   # not needed if migration file is already generated

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = DB_MIGRATION_URI
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':
    manager.run()

rawDescription: How to use Flask-Migrate with Google App Engine?

description: Use Flask-Migrate with Google App Engine


code:
from django.template import Context, Template

def responder():
    yield '' # to make sure the header is sent

    # do all your work

    t = Template('''
        {% extends "base.html" %}
        {% block content %} FOO {% endblock %}
    ''')
    yield t.render(Context({}))

return HttpResponse(responder())

rawDescription: Can a Django view return its header first?


code:
class SampleSchema(Schema):
    class Meta:
        ordered = True

rawDescription: Changing json attributes order in python flask/marshmallow


rawDescription: MongoDB PyMongo Listing all keys in a document


code:
import sys

if sys.version_info[0] == 2:  # Not named on 2.6
    from __future__ import print_function
    from StringIO import StringIO
else:
    from io import StringIO

rawDescription: printing floats to io.StringIO in Python 2/3

description: Printing floats to io.StringIO in Python 2/3


code:
def properties(self):
    class_items = self.__class__.__dict__.iteritems()
    return dict((k, getattr(self, k))
                for k, v in class_items
                if isinstance(v, property))

rawDescription: In a Python object, how can I see a list of properties that have been defined with the @property decorator?


code:
import cherrypy
from cherrypy.lib.static import serve_file
import os

class Hello(object):
    @cherrypy.expose
    def index(self):
        return "Hello World"

    @cherrypy.expose
    def static(self, page):
        return serve_file(os.path.join(current_dir, 'static', page), content_type='text/html')

if __name__ == '__main__':
    current_dir = os.path.dirname(os.path.abspath(__file__))
    cherrypy.quickstart(Hello())

rawDescription: CherryPy access restrictions with static files


code:
parent = soup.find("div", id='business-additional-info-text')
for child in parent.children:
    if("Number of Employees" in child):
        print(child.findNext('p').contents[0].strip())

rawDescription: Get content of a header tag searching by header tag name


code:
import RPi.GPIO as GPIO
import time
import cv2
import os

GPIO.setmode(GPIO.BCM)

GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:
    input_state = GPIO.input(17)
    while input_state:
        input_state = GPIO.input(17)
    print('Button Pressed')
    capture = cv2.VideoCapture(0)
    capture.set(3,1280)
    capture.set(4,1024)
    ret, img = capture.read()
    cv2.imshow("input", img)
    cv2.waitKey(1500)
    del(capture)
    cv2.VideoCapture(0).release()

rawDescription: Keep the if statement going

description: Keep the if statement going


code:
import string
import random
import time

response = "a"              # the variable that will hold the user's response
c = "b"                     #the variable that will hold the character the user should type
score = 0                   #the variable that will hold the user's score
start = time.time()         #the variable that holds the starting time
elapsed = 0                 #the variable that holds the number of seconds elapsed.
while elapsed < 30:         #while less than 30 seconds have elapsed

    if response == c:       #if the response from the previous loop matches the character
        score += 1          #from the previous loop, increase the score.

    #c is a random character
    c = random.choice(string.ascii_lowercase + string.digits)
    print(c)

    response = input("Type a letter or a number: ") #get the user's response

    elapsed = time.time() - start #update the time elapsed

rawDescription: Python time limit

description: Python time limit


code:
def addValue(linkedSet, value):

    newNode={
        'data': value,
        'next': None
    }

    # if linkedSet is None, then you can just return this newNode

    # if linkedSet isnt None...
        # if linkedSets next is None, then it should just point to this newNode
        # (append)

        # otherwise, you should set its current next to the next of this newnode,
        # and then set its next to this newNode (insert)

rawDescription: Linked Lists Python 2.7

description: Linked Lists Python 2.7


code:
def add(self):
    """Create a new user.
    Line 2 of comment...
    And so on...
    """

rawDescription: What is the proper way to comment functions in python?


code:
x = np.linspace(0,6,31)
y = np.exp(-0.5*x) * np.sin(x)
plot(x, y, 'bo-')
savefig('demo.png', transparent=True)

rawDescription: How to export plots from matplotlib with transparent background?

description: Export plots from matplotlib with transparent background


code:
import os.path
from configobj import ConfigObj

BASE = os.path.dirname(os.path.abspath(__file__))

class myHelper:

    def __init__(self):
        self.config = ConfigObj(os.path.join(BASE, 'config.cfg'))

rawDescription: ConfigObj and absolute paths

description: ConfigObj and absolute paths


rawDescription: find the index of maximum element of 2nd column of a 2 dimensional list

description: Find the index of maximum element of 2nd column of a 2 dimensional list


code:
import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'

assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

rawDescription: How to copy a file using python?

description: Copy a file using python


code:
def copy(src, dst):
    if os.path.islink(src):
        linkto = os.readlink(src)
        os.symlink(linkto, dst)
    else:
        shutil.copy(src,dst)

rawDescription: Copying a symbolic link in Python

description: Copying a symbolic link in Python


code:
list_var = open("small_list.txt", "r").read().split()
new_list = []

for i in range(0, len(list_var)):
    new_list.append(float(list_var[i]))

print(new_list)

rawDescription: Text file data into python list

description: Text file data into python list


code:
from Bio import AlignIO,SeqIO,ExPASy,SwissProt
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio.Emboss.Applications import NeedleCommandline
from prody.proteins.pdbfile import parsePDB, writePDB
import os

oneletter = {
'ASP':'D','GLU':'E','ASN':'N','GLN':'Q',
'ARG':'R','LYS':'K','PRO':'P','GLY':'G',
'CYS':'C','THR':'T','SER':'S','MET':'M',
'TRP':'W','PHE':'F','TYR':'Y','HIS':'H',
'ALA':'A','VAL':'V','LEU':'L','ILE':'I',
}

# Retrieve pdb to extract sequence
# Can probably be done with Bio.PDB but being able to use the vmd-like selection algebra is nice
pdbname="2kpl"
selection="chain A"
structure=parsePDB(pdbname)
pdbseq_str=''.join([oneletter[i] for i in structure.select("protein and name CA and     %s"%selection).getResnames()])
alnPDBseq=SeqRecord(Seq(pdbseq_str,IUPAC.protein),id=pdbname)
SeqIO.write(alnPDBseq,"%s.fasta"%pdbname,"fasta")

# Retrieve reference sequence
accession="Q96QZ7"
handle = ExPASy.get_sprot_raw(accession)
swissseq = SwissProt.read(handle)
refseq=SeqRecord(Seq(swissseq.sequence,IUPAC.protein),id=accession)
SeqIO.write(refseq, "%s.fasta"%accession,"fasta")

# Do global alignment with needle from EMBOSS, stores entire sequences which makes numbering easier
needle_cli = NeedleCommandline(asequence="%s.fasta"%pdbname,bsequence="%s.fasta"%accession,gapopen=10,gapextend=0.5,outfile="needle.out")
needle_cli()
aln = AlignIO.read("needle.out", "emboss")
os.remove("needle.out")
os.remove("%s.fasta"%pdbname)
os.remove("%s.fasta"%accession)

alnPDBseq = aln[0]
alnREFseq = aln[1]
# Initialize per-letter annotation for pdb sequence record
alnPDBseq.letter_annotations["resnum"]=[None]*len(alnPDBseq)
# Initialize annotation for reference sequence, assume first residue is #1
alnREFseq.letter_annotations["resnum"]=range(1,len(alnREFseq)+1)

# Set new residue numbers in alnPDBseq based on alignment
reslist = [[i,alnREFseq.letter_annotations["resnum"][i]] for i in range(len(alnREFseq)) if alnPDBseq[i] != '-']
for [i,r] in reslist:
    alnPDBseq.letter_annotations["resnum"][i]=r

# Set new residue numbers in the structure
newresnums=[i for i in alnPDBseq.letter_annotations["resnum"][:] if i != None]
resindices=structure.select("protein and name CA and %s"%selection).getResindices()
resmatrix = [[newresnums[i],resindices[i]] for i in range(len(newresnums)) ]
for [newresnum,resindex] in resmatrix:
    structure.select("resindex %d"%resindex).setResnums(newresnum)

writePDB("%s.renumbered.pdb"%pdbname,structure)

rawDescription: renumber residues in a protein structure file (pdb)

description: Renumber residues in a protein structure file (pdb)


code:
def show_callers_locals():
    """Print the local variables in the caller's frame."""
    import inspect
    frame = inspect.currentframe()
    try:
        print(frame.f_back.f_locals)
    finally:
        del frame

rawDescription: Get locals from calling namespace in Python