code:
def getCbFun(queue): # closure
    def cbFun(snmpEngine,stateReference,
          contextEngineId, contextName,
          varBinds,
          cbCtx):
        ...
        queue.add(varBinds)
        ...
    return cbFun

...

# Shared queue object
queue = Queue()

# Register SNMP Application at the SNMP engine
ntfrcv.NotificationReceiver(snmpEngine, getCbFun(queue))

...

rawDescription: python multiprocessing to receive snmp alerts

description: Python multiprocessing to receive snmp alerts


code:
def warpbar(text, lineLength):
   n = len(text)
   return "#"*lineLength+"\n"+"="*(n-lineLength)

rawDescription: Python replace up to \n in a function

description: Python replace up to \n in a function


code:
import re
from collections import Counter
t = "This is a sentence with many words. Some words are repeated"
Counter(re.split(r'\W', t)).most_common()

rawDescription: Calculating word frequencies in Python or R


code:
class Game(object):

    def __init__(self):
        self._stack_size = 5

    @property
    def stack_size(self):
        return self._stack_size

    @stack_size.setter
    def stack_size(self, val):
        self._stack_size = val
        #do some more updates of other things

rawDescription: Function that detects when variable change?


code:
class MyModelAdmin(admin.ModelAdmin):
    list_display = ('foo', 'bar')

    def queryset(self, request):
        qs = self.model._default_manager.only('foo', 'bar')
        ordering = self.get_ordering(request)
        if ordering:
            qs = qs.order_by(*ordering)
        return qs

rawDescription: to_python being called every time data is loaded from DB

description: To_python being called every time data is loaded from DB


rawDescription: Python webapp2: redirect back

description: Python webapp2: redirect back


rawDescription: NumPy min/max in-place assignment

description: NumPy min/max in-place assignment


code:
wed = 2 # from the datetime.weekday definition
first_wed = start + datetime.timedelta(days=(7 + wed - start.weekday()) % 7)

rawDescription: Output all dates for a date range

description: Output all dates for a date range


code:
import numpy as np
si, se = np.where(~x.mask)
x = x[si.min():si.max() + 1, se.min():se.max() + 1]

rawDescription: Numpy : clip/cut 2d masked array

description: Numpy : clip/cut 2d masked array


code:
import re
strs = 'The output is\n1) python\nA dynamic language\neasy to learn\n2) C++\ndifficult to learn\n3244) PHP\neay to learn\n'
re.findall(r'\d+\)\s[^\d]+',strs)

rawDescription: How to write a regex in python to match this?

description: Write a regex in python to match this


code:
import subprocess
import os

fasta_dir = "/Users/vivaksoni1/Downloads/DA_CDS/fasta_files/"

with open("five_seqs.txt", "w") as f:
    for file in os.listdir(fasta_dir):
        f.write(file + '\t')
        grep = subprocess.Popen(["grep", "-c", "^>", fasta_dir + file], stdout = subprocess.PIPE)
        out, err = grep.communicate()
        f.write(out + '\n')

rawDescription: Using python subprocess.call for writing count of fasta sequences to file


code:
import sys
import pygame as pg

def main():
    pg.init()
    screen = pg.display.set_mode((320, 240))
    clock = pg.time.Clock()
    done = False
    bg_color = pg.Color(50, 80, 120)
    # Create the original image that we use for the rotation
    # to avoid visual degeneration.
    orig_img = pg.Surface((100, 100))
    orig_img.fill((20, 50, 130))
    pg.draw.circle(orig_img, pg.Color('springgreen2'), (30, 30), 30)
    pg.draw.circle(orig_img, pg.Color('lightgoldenrod3'), (60, 60), 30)
    pg.draw.rect(orig_img, pg.Color('black'), (48, 0, 4, 100))
    pg.draw.rect(orig_img, pg.Color('black'), (0, 48, 100, 4))
    rect = orig_img.get_rect(topleft=(30, 30))

    angle = 0

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        angle += 1
        # Rotate the image.
        img = pg.transform.rotate(orig_img, angle)
        rect = img.get_rect(center=rect.center)
        # Calculate new crop position. Half of the new
        # width & height minus half of the original dimensions.
        x, y = rect.width/2 - 50, rect.height/2 - 50
        sub = img.subsurface((x, y, 100, 50))

        screen.fill(bg_color)

        screen.blit(img, rect)
        screen.blit(sub, (150, 150))

        pg.display.flip()
        clock.tick(30)

if __name__ == "__main__":
    main()
    pg.quit()
    sys.exit()

rawDescription: How to "Crop" a Rotated Image In Pygame

description: "Crop" a Rotated Image In Pygame


code:
def populate_equilibria (obj):
    obj.populate_equilibria()
    return obj

j1 = jobserver.submit(populate_equilibria,(net2,),(),("numpy as num"))
net2 = j1()

rawDescription: In ParallelPython, a method of an object ( object.func() ) fails to manipulate a variable of an object ( object.value )


code:
file = open('path', 'r+')
config = file.read()
## all the code inbetween works fine
## config is .split()-ed, hence the list
if config == ['']:
    config = ''
file.seek(0)    # rewind the file
file.write(config)
file.close()

rawDescription: Writing empty string to textfile in Python


code:
with open('out.log', 'a') as f:
    f.write('output is ')
    # some work
    s = 'OK.'
    f.write(s)
    f.write('\n')

# some other work
with open('out.log', 'a') as f:
    f.write('done\n')

rawDescription: Python: Writing to a File

description: Python: Writing to a File


code:
import re

tests=['1m30s','3m15s','2m25s','2m','55s']
for time_str in tests:
    match=re.match('(?:(\d*)m)?(?:(\d*)s)?',time_str)
    if match:
        minutes = int(match.group(1) or 0)
        seconds = int(match.group(2) or 0)
        print({'minutes':minutes,
               'seconds':seconds})

# {'seconds': 30, 'minutes': 1}
# {'seconds': 15, 'minutes': 3}
# {'seconds': 25, 'minutes': 2}
# {'seconds': 0, 'minutes': 2}
# {'seconds': 55, 'minutes': 0}

rawDescription: Parsing 'time string' with Python?

description: Parsing 'time string' with Python


code: statsList = taskqueue.QueueStatistics.fetch([taskqueue.Queue("foo"), taskqueue.Queue("bar")])

rawDescription: Check if a queue is empty in Google App Engine


code:
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(user,passwd)
while True:
    mail.select("inbox")
    result, idData = mail.uid('search', query, "ALL")
    processIDs(idData)
    time.sleep(60)

rawDescription: Python Imaplib: Get new gmail mails without reconnect


code:
first = [x for (x,y) in data]
second = [y for (x,y) in data]

rawDescription: Extract array from list in python

description: Extract array from list in python


code:
cmap = matplotlib.pyplot.cm.Greys
bounds = numpy.linspace(numpy.amin(Z),numpy.amax(Z), n + 1)
normalisation = matplotlib.colors.BoundaryNorm(bounds, cmap.N)

rawDescription: matplotlib 3d contour_plot colour levels

description: Matplotlib 3d contour_plot colour levels


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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100

xs = np.random.randint(0, 10, size=n)
ys = np.random.randint(0, 10, size=n)
zs = np.random.randint(0, 10, size=n)
colors = np.random.randint(0, 10, size=n)
ax.scatter(xs, ys, zs, c=colors, marker='o')
plt.show()

rawDescription: 3D scatter plot

description: 3D scatter plot


code:
import os

path = os.environ['PATH_INFO']

rawDescription: Get URL from middleware

description: Get URL from middleware


code:
h2_details = soup.find('h2', text='Case details')

table = h2_details.find_next_sibling('table')

details = {}
for row in table.find_all('tr'):
    cells = row.find_all('td', limit=2)
    details[cells[0].string] = cells[1].string

rawDescription: BeautifulSoup 4 - parse a two col table into a dictionary


code:
node = {}
for i in range(number_of_instances):
    node[i] = Node()
...
for i in range(number_of_nodes):
    my_graph.add_node(node[i], name="node %s" % i)

rawDescription: creating named instances of a class within a for loop -- related to networkx -- Python

description: Creating named instances of a class within a for loop -- related to networkx -- Python


code: x[index] if len(x) > index else default

rawDescription: How to get the nth element of a python list or a default if not available

description: Get the nth element of a python list or a default if not available


code:
from PIL import Image, ImageFile, PngImagePlugin

def patched_chunk_tRNS(self, pos, len):
    i16 = PngImagePlugin.i16
    s = ImageFile._safe_read(self.fp, len)
    if self.im_mode == "P":
        self.im_info["transparency"] = map(ord, s)
    elif self.im_mode == "L":
        self.im_info["transparency"] = i16(s)
    elif self.im_mode == "RGB":
        self.im_info["transparency"] = i16(s), i16(s[2:]), i16(s[4:])
    return s
PngImagePlugin.PngStream.chunk_tRNS = patched_chunk_tRNS

def patched_load(self):
    if self.im and self.palette and self.palette.dirty:
        apply(self.im.putpalette, self.palette.getdata())
        self.palette.dirty = 0
        self.palette.rawmode = None
        try:
            trans = self.info["transparency"]
        except KeyError:
            self.palette.mode = "RGB"
        else:
            try:
                for i, a in enumerate(trans):
                    self.im.putpalettealpha(i, a)
            except TypeError:
                self.im.putpalettealpha(trans, 0)
            self.palette.mode = "RGBA"
    if self.im:
        return self.im.pixel_access(self.readonly)
Image.Image.load = patched_load

Image.open('kHrY6.png').convert('RGBA').save('kHrY6-out.png')

rawDescription: Python PIL - All areas of PNG with opacity > 0 have their opacity set to 1


code:
class EnsembleClassifier(BaseEstimator, ClassifierMixin):
    def __init__(self, classifiers=None):
        self.classifiers = classifiers

    def fit(self, X, y):
        for classifier in self.classifiers:
            classifier.fit(X, y)

    def predict_proba(self, X):
        self.predictions_ = list()
        for classifier in self.classifiers:
            self.predictions_.append(classifier.predict_proba(X))
        return np.mean(self.predictions_, axis=0)

rawDescription: Best way to combine probabilistic classifiers in scikit-learn

description: Combine probabilistic classifiers in scikit-learn


rawDescription: Python Selenium return text, unicode object is not callable


code:
with open('data.txt') as f:
    full_lines = f.readlines()

# parse full lines to get the text to right of "-"
lines = [line.partition('-')[2].rstrip() for line in full_lines]

numcases = int(lines[0])
for i in range(1, len(lines), 2):
    caseinput = lines[i]
    caseoutput = lines[i+1]
    ...

rawDescription: What is a better way to readlines from Python file?


code:
import threading
import time

value = 3

def process():
    while True:
        print(value)
        time.sleep(1)

thread = threading.Thread(target=process)
thread.start()

while True:
    value = input('Enter value: ')

rawDescription: How to read users input when in loop (and without blocking work in this loop)?

description: Read users input when in loop (and without blocking work in this loop)


code:
self.response.headers['Content-Type'] = 'application/csv'
writer = csv.writer(self.response.out)

writer.writerow(["foo", "foo,bar", "bar"])

rawDescription: generating a CSV file online on Google App Engine

description: Generating a CSV file online on Google App Engine


code: cmd = "bash -c 'grep -L killed /dir/dumps/*MAC-66.log'"

rawDescription: pexpect.run can not run a long command

description: Pexpect.run can not run a long command


code:
table = []
for each_line in homefile:
##doesn't include first line
        arr1 = each_line.strip("\n").split('\t')
        table.append(arr1)
##created a list of lists(matrix); each row as one entry in table(list)
cols = zip(*table)
##this switches rows and columns

rawDescription: How do I analyze columns in python?

description: Analyze columns in python


code:
import requests
r = requests.get("http://localhost:5000")
# a flask application there sets two cookies 'first' and 'second'

r.cookies.keys()
# returns ['first', 'second']

r.headers['Set-Cookie']
# returns 'first=4; Path=/, second=42; Path=/'

rawDescription: python web-client multipile set-cookie header, get raw set-cookie header

description: Python web-client multipile set-cookie header, get raw set-cookie header


code:
image = Image.new("RGBA", (600,150), (255,255,255))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("resources/HelveticaNeueLight.ttf", fontsize)

draw.text((10, 0), txt, (0,0,0), font=font)

rawDescription: Python PIL using different font

description: Python PIL using different font


rawDescription: Does pandas have equivalents to R's 'with()' and 'within()' functions?


rawDescription: Retrieving netstat from local server python script


code:
data1 = u'NAME: abc\nSchool Name: CD\n________________\nENG: B   \nMat: B   '

import re
from itertools import izip
data2 = re.split(r'[:\n________________]+',data1)
i = iter(data2)
ans = dict(izip(i, i))

rawDescription: python Unicode string splitting/ to json conversion

description: Python Unicode string splitting/ to json conversion


code:
from xml.etree import cElementTree as ET
import urllib

def get_bass_fishing_URLs():
  results = []
  data = urllib.urlopen(
      'http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/')
  tree = ET.parse(data)
  ns = '{http://www.w3.org/2005/Atom}'
  for entry in tree.findall(ns + 'entry'):
    for link in entry.findall(ns + 'link'):
      if link.get('rel') == 'alternate':
        results.append(link.get('href'))

rawDescription: Simple scraping of youtube xml to get a Python list of videos


rawDescription: Matrix of labels to adjacency matrix

description: Matrix of labels to adjacency matrix


code:
def readll(infile):
    with open(infile) as data:
        floatlist1, floatlist2 = [], []
        reading = False

        for line in data:
            if not reading:
                if '@' not in line:
                    reading = True
                else:
                    continue

            if '&' in line:
                return floatlist1, floatlist2

            numbers = map(float, line.split())
            floatlist1.append(numbers[0])
            floatlist2.append(numbers[1])

rawDescription: How to make lists of integers from a portion of a file with Python?

description: Make lists of integers from a portion of a file with Python


code:
import pandas as pd
import numpy as np

df = pd.read_csv('survey_scores.csv', header=0)
np.round(pd.DataFrame(df.groupby('question_number').aggregate('mean').score).transpose(), 2).to_html(float_format=lambda x: '%.2f' % x)

rawDescription: Pandas DataFrame Float Formatting

description: Pandas DataFrame Float Formatting


code:
class SocketClientThread(threading.Thread):
    """ Implements the threading.Thread interface (start, join, etc.) and
        can be controlled via the cmd_q Queue attribute. Replies are placed in
        the reply_q Queue attribute.
    """
    def __init__(self, cmd_q=Queue.Queue(), reply_q=Queue.Queue()):
        super(SocketClientThread, self).__init__()
        self.cmd_q = cmd_q
        self.reply_q = reply_q
        self.alive = threading.Event()
        self.alive.set()
        self.socket = None

        self.handlers = {
            ClientCommand.CONNECT: self._handle_CONNECT,
            ClientCommand.CLOSE: self._handle_CLOSE,
            ClientCommand.SEND: self._handle_SEND,
            ClientCommand.RECEIVE: self._handle_RECEIVE,
        }

    def run(self):
        while self.alive.isSet():
            try:
                # Queue.get with timeout to allow checking self.alive
                cmd = self.cmd_q.get(True, 0.1)
                self.handlers[cmd.type](cmd)
            except Queue.Empty as e:
                continue

    def join(self, timeout=None):
        self.alive.clear()
        threading.Thread.join(self, timeout)

rawDescription: Python Queue waiting for thread before getting next item


code:
dataset = []
for row_index in range(sheet.nrows):
   datarow = []
   for col_index in range(sheet.ncols):
       datarow.append (sheet.cell(row_index,col_index).value)
   dataset.append(datarow)

rawDescription: Using multiple python lists to format source data from Excel


code:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

fromaddr = 'demo@gmail.com'
toaddrs = 'demotest@gmail.com'

msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = "good morning" #like name
msg['To'] = "GGGGGG"

body = MIMEText("example email body")
msg.attach(body)

username = 'demo@gmail.com'
password = ''
server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()

rawDescription: send mail using python

description: Send mail using python


code:
str = 'func(param1, param2)'
re.match(r',\s*param2', str)
re.search(r',\s*param2', str)

rawDescription: Python Regex: "re.match()" works differently than "re.sub()" for regex


code:
import git
repo = git.Repo("path/of/repo/")

# the below gives us all commits
repo.commits()

# take the first and last commit

a_commit = repo.commits()[0]
b_commit = repo.commits()[1]

# now get the diff
repo.diff(a_commit,b_commit)

rawDescription: how to do a git diff of current commit with last commit using gitpython?

description: Do a git diff of current commit with last commit using gitpython


code:
import numpy as np

signal = np.random.rand(1000000)
th = signal > 0.5
th[1:][th[:-1] & th[1:]] = False

rawDescription: Finding first samples greater than a threshold value efficiently in Python (and MATLAB comparison)


rawDescription: Return Results of SQLAlchemy Search Query


code:
import os
import io

filelst = []
allfile = os.listdir(os.getcwdu())
for file in allfile:
        if os.path.isfile(file):
            filelst.append(file)

w = io.open(os.getcwd()+'\\_filelist.txt','w+', encoding="utf-8")

for file in allfile:
    w.write(file)
    w.write("\n")
w.close()

rawDescription: How to make this python(2.7) scripts works with unicode filename?

description: Make this python(2.7) scripts works with unicode filename


code:
import json

try:
    with open('scores', 'r') as f:
        player_scores = json.load(f)
except IOError:
    # no such file, create an empty dictionary
    player_scores = {}

name = input("Enter new player's name: ").upper()
# create a complete, new dictionary
players_scores[name] = {'GOLF': 0, 'MON DEAL': 0}

with open('scores', 'w') as f:
    json.dump(player_scores, f)

rawDescription: file IO with defaultdict

description: File IO with defaultdict


code:
from scipy.optimize import curve_fit

def f(x, A, B): # this is your 'straight line' y=f(x)
    return A*x + B

A,B = curve_fit(f, x, y)[0] # your data x, y to fit

rawDescription: Least-Squares Fit to a Straight Line python code


code:
d = datetime.datetime.now()

a = d.strftime('date_%Y%m%d_%H%M%S_%f')
os.mkdir(a)

rawDescription: python variable in the function call

description: Python variable in the function call


code:
my_pos = {}
for key in pos.keys():
     x,y = pos[key]
     my_pos[key] = (-x,-y)#or whatever function you want
nx.draw_networkx(H, pos=my_pos, with_labels=False, node_size = 10)

rawDescription: Matplotlib: How to mirror an image with respect to both axes?


code:
def test(var1=None):
    return { var1: var1 }

def calltest():
    d = test()
    print(d['var1'])

def disp(router, request, response):
    rv = router.default_dispatcher(request, response)
    # turn dict into json and craft the response
    return webapp2.Response(json.dumps(rv))
    # alternatively, you could make your handlers return objects with a .json()
    # method and call that

app = webapp2.WSGIApplication([
    webapp2.Route(r'/test/<var1>', handler=test, methods="GET"),
])

app.router.set_dispatcher(disp)

rawDescription: How can you determine if webapp2 called your function or if it was another method in Python?

description: Determine if webapp2 called your function or if it was another method in Python


code:
from PIL import Image
import glob
images = []
for filename in glob.glob('./images/*.gif'): # i.e. gif images
    im=Image.open(filename)
    images.append(im)

rawDescription: How to load set of images in a directory to a arraylist in python

description: Load set of images in a directory to a arraylist in python


code:
total = 0
for i in range(10):
    total += int(input("\nEnter price here: "))
grand_total = 18 * total / 100 + total
print("\nThe total amount will equal to", grand_total, "(with 18% V.A.T)")

rawDescription: How do I iterate in Python?

description: Iterate in Python


code:
class EmployeeInline(admin.StackedInline):
    model = Employee
    can_delete = False
    verbose_name_plural = 'employee'
    fk_name = 'manager_id'

rawDescription: Extending Django User Model: ForeignKey Error


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

        self.setWindowTitle("Window With Tabs")
        self.setGeometry(50,50,400,400)

        layout = QVBoxLayout(self)

        oTabWidget = QTabWidget(self)
        layout.addWidget(oTabWidget)

rawDescription: PyQt5 - Can QTabWidget content extend up to Main Window edges, even with no content?


code:
# create a dict of find keys and replace values
findlines = open('find.txt').read().split('\n')
replacelines = open('replace.txt').read().split('\n')
find_replace = dict(zip(findlines, replacelines))

with open('data.txt') as data:
    with open('new_data.txt', 'w') as new_data:
        for line in data:
            for key in find_replace:
                if key in line:
                    line = line.replace(key, find_replace[key])
            new_data.write(line)

rawDescription: How to find and replace multiple lines in text file?

description: Find and replace multiple lines in text file


code:
class departments(models.Model):
   priority = models.TextField('prioriy')
   department = models.TextField('Department')
   emp = models.IntegerField('Emp_id')
   empname = models.TextField('EmpName')
   def __unicode__(self):
      return department

   def save(self, force_insert=False, force_update=False, using=None,      update_fields=None):
       self.emp = ur_hash_func(self.emp)
       return models.Model.save(self, force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)

rawDescription: Is it possible to add new field dynamicaly through django admin panel


code:
from matplotlib import pyplot as plt
import numpy as np

x = np.arange(0,3,.25)
y = np.sin(x)
txt = '''
    Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
    reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
    pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
    culpa qui officia deserunt mollit anim id est laborum.'''

fig = plt.figure()
ax1 = fig.add_axes((.1,.4,.8,.5))
ax1.bar(x,y,.2)
fig.text(.1,.1,txt)
plt.show()

rawDescription: Is there a way of drawing a caption box in matplotlib


code:
def p(x,n=0):
    if n == 0:
        n = int(x.bit_length() * 0.3)
    if n < 100:
        return str(x)
    n >>= 1
    l = 10**n
    a,b = divmod(x, l)
    upper = p(a,n)
    lower = p(b,n).rjust(n, "0")
    return upper + lower

rawDescription: Slow Big Int Output in python

description: Slow Big Int Output in python


rawDescription: Why Python multiprocessing is running sequencially?


code: prepopulated_fields = {'slug': ('title',), }

rawDescription: Is there an easy way to populate SlugField from CharField?


code:
setup = """
from Crypto.Cipher import AES
import os
newFile = []
fileData = open('filename').read()
"""
stmt = """
key = os.urandom(32)
cipher = AES.new(key, AES.MODE_CFB)
for lines in fileData:
    newFile = cipher.encrypt(lines)"""

tt = timeit.Timer(stmt, setup)
tt.repeat()

rawDescription: Can't use a data obj with timeit.Time module in python


code:
with open("big.data", "r+b") as f:
    # memory-map the file, size 0 means whole file
    mm = mmap.mmap(f.fileno(), 0)
    # write byte 42 to position 12345678
    mm[12345678] = 42
    # add 1 to byte at position 12345679
    mm[12345679] += 1
    mm.close()

rawDescription: Overwrite nth byte of file

description: Overwrite nth byte of file


code:
import turtle

screen = turtle.Screen()
turtle = turtle.Turtle()

def turtle_headto(x, y):
    turtle.left(turtle.towards(x, y) - turtle.heading())
    turtle.goto(x, y)

screen.onscreenclick(turtle_headto)

screen.mainloop()

rawDescription: How to make a turtle object look at where the mouse has clicked

description: Make a turtle object look at where the mouse has clicked


code:
from collections import Counter
protein = "AGTTTCAGGAC"
Counter(protein[i:i+6] for i in range(len(protein)-5))

rawDescription: finding frequent string patterns using python

description: Finding frequent string patterns using python


code:
form1 = PersonForm(request.POST or None, prefix='person')
form2 = InstrumentForm(request.POST or None, prefix='instrument')

if form1.is_valid() and form2.is_valid():
  form2.save()
  form1.save()
  # return redirect
# render forms

rawDescription: Subclassing multiple forms in Django

description: Subclassing multiple forms in Django


code:
def foo(x=None,y=None,z=None):
    return x+y+z
s = foo(*(1,2),z=3)
s

rawDescription: Partially unpack parameters in python

description: Partially unpack parameters in python


rawDescription: how to show a django ModelForm field as uneditable

description: Show a django ModelForm field as uneditable


code:
def resizeImg(sourceFile, destFile, width, height):
  with Image(width=width, height=height) as outerImg:
    with Image(filename=sourceFile) as img:
      img.transform(resize="%dx%d>" % (width, height))
      outerImg.format = img.format.lower()
      outerImg.composite(img, left=(width - img.width) / 2, top=(height - img.height) / 2)
      outerImg.save(filename=destFile)

rawDescription: Python Wand how to resize keeping aspect ratio and filling in the remaining space with an transparency


code: subprocess.call(["find", ".", "-exec", "touch", "{}", ";"])

rawDescription: How do I execute a complex shell find command from Python?

description: Execute a complex shell find command from Python


code:
lda = LdaModel(corpus, num_topics=10)

lda.update(other_corpus)

rawDescription: Latent Dirichlet Allocation using Gensim on more than one corpus


rawDescription: Reshaping Pandas data frame (a complex case!)


code:
import struct

def send_data(file_descriptor, data):
    length = struct.pack('>L', len(data))
    packet = "%s%s" % (length, data)
    file_descriptor.write(packet)

def read_data(file_descriptor):
    binary_length = file_descriptor.read(4)
    length = struct.unpack('>L', binary_length)[0]

    data = ''
    while len(data) < length:
        data += file_descriptor.read(length - len(data))

rawDescription: Sending data chunks over named pipe in linux


code:
from Tkinter import *

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)

        self.text = Entry(self)
        self.text.pack({"side": "left"})

        self.but1 = Button(self)
        self.but1["text"] = "a"
        self.but1.bind("<Button-1>",  self.do)
        self.but1.pack({"side": "left"})

        self.but2 = Button(self)
        self.but2["text"] = "b"
        self.but2.bind("<Button-1>",  self.do)
        self.but2.pack({"side": "left"})

        self.pack()

    def do(self, event):
        widget = event.widget
        self.text.delete(0, END)
        self.text.insert(0, widget["text"])

root = Tk()
app = Application(master=root)
app.mainloop()

rawDescription: Button content into the Entry

description: Button content into the Entry


code:
i = ctypes.c_uint(0)
i.value -= 1
i
i.value += 1
i

rawDescription: Java/Python MD5 implementation- how to overcome unsigned 32-bit requirement?


code:
K=5
N=3
src=[['1']*n+['4']*(K-n) for n in xrange(K-N,N+1)]
set(x for s in src for x in itertools.permutations(s))

rawDescription: Python implementation for permutation given specific conditions


code:
path1 = [0, 3, 1]
splitsOfPath1 = zip(path1, path1[1::])
splitsOfPath1
path2 = [0, 3, 2, 1]
splitsOfPath2 = zip(path2, path2[1::])
splitsOfPath2

rawDescription: Break a list into an overlapping list of tuple in python


code:
df
f = df.replace([0,'NA'], np.nan).apply(lambda x: any(~x.isnull()))
f
df.loc[:,f]

rawDescription: Python Pandas dropping all columns with nans, 0, and NA from dataframe


code:
class trueint(int):
    def __nonzero__(self):
        return True
    __bool__ = __nonzero__    # Python 3

truezero = trueint(0)

if truezero:
    print("yep, this zero is true!")

rawDescription: If not x % y: Do something

description: If not x % y: Do something


code:
from django.db.models import Q

Foo.objects.filter(Q(fk_field=fk_value) | Q(fk_field=None))

rawDescription: How to filter Django objects to accept matches and NULLs?

description: Filter Django objects to accept matches and NULLs


code:
class MyResource(ModelResource):
    class Meta:
        queryset = MyModel.objects.all()
        resource_name = 'environment'
        list_allowed_methods = ['get', 'post']
        authentication = ApiKeyAuthentication()
        authorization = Authorization()

    # Only allow creation of objects belonging to the user
    def obj_create(self, bundle, **kwargs):
        return super(EnvironmentResource, self).obj_create(bundle, user=bundle.request.user)

    # Only allow accessing resources for this user
    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(user=request.user)

rawDescription: Model resource with users as FK TastyPie API


code:
a = np.arange(12).reshape(3,4)
a
np.delete(a, [1,3], axis=1)

rawDescription: remove a specific column in numpy

description: Remove a specific column in numpy


code:
from Queue import Queue
from threading import Thread

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done

rawDescription: Execute other commands while one is already running


code:
if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
    here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

rawDescription: Very Long If Statement in Python

description: Very Long If Statement in Python


code:
#!/usr/bin/env python2
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from multiprocessing import Pool

class Form(QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.browser = QTextBrowser()
        self.setWindowTitle('Just a dialog')

class MySplashScreen(QSplashScreen):
    def __init__(self, animation, flags):
        # run event dispatching in another thread
        QSplashScreen.__init__(self, QPixmap(), flags)
        self.movie = QMovie(animation)
        self.connect(self.movie, SIGNAL('frameChanged(int)'), SLOT('onNextFrame()'))
        self.movie.start()

    @pyqtSlot()
    def onNextFrame(self):
        pixmap = self.movie.currentPixmap()
        self.setPixmap(pixmap)
        self.setMask(pixmap.mask())

# Put your initialization code here
def longInitialization(arg):
    time.sleep(arg)
    return 0
if __name__ == "__main__":
    import sys, time

    app = QApplication(sys.argv)

    # Create and display the splash screen
#   splash_pix = QPixmap('a.gif')
    splash = MySplashScreen('a.gif', Qt.WindowStaysOnTopHint)
#   splash.setMask(splash_pix.mask())
    #splash.raise_()
    splash.show()
    app.processEvents()

    # this event loop is needed for dispatching of Qt events
    initLoop = QEventLoop()
    pool = Pool(processes=1)
    pool.apply_async(longInitialization, [2], callback=lambda exitCode: initLoop.exit(exitCode))
    initLoop.exec_()

    form = Form()
    form.show()
    splash.finish(form)
    app.exec_()

rawDescription: Using a gif in Splash Screen in pyqt

description: Using a gif in Splash Screen in pyqt


code:
class MyData:
    def __init__(self, data):
        "Initialize MyData from a sequence"
        self.data = data

    @classmethod
    def fromfilename(cls, filename):
        "Initialize MyData from a file"
        data = open(filename).readlines()
        return cls(data)

    @classmethod
    def fromdict(cls, datadict):
        "Initialize MyData from a dict's items"
        return cls(datadict.items())

MyData([1, 2, 3]).data
MyData.fromfilename("/tmp/foobar").data
MyData.fromdict({"spam": "ham"}).data

rawDescription: overloading __init__ in python

description: Overloading __init__ in python


code:
if lst[0] == 1 and lst[1] == 0:
    return 0
if lst[len(lst)-1] == 1 and lst[len(lst)-2] == 0:
    return 1
for i in range(1,len(lst)-1):
    if lst[i] == 1 and lst[i-1] == 0 and lst[i+1] == 0:
        return i

rawDescription: Searching for an isolated list element

description: Searching for an isolated list element


rawDescription: Regex - Combining an 'or' with a 'look-behind'


code:
myprog.py
pause

rawDescription: How to launch a Python file on Windows 7?

description: Launch a Python file on Windows 7


code:
import tkinter
from tkinter import ttk
from tkinter import PhotoImage
import os

root = tkinter.Tk()
list_files = os.listdir(".")
for path in list_files:
    if path.endswith(".gif"):
        drink = PhotoImage(file=path)
        b1 = ttk.Button(root, image=drink, text="Hello", compound="right")
        b1.pack()
        l1 = ttk.Label(root, image=drink)
        l1.image = drink
        l1.pack()

root.mainloop()

rawDescription: Python-Tkinter, for-loop to create pictured button


code:
import requests
session = requests.Session()
session.cookies.get_dict()
response = session.get('http://google.com')
session.cookies.get_dict()

rawDescription: python requests get cookies

description: Python requests get cookies


code: foo.setdefault('bar', 123)

rawDescription: Pythonic way of setting a default

description: Pythonic way of setting a default


code:
def variant1a(node_name, graph):
    """Include a docstring, too!"""
    for node in graph.get_nodes():
        if node.get_name() == node_name:
            return node, graph
    return create_node(node_name, graph)

rawDescription: Python coding style - multiple return statements


code:
import paramiko
import os

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('localhost',username='****')

apath = '/var/log'
apattern = '"*.log"'
rawcommand = 'find {path} -name {pattern}'
command = rawcommand.format(path=apath, pattern=apattern)
stdin, stdout, stderr = ssh.exec_command(command)
filelist = stdout.read().splitlines()

ftp = ssh.open_sftp()
for afile in filelist:
    (head, filename) = os.path.split(afile)
    print(filename)
    ftp.get(afile, './'+filename)
ftp.close()
ssh.close()

rawDescription: How can I get all .log and .txt files when I SSH into a server

description: Get all .log and .txt files when I SSH into a server


code:
a = [('John', 'first@email.com'), ('John', 'second@email.com'), ('Jack', 'third@email.com')]
[dict([('sender', x[0]), ('email',x[1])]) for x in a]

rawDescription: Python 3: list of 2 elements into dictionary


code:
import pylab

my_labels = ['food', 'music', 'clothes']

fig = pylab.figure()
fig.text(0.4,0.95,"Consumption by Region")

ax1 = fig.add_subplot(2,2,1)
ax1.pie([1,2,3])
ax1.text(0.6, 1, "North West")

ax2 = fig.add_subplot(2,2,2)
ax2.pie([6,4,3])
ax2.text(0.6, 1, "North East")

ax3 = fig.add_subplot(2,2,3)
ax3.pie([1,4,3])
ax3.text(0.6, 1, "South West")

ax4 = fig.add_subplot(2,2,4)
ax4.pie([9,1,3])
ax4.text(0.6, 1, "South East")

pylab.legend(my_labels, title="Legend", loc=(-1.5,0.9))

pylab.show()

rawDescription: Don't display labels in subplot

description: Don't display labels in subplot


rawDescription: SQLAlchemy: a better way for update with declarative?


code: sum(map(predicate, seq)) == 1

rawDescription: Idiomatic Python has_one

description: Idiomatic Python has_one


rawDescription: Find simultaneous multiple "Text" options in HTML


code:
def add(value):
    # code written by me
    add.state = add.state+1
    do_something()
add.state = 0

rawDescription: Python: remember module function call values


code:
def maxdrop(p):
    bestdrop = 0
    wheredrop = -1,-1
    i = 0
    while i < len(p) - 1:
        if p[i+1] < p[i]:
            bestlocal = p[i+1]
            wherelocal = i+1
            j = i + 1
            while j < len(p) - 1 and p[j + 1] < p[i]:
                j += 1
                if p[j] < bestlocal:
                    bestlocal = p[j]
                    wherelocal = j
            if p[i] - bestlocal > bestdrop:
                bestdrop = p[i] - bestlocal
                wheredrop = i, wherelocal
            i = j+1
        else:
            i += 1
    return bestdrop,wheredrop

rawDescription: Python: Write a program to find the time period(s) of the largest price drop(s)


code:
d = {'a': [1,2,3], 'b': [4,5,6], 'c': [7,8,9]}

button = QToolButton()

def callback_factory(k, v):
    return lambda: button.setText('{0}_{1}'.format(k, v))

menu = QMenu()
for k, vals in d.items():
    sub_menu = menu.addMenu(k)
    for v in vals:
        action = sub_menu.addAction(str(v))
        action.triggered.connect(callback_factory(k, v))

button.setMenu(menu)

rawDescription: How to create combobox with combobox inside using PyQt

description: Create combobox with combobox inside using PyQt


code: newestFile = os.path.basename(max(glob.iglob(path + '*.txt'), key=os.path.getctime))

rawDescription: glob.iglob Remove path from filename

description: Glob.iglob Remove path from filename


code: int(max(min(currentHP / float(maxHP) * health_bar_width, health_bar_width), 0))

rawDescription: Pygame Scaling Healthbar

description: Pygame Scaling Healthbar


code:
import re
term_list = ["when","is","and"]
regexp = re.compile(r"|".join(term_list), re.IGNORECASE)
db.my_collection.find_one({"title": regexp })

rawDescription: List of substring or regex match in a field in pymongo


code:
from itertools import takewhile

if K is None:
    condition = lambda x: True
else:
    condition = lambda x: x[0] < K

for i,line in takewhile(condition, enumerate(af)):
    bf.write(line)

rawDescription: avoiding code duplication in Python code

description: Avoiding code duplication in Python code


code:
import nltk
sentence = """At eight o'clock on Thursday morning
Arthur didn't feel very good."""
tokens = nltk.word_tokenize(sentence)
tokens

rawDescription: How do I tokenize a string sentence in NLTK?

description: Tokenize a string sentence in NLTK


code:
if name in cls.__dict__:
    # ... your code here ...
    pass

rawDescription: Check if class attribute was defined or derived in given class


code: points= [list(map(int,v.split())) if v.strip().lower() != "j" else "JUMP" for v in vlist]

rawDescription: turn a list of strings into a list of xyz cooridnates python

description: Turn a list of strings into a list of xyz cooridnates python


code:
radio_var = IntVar(value=0)

Radio_1 = Radiobutton(the_window,
                      text="First",
                      variable=radio_var,  # <---
                      command=change_first_set_colour,  # <---
                      value=1)
Radio_1.place(x=50, y=165)  # <---

...

Radio_2 = Radiobutton(the_window,
                      text="Second",
                      variable=radio_var,  # <---
                      command=change_second_set_colour,  # <---
                      value=2)
Radio_2.place(x=180, y=165)  # <---

...

Radio_3 = Radiobutton(the_window,
                      text="Third",
                      variable=radio_var,  # <---
                      command=change_third_set_colour,  # <---
                      value=3)
Radio_3.place(x=345, y=165)  # <---

rawDescription: Radiobuttons in Python (TKinter)

description: Radiobuttons in Python (TKinter)


code:
# scripts have access to these vars, which can be useful for loading unique data
trans.thread_num = self.thread_num
trans.process_num = self.process_num

rawDescription: Multiprocess synchronization in python

description: Multiprocess synchronization in python


rawDescription: How to check if Python3 was built with '--enable-shared'?

description: Check if Python3 was built with '--enable-shared'


rawDescription: Convert a list of bytes to a byte string


code:
if category == 'bulky item':
        items.append((Address,
             x,
            y,
              x,
              y,
              ReasonCode,
              SRNumber,
             SRNumber,
             FullName,
              ResolutionCode,
              HomePhone,
              CreatedDate,
              UpdatedDate,
              BulkyItemInfo,
             k_bulky_comm,
              ServiceDate,
             CYLA_DISTRICT,
             SCCatDesc,
            # ServiceNotes,
             Prior_Resolution_Code,
             CYLA_DISTRICT,
            ))
elif category == 'e-waste':
        items.append((Address,
             x,
            y,
              x,
              y,
              ReasonCode,
              SRNumber,
             SRNumber,
             FullName,
              ResolutionCode,
              HomePhone,
              CreatedDate,
              UpdatedDate,
              BulkyItemInfo,
             k_manual_pickup_comm,
              ServiceDate,
             CYLA_DISTRICT,
             SCCatDesc,
            # ServiceNotes,
             Prior_Resolution_Code,
             CYLA_DISTRICT,
            ))

rawDescription: Using OR operator in NumPy Array to Append multiple items


code:
@app.route('/docs', defaults={'filename': 'index.html'})
@app.route('/docs/<path:filename>')
def documentation(filename):
    return flask.send_from_directory(
        app.config['UPLOAD_FOLDER'],
        filename
    )

rawDescription: How to use sphinx with flask?

description: Use sphinx with flask


code:
from functools import reduce

val = reduce(lambda r, f: f(r), (f1, f2, f3), arg)

rawDescription: Is there a chain calling method in Python?


code:
from fs.memoryfs import MemoryFS
from fs.expose import fuse
fs = MemoryFS()
mp = fuse.mount(fs,"/mnt/my-memory-fs")
mp.unmount()

rawDescription: unmount fuse fs from python script

description: Unmount fuse fs from python script


rawDescription: How to index a Python list

description: Index a Python list


code:
x = np.append(x_nose, x_mid)
x = np.append(x, x_tail )
r = np.append(r_nose, r_mid)
r = np.append(r, r_tail )

plt.plot(x,r,'k',linewidth=2,antialiased=True)

rawDescription: Matplotlib lines do not join smoothly, Python


code:
import sys
sys.stdin = open('input.txt', 'r')

rawDescription: Pass input file to python debugger in Aptana


code:
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
                facecolors=cm.coolwarm(F), shade=False)

rawDescription: Matplotlib 3D Plot Colors Appear Darker Than Normal


code:
lines1 = open(path1).readlines()
lines2 = open(path2).readlines()

for i in lines1:
    for j in lines2:
        if j.startswith(i.rstrip()):
            print(j.rstrip())
            break

rawDescription: How to compare two files and extract some data with Python

description: Compare two files and extract some data with Python


code:
from peewee import SelectQuery

# this does the uuid conversion in python
class UUIDField(Field):
    db_field = 'binary(16)'

    def db_value(self, value):
        if value is None: return None

        value = value.translate(None, '-')
        query = SelectQuery(self.model_class, fn.UNHEX(value).alias('unhex'))
        result = query.first()
        value = result.unhex
        return value

    def python_value(self, value):
        if value is None: return None
        query = SelectQuery(self.model_class, fn.HEX(value).alias('hex'))
        result = query.first()
        value = '{}-{}-{}-{}-{}'.format(
            result.hex[0:8],
            result.hex[8:12],
            result.hex[12:16],
            result.hex[16:20],
            result.hex[20:32]
        )
        return value

rawDescription: peewee + MySQL, How to create a custom field type that wraps SQL-built ins?

description: Peewee + MySQL, How to create a custom field type that wraps SQL-built ins


code:
import numpy as np
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

G = nx.Graph()
G.add_edges_from([(0,1),(1,2),(2,0)])
fig = plt.figure(figsize=(8,8))
pos=nx.graphviz_layout(G)
nc = np.random.random(3)
nodes = nx.draw_networkx_nodes(G,pos,node_color=nc)
edges = nx.draw_networkx_edges(G,pos)

def update(n):
  nc = np.random.random(3)
  nodes.set_array(nc)
  return nodes,

anim = FuncAnimation(fig, update, interval=50, blit=True)

rawDescription: Using NetworkX with matplotlib.ArtistAnimation


code:
df = ...
df_modified = df[df.columns[:-1]]
df_modified.columns = df.columns[1:]

rawDescription: How to exclude first word in Pandas header?

description: Exclude first word in Pandas header


code:
sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
sfreq.valtext.set_visible(False)

rawDescription: How to remove/hide matplotlib slider values

description: Remove/hide matplotlib slider values


code:
def substring_test(x, y):
    if len(y) > len(x):
        return -1
    for i in range(len(x) - len(y) + 1):
        if x[i:i+len(y)] == y:
            return i
    return -1

rawDescription: How to find an index for a substring?

description: Find an index for a substring


code:
#original data, two 2x2 images, normalized
x = rand(2,2)
x/=sum(x)
y = rand(2,2)
y/=sum(y)

#initial guess of the flux matrix
# just the product of the image x as row for the image y as column
#This is a working flux, but is not an optimal one
F = (y.flatten()*x.flatten().reshape((y.size,-1))).flatten()

#distance matrix, based on euclidean distance
row_x,col_x = meshgrid(range(x.shape[0]),range(x.shape[1]))
row_y,col_y = meshgrid(range(y.shape[0]),range(y.shape[1]))
rows = ((row_x.flatten().reshape((row_x.size,-1)) - row_y.flatten().reshape((-1,row_x.size)))**2)
cols = ((col_x.flatten().reshape((row_x.size,-1)) - col_y.flatten().reshape((-1,row_x.size)))**2)
D = np.sqrt(rows+cols)

D = D.flatten()
x = x.flatten()
y = y.flatten()
#COST=sum(F*D)

#cost function
fun = lambda F: sum(F*D)
jac = lambda F: D
#array of constraint
#the constraint of sum one is implicit given the later constraints
cons  = []
#each row and columns should sum to the value of the start and destination array
cons += [ {'type': 'eq', 'fun': lambda F:  sum(F.reshape((x.size,y.size))[i,:])-x[i]}     for i in range(x.size) ]
cons += [ {'type': 'eq', 'fun': lambda F:  sum(F.reshape((x.size,y.size))[:,i])-y[i]} for i in range(y.size) ]
#the values of F should be positive
bnds = (0, None)*F.size

from scipy.optimize import minimize
res = minimize(fun=fun, x0=F, method='SLSQP', jac=jac, bounds=bnds, constraints=cons)

rawDescription: Compare similarity of images using OpenCV with Python


code:
class CRUDCursor(object):
    def __init__(self, c, crud):
        self.crud = crud
        self.cursor = however_you_get_an_actual_sql_cursor(c)

    def get(self, target, where):
        #this is strictly for illustration purposes, I realize all
        #the vulnerabilities this leaves me exposed to.
        query = "SELECT {fields} FROM {table} WHERE {target} = {where}"
        query.format(fields=self.crud.fields, table=self.crud.table,
                     target=target, where=where)
        self.cursor.execute(query)
        # you may want this to return something as well?

class CRUD(object):
    def __init__(self, table, public_fields):
        self.table = table
        self.public_fields = public_fields

    def fields(self):
        return ', '.join([f for f in self.public_fields])

    # no get method

    def cursor(self, cursor):
        return CRUDCursor(self, cursor)

rawDescription: Python descriptors to chain methods

description: Python descriptors to chain methods


code: [a_i - b_i for a_i, b_i in zip(a, b)]

rawDescription: Subtracting 2 lists in Python

description: Subtracting 2 lists in Python


code: sorted(list1, key=lambda x: re.sub('[^A-Za-z]+', '', x).lower())

rawDescription: How to sort list of String without considering Special characters and with case insensitive

description: Sort list of String without considering Special characters and with case insensitive


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.label = QtGui.QLabel('Count = 0', self)
        self.button = QtGui.QPushButton('Start', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.label)
        layout.addWidget(self.button)
        self._active = False

    def handleButton(self):
        if not self._active:
            self._active = True
            self.button.setText('Stop')
            QtCore.QTimer.singleShot(0, self.runLoop)
        else:
            self._active = False

    def closeEvent(self, event):
        self._active = False

    def runLoop(self):
        from time import sleep
        for index in range(100):
            sleep(0.05)
            self.label.setText('Count = %d' % index)
            QtGui.qApp.processEvents()
            if not self._active:
                break
        self.button.setText('Start')
        self._active = False

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: Create loop that doesn't lock up the window Pyqt4


code:
import os
for top in ['/tmp/bar', '/tmp/baz', '/tmp/bat']:
    for dirpath, dirs, files in os.walk(top):
        for filename in files:
            with open(os.path.join(dirpath, filename), 'a') as fp:
                fp.write("Kilroy\n")

rawDescription: Need to modify files top to bottom using python's os walk. Generator object?


code: np.isclose(arr_f, a, atol=0.01).any()

rawDescription: Check if float is close to any float stored in array


code:
import win32api
path = r'c:\python27\lib\site-packages\win32\win32api.pyd'
info = win32api.GetFileVersionInfo(path, '\\')
'{}.{}.{}.{}'.format(
    win32api.HIWORD(info['FileVersionMS']),
    win32api.LOWORD(info['FileVersionMS']),
    win32api.HIWORD(info['FileVersionLS']),
    win32api.LOWORD(info['FileVersionLS']))

rawDescription: get version of python module.pyd

description: Get version of python module.pyd


rawDescription: arranging the values of vector to lists in Python

description: Arranging the values of vector to lists in Python


code:
class Parent(object):
    def __init__(self):
        for attr in self.ATTRS:
            setattr(self, attr, 0)

class Child(Parent):
    #class variable
    ATTRS = ['attr1', 'attr2', 'attr3']

    def __init__(self):
        super(Child, self).__init__()

rawDescription: Python parent class accessing class variable of child class


code:
keyword = 'keyword'
alphabet = 'abcfghjlmnpqstuvxz'
# Make an empty matrix -- could also use numpy chararray for this, but
# this is good enough for this example.
matrix = [[None] * 5 for i in range(5)]

full_string = keyword + alphabet

for i in range(25):
   matrix[i // 5][i % 5] = full_string[i]

for row in matrix:
   print(row)

rawDescription: Python: Insert two sets of chars into a matrix


code: w.writerows(c.split(' | ') for c in content)

rawDescription: Python writerows trouble

description: Python writerows trouble


code:
cdf = np.cumsum([0, 0.02, 0.08, 0.16, 0.29, 0.45])     # leftmost bin edge = 0
counts, edges = np.histogram(np.random.rand(100), bins=cdf)

print(counts)
# [ 4,  8, 16, 30, 42]

rawDescription: How can I generate a random sample of bin counts given a sequence of bin probabilities?

description: Generate a random sample of bin counts given a sequence of bin probabilities


code:
from collections import namedtuple

Weapon = namedtuple('Weapon', ['damage', 'price'])

weapons = {
    'pistol': Weapon(4, 5),
    'cannon': Weapon(4, 5),
    # ...
}

def fight():
    weapon_name = raw_input("What weapon would you like to use?")
    enemy.health -= weapons[weapon_name].damage

rawDescription: Referencing Class properties with variables in Python 2.7


code:
class HexFile(object):
    def __init__(self, fp, wordsize=4):
        self.fp = fp
        self.ws = wordsize
    def __iter__(self):
        while True:
            data = self.fp.read(self.ws)
            if not data: break
            yield data.encode('hex')

rawDescription: Python: Seeing all files in Hex

description: Python: Seeing all files in Hex


code:
def f():
  []
  list()
  {}
  dict()

dis.dis(f)

rawDescription: Initializing empty Python data structures


rawDescription: Django group / aggregation

description: Django group / aggregation


code:
your_new_migration.py
def update_slugs(apps, schema_editor):
    SomeModel = apps.get_model("some_app", "SomeModel")

    for instance in SomeModel.objects.all():
        instance.slug = '%s-%s' % (instance.slug, instance.object_id)
        instance.save()

class Migration(migrations.Migration):

    dependencies = [
        # ... your existing dependencies
    ]

    operations = [
        # add this operation ...
        migrations.RunPython(update_slugs, reverse_code=migrations.RunPython.noop),

        # ... before your original migration, such as:
        # migrations.AlterField(
        #     model_name='somemodel',
        #     name='slug',
        #     field=models.CharField(unique=True),
        # ),
    ]

rawDescription: migrate model slug field to unique for existing database

description: Migrate model slug field to unique for existing database


code:
if __name__ == '__main__':
    import signal
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    your_application_main()

rawDescription: keyboard interrupt with with python gtk?

description: Keyboard interrupt with with python gtk


code: sum(1 for i in it)

rawDescription: What's the shortest way to count the number of items in a generator/iterator?


code:
date_div = "Blah blah blah, Updated: Aug. 23, 2012"
date_div.split('Updated: ')
date_div.split('Updated: ')[-1]

rawDescription: Use Regex re.sub to remove everything before and including a specified word


code:
a = pexpect.spawn(['ssh', 'remote-host', './script.sh', 'a'])
a.expect('something')

b = pexpect.spawn(['ssh', 'remote-host', './script.sh', 'b'])
b.expect('something else')

# ...

# to kill ALL of the children
a.sendcontrol('c')
a.close()

b.sendcontrol('c')
b.close()

rawDescription: Send Ctrl-C to remote processes started via subprocess.Popen and ssh


code:
#!/usr/bin/env python

import gtk
from gimpfu import *

def plugin_main() :

    message = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK)
    message.set_markup("Thank you Frederic Jaume -> \nhttp://www.exp-media.com/content/extending-gimp-python-python-fu-plugins-part-4")
    message.run()
    gimp.quit()

register(
    "helloworld",
    "Saying Hi",
    "Saying Hello to the World",
    "William Crandell <william@crandell.ws>",
    "William Crandell <william@crandell.ws>",
    "2015",
    "Hello Gimp",
    "",
    [],
    [],
    plugin_main,
    menu = "<Toolbox>/Hello/"
)

main()

rawDescription: Gimp Python plugin without requiring a currently open image? (Plug is to Open/Export/Close image via FileChooserDialog)


code:
def list_string(strn):
  level=[]
  def permute(prefix, suffix):
    level.append(prefix)
    if len(suffix)==0:
       return
    for i in range(len(suffix)):
      permute(prefix + suffix[i], suffix[:i]+suffix[i+1:])
  permute("",strn)
  return level

t = list_string("hey")
# ['', 'h', 'he', 'hey', 'hy', 'hye', 'e', 'eh', 'ehy', 'ey', 'eyh', 'y', 'yh', 'yhe', 'ye', 'yeh']

rawDescription: How to get all possible subset of the string in python

description: Get all possible subset of the string in python


code:
def change_value_at_index(tpl, index, value):
    # Your code here
    if index >= len(tpl) or index < -len(tpl):
        return tpl
    else:
        a = tpl[:index] + (value,) + tpl[index+1:]
        return a

rawDescription: How to implement a function change_value_at_index that takes in three parameters: a tuple, an index, and a new value?

description: Implement a function change_value_at_index that takes in three parameters: a tuple, an index, and a new value


code:
df = DataFrame({'A' : range(10) },index=pd.date_range('20130101',freq='2S',periods=10,tz='US/Eastern'))
df
idx = pd.date_range('20130101 00:00:00',periods=20,freq='5s',tz='US/Eastern')
df.reindex(idx,method='nearest')

rawDescription: Wierd Pandas DataFrame Index type conversion


code: ScatterLayout(do_scale=False, do_translation_x=False, do_translation_y=False, do_rotation=False)

rawDescription: Rotated camera input in Kivy

description: Rotated camera input in Kivy


code:
#Get the stream index from the packet
streamIndex = packet.xpath('proto/field[@name="tcp.stream"]')[0].attrib['show']
#Use that stream index to get the matching response packet
return packet.xpath('/pdml/packet[proto/field[@name="tcp.stream" and @show="' + streamIndex + '"] and proto/field[@name="http.request.full_uri"]]')[0]

rawDescription: Associating HTTP Requests with Responses in large packet capture


code:
import bisect
class dictvs(dict):
    def __init__(self):
        self._list = []

    def __setitem__(self, key, value):
        old = self.get(key)
        if old is None:
            bisect.insort(self._list, value)
            dict.__setitem__(self, key, value)
        else:
            oldpos = bisect.bisect_left(self._list, old)
            newpos = bisect.bisect_left(self._list, value)
            if newpos > oldpos:
                newpos -= 1
                for i in xrange(oldpos, newpos):
                    self._list[i] = self._list[i + 1]
            else:
                for i in xrange(oldpos, newpos, -1):
                    self._list[i] = self._list[i - 1]
            self._list[newpos] = value
            dict.__setitem__(self, key, value)

    def __delitem__(self, key):
        old = self.get(key)
        if old is not None:
            oldpos = bisect.bisect(self._list, old)
            del self._list[oldpos]
        dict.__delitem__(self, key)

    def values(self):
        return list(self._list)

rawDescription: Value-sorted dict for Python?

description: Value-sorted dict for Python


code: sys.path.extend(map(os.path.abspath, ['other1/', 'other2/', 'yourlib/']))

rawDescription: Importing In Python

description: Importing In Python


code:
wmap_map_I_smoothed = hp.smoothing(wmap_map_I, fwhm=60, arcmin=True)
hp.mollview(wmap_map_I_smoothed, min=-1, max=1, title='Map smoothed 1 deg')

rawDescription: Fast way using healpy to get convolution of a healpy map and a 2D Gaussian


code:
import datetime as dt
mytime = dt.datetime.strptime('0130','%H%M').time()
mydatetime = dt.datetime.combine(dt.date.today(), mytime)

rawDescription: Easiest way to combine date and time strings to single datetime object using Python


code: first_column = [x[0] for x in mysql_rows]

rawDescription: Python list format from mysqldb

description: Python list format from mysqldb


code:
with open ("data.txt", "r") as myfile:
    data=myfile.read().replace('\n', '')

rawDescription: Content of text file as a input to python script


code:
for i in p.finditer(s1):
     i.group(1)

rawDescription: Python RE - different matching for finditer and findall


rawDescription: Updating Pandas dataframe with "new information" when it includes NaNs


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.edit = QtGui.QLineEdit(self)
        self.edit.installEventFilter(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)

    def eventFilter(self, source, event):
        if source is self.edit:
            if event.type() == QtCore.QEvent.MouseMove:
                pos = event.globalPos()
                print('pos: %d, %d' % (pos.x(), pos.y()))
            elif event.type() == QtCore.QEvent.Enter:
                print('ENTER')
            elif event.type() == QtCore.QEvent.Leave:
                print('LEAVE')
        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 300, 100)
    window.show()
    sys.exit(app.exec_())

rawDescription: QLineEdit hover-over Signal - when mouse is over the QlineEdit


code:
class CommentSerializer(serializers.ModelSerializer):

    title = serializers.CharField(source="title.title", read_only=True)

    class Meta:
        model = Comment
        fields = ('title','comments')

rawDescription: Django api returning model ID instead of model's title


rawDescription: Python: converting single digit decimal to hex


code: data = ast.literal_eval(open('data.txt').read()) # create file, read contents, evaluate

rawDescription: Python: Read file with list as list

description: Python: Read file with list as list


code: array = [not elem for elem in array]

rawDescription: How to change all True values in list on False and vice versa

description: Change all True values in list on False and vice versa


code:
# For each tuple inside daily_sales
for sale in daily_sales:
  # Use the first element of that tuple as a key and check if it's inside the dictionary budgeted_sales
  if sale[0] in budgeted_sales:
    # Compare the value stored for that key with the second element of the tuple (which contains the other price) and print stuff
    if budgeted_sales[sale[0]] > sale[1]: print('Over')
    else: print('Under')

rawDescription: Iterate over tuple list and dictionary to make calc


code:
def process_line(line, first_value, outf):
    parts = line.strip().split(' ')
    parts[0] = '%.3f' % (float(parts[0]) - first_value)
    print >>outf, ' '.join(parts)

with open('in.txt') as inf, open('out.txt', 'w') as outf:
    first_line = inf.readline().strip()
    first_value = float(first_line.split(' ', 1)[0])
    process_line(first_line, first_value, outf)
    for line in inf:
        process_line(line, first_value, outf)

rawDescription: subtracting every entry of a column with first value of the column

description: Subtracting every entry of a column with first value of the column


code:
import alphanum
unsorted = ['NASEC-100', 'NASEC-200', 'NASEC-99', 'NASEC-101']
sorted = unsorted[:]
sorted.sort(alphanum.alphanum)
sorted

rawDescription: How to use alphanum.py?

description: Use alphanum.py


code:
_expensive_to_compute = None
def get_expensive_to_compute():
    global _expensive_to_compute
    if _expensive_to_compute is None:
        _expensive_to_compute = do_computation()
    return _expensive_to_compute

rawDescription: Descriptors in global scope?

description: Descriptors in global scope


code:
print(re.findall("\"(release/.+?)\"", text))
['release/testing', 'release/xzczx', 'release/a.aa.a.2', 'release/1a1', 'release/aaaa', 'release/another_release', 'release/asdasdasd', 'release/my_branch', 'release/please_work', 'release/qqqqq', 'release/test_branch', 'release/zzzasdasda', 'release/zzzsersfawda']

rawDescription: Python re findall using regular expressions


code: system("mysql -uroot -p db_name > `tty`");

rawDescription: Python's os.execvp equivalent for PHP

description: Python's os.execvp equivalent for PHP


code:
#Untested Code
Project.objects.filter(action__person = person)

rawDescription: Django queryset filter for backwards related fields


code:
from sympy import *
a_0, a_1, a_2, x  = symbols('a_0, a_1, a_2, x')
p = Poly( a_0 + a_1*x + a_2 * x**2, x)
powers = Matrix([[x**k for k in range(p.degree()+1)]])
c = p.all_coeffs()
c.reverse()
coefficients = Matrix(c)
print(powers, coefficients, (powers*coefficients)[0,0])

rawDescription: Transforming a set of symbolic linear equations in to matrix form


code:
import csv

with open(A, 'rb') as file_a:
    selected = {tuple(row[:2]) for row in csv.reader(file_a)}

with open(B, 'rb') as file_b, open(C, 'wb') as file_c:
    reader = csv.reader(file_b)
    writer = csv.writer(file_c)
    writer.writerows(row for row in reader if tuple(row[:2]) in selected)

rawDescription: Python: Compare information in two text files and write matching info to new file


code:
from subprocess import check_output

c = check_output("identify -verbose img.jpg".split())
d = {}
print(c)
for line in c.splitlines()[:-1]:
    spl = line.split(":",1)
    k, v = spl
    d[k.lstrip()] = v.strip()
print(d)

{'Blue': '', 'Border color': 'srgb(223,223,223)', 'Compression': 'JPEG', 'Elapsed time': '0:01.000', 'Artifacts': '', 'Overall': '', 'blue primary': '(0.15,0.06)', 'Dispose': 'Undefined', 'jpeg': 'sampling-factor: 2x2,1x1,1x1', 'red primary': '(0.64,0.33)', 'Interlace': 'JPEG', 'Compose': 'Over', 'Tainted': 'False', 'Filesize': '3.9KB', 'Pixels per second': '0B', 'Units': 'Undefined', 'Chromaticity': '', 'Number pixels': '7.5K', 'Type': 'TrueColor', 'Red': '', 'Channel depth': '', 'blue': '8-bit', 'Background color': 'white', 'Transparent color': 'black', 'verbose': 'true', 'min': '0 (0)', 'Resolution': '72x72', 'Image statistics': '', 'filename': 'img.jpg', 'green primary': '(0.3,0.6)', 'Print size': '1.38889x1.04167', 'Channel statistics': '', 'Class': 'DirectClass', 'red': '8-bit', 'Matte color': 'grey74', 'Page geometry': '100x75+0+0', 'skewness': '-0.284137', 'Geometry': '100x75+0+0', 'max': '255 (1)', 'Colorspace': 'sRGB', 'Depth': '8-bit', 'Green': '', 'date': 'modify: 2015-01-13T19:18:06+00:00', 'User time': '0.000u', 'Rendering intent': 'Perceptual', 'kurtosis': '0.369947', 'Gamma': '0.454545', 'Orientation': 'Undefined', 'Endianess': 'Undefined', 'Image': 'img.jpg', 'Format': 'JPEG (Joint Photographic Experts Group JFIF format)', 'white point': '(0.3127,0.329)', 'Properties': '', 'green': '8-bit', 'Iterations': '0', 'signature': '620e0541b826edb6dc5a2420beaaf697fdf6682ba50f915b8ab767fafbb3b7d2', 'standard deviation': '46.9874 (0.184264)', 'Quality': '85', 'mean': '133.602 (0.52393)'}

rawDescription: EXIF python PIL return emtpy dictionary

description: EXIF python PIL return emtpy dictionary


code:
values = np.array([2,5,3,6,4,7,1])
idx = np.array(list('abcdefg'))
clrs = ['grey' if (x < max(values)) else 'red' for x in values ]
sb.barplot(x=idx, y=values, color=clrs)

rawDescription: How to set a different color to the largest bar in a seaborn barplot?

description: Set a different color to the largest bar in a seaborn barplot


code:
try:
    result = g.pop('age')
except KeyError:
    result = default_answer()

rawDescription: dict.pop or dict.get and evaluation

description: Dict.pop or dict.get and evaluation


code: return redirect('home')

rawDescription: reverse function does not change the url to request a different view, django

description: Reverse function does not change the url to request a different view, django


code:
class MyForm(forms.Form):
    email = forms.EmailField(required=False)
    cell = forms.CharField(required=False, max_length=20)

    def clean(self):
        cleaned_data = super(MyForm, self).clean()
        if cleaned_data.get('email') and cleaned_data.get('cell'):
            raise forms.ValidationError("Please select either E-mail address or cell number, but not both")
        return cleaned_data

rawDescription: Post to Python view after Javascript validation in Django


code:
import json
jsondata = r'''{"quotes":["I could calculate your chance of survival, but you won't like it.","I'd give you advice, but you wouldn't listen. No one ever does.","I ache, therefore I am.","I've seen it. It's rubbish. (About a Magrathean sunset that Arthur finds magnificent)","Not that anyone cares what I say, but the Restaurant is on the other end of the universe.","I think you ought to know I'm feeling very depressed.","My capacity for happiness,\" he added, \"you could fit into a matchbox without taking out the matches first.","Arthur: \"Marvin, any ideas?\" Marvin: \"I have a million ideas. They all point to certain death.\"","\"What's up?\" [asked Ford.] \"I don't know,\" said Marvin, \"I've never been there.\"","Marvin: \"I am at a rough estimate thirty billion times more intelligent than you. Let me give you an example. Think of a number, any number.\" Zem: \"Er, five.\" Marvin: \"Wrong. You see?\"","Zaphod: \"Can it Trillian, I'm trying to die with dignity. Marvin: \"I'm just trying to die.\""]}'''
from pprint import pprint
pprint(data)
import random
print(random.choice(data['quotes']))
print(random.choice(data['quotes']))

rawDescription: Formatting almost a json-file

description: Formatting almost a json-file


rawDescription: python: changing the value of a specific column in 2-d list

description: Python: changing the value of a specific column in 2-d list


code:
import os
from PyQt4 import QtCore

def myWalk(root_path):
    dir_info = QtCore.QDir(root_path)
    dirs = dir_info.entryList(filters=(QtCore.QDir.Dirs | QtCore.QDir.NoDotAndDotDot))
    files = dir_info.entryList(filters=(QtCore.QDir.Files | QtCore.QDir.NoDotAndDotDot))
    for i in dirs:
        myWalk(os.path.join(root_path, i))

rawDescription: How can I get around window's max path length limit when using os.walk?

description: Get around window's max path length limit when using os.walk


code:
# The function handler called is called whenever
# value in spinbox2 is changed and parameter to
# handler is the new value of spinbox2
def handler(value):
    spinbox1.setMaximum(value)

rawDescription: PyQt QSpinBox update range depending on the value of other spinbox


code:
data2 = jsonpickle.decode(whatever)
data2["Metadata"]["dateAndTime"] = "Whatever"
data2 = jsonpickle.encode(data2)

rawDescription: How to access decoded JSON values in .txt file

description: Access decoded JSON values in .txt file


code:
self.db.aggregate(
    # Lets find our records
    {"$match":{"Time":{"$gte":100,"$lte":1000}}},

    # Now lets group on the name counting how many grouped documents we have
    {"$group":{"_id":"$name", "sum":{"$sum":1}}}
)

rawDescription: Migrating to MongoDB: how to query GROUP BY + WHERE


code:
class MyHash(object):
     def __init__(self, v):
         self._v = v

     def __hash__(self):
         return hash(self._v) * -1

     def __eq__(self, other):
         return self._v == other._v

rawDescription: Alter the hash function of a dictionary

description: Alter the hash function of a dictionary


code:
s = input()
lstr = list(s)

current = ''
nb_current = 0
fullstr = ''

for c in lstr:
    if nb_current ==0: #only for the first character of the list
        current = c
        nb_current = 1
    elif c==current:
        nb_current += 1
    else:
        fullstr += str(nb_current)
        fullstr += current
        current = c
        nb_current = 1

if nb_current>0:
    fullstr += str(nb_current)
    fullstr += current

print(fullstr)

rawDescription: Trying to sort letters characters in a specific way but can't quite get it right


code:
def inv(perm):
    inverse = [0] * len(perm)
    for i, p in enumerate(perm):
        inverse[p] = i
    return inverse

perm = [3, 0, 2, 1]
print(inv(perm))
for i in perm:
    print(inv(perm)[i])

[1, 3, 2, 0]
0
1
2
3

rawDescription: Inverting permutations in Python

description: Inverting permutations in Python


code:
def test_parse_har(self):
    with patch.object(rules, 'add_dns_analysis', return_value=None) as \
       dns_mock:
        result = rules.parse_har(self.data,[self.rule],RulesTest.url)
        self.assertEqual(result[RULES.TOTAL_REQUESTS], 484)
        self.assertEqual(result[RULES.HTML_SIZE], 241592)
        self.assertEqual(result[RULES.JS_SIZE], 1006469)
        dns_mock.assert_called_once_with('test result', 'test url')

rawDescription: Python how to assert that a method has been called


code:
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np

x_data = np.random.randn(100)
y_data = -x_data + np.random.randn(100)*0.5

df = pd.DataFrame()
df['vcnt'] = x_data
df['ecnt'] = y_data

left = 0.1
bottom = 0.1
top = 0.8
right = 0.8
main_ax = plt.axes([left,bottom,right-left,top-bottom])
# create axes to the top and right of the main axes and hide them
top_ax = plt.axes([left,top,right - left,1-top])
plt.axis('off')
right_ax = plt.axes([right,bottom,1-right,top-bottom])
plt.axis('off')
main_ax.plot(df['vcnt'],  df['ecnt'], 'ko', alpha=0.5)
# Save the default tick positions, so we can reset them..

tcksx = main_ax.get_xticks()
tcksy = main_ax.get_yticks()

right_ax.boxplot(df['ecnt'], positions=[0], notch=True, widths=1.)
top_ax.boxplot(df['vcnt'], positions=[0], vert=False, notch=True, widths=1.)

main_ax.set_yticks(tcksy) # pos = tcksy
main_ax.set_xticks(tcksx) # pos = tcksx
main_ax.set_yticklabels([int(j) for j in tcksy])
main_ax.set_xticklabels([int(j) for j in tcksx])
main_ax.set_ylim([min(tcksy-1),max(tcksy)])
main_ax.set_xlim([min(tcksx-1),max(tcksx)])

# set the limits to the box axes
top_ax.set_xlim(main_ax.get_xlim())
top_ax.set_ylim(-1,1)
right_ax.set_ylim(main_ax.get_ylim())
right_ax.set_xlim(-1,1)

plt.show()

rawDescription: Add either a density or box plot to the margins of a plot in Matplotlib


code:
searchdict = self.get_recent_searches(10)
searches = searchdict['searches']

dic['recent'] = searches[:5]

rawDescription: Python: How to get first 5 or last 5 from list of 10?


code:
r = requests.head('http://www.example.com')
r.request.method
r = requests.get('http://www.example.com')
r.request.method

rawDescription: How do I get HTTP VERB from Python Requests 'Response' objects?

description: Get HTTP VERB from Python Requests 'Response' objects


code:
lsts = [[0,1,2,3,4,5], [6,7,8,9,10,11], [12,56,86,9], [55,53,12]]
sets = map(set, lsts)

def find(iterables, element):
    return [i for i, iterable in enumerate(iterables) if element in iterable]

rawDescription: Find a number in list of lists

description: Find a number in list of lists


code:
if value in my_array[:, col_num]:
    do_whatever

rawDescription: What is the most efficient way to check if a value exists in a NumPy array?


rawDescription: Can Python directory names be keywords? E.g. 'import'?


code: l1 = [ child.attrib['action'] for child in root ]

rawDescription: Parse xml attributes into strings

description: Parse xml attributes into strings


rawDescription: Scikit hmm score returned negative value


code:
import math,cairo

width, height = 768,768
surface = cairo.PDFSurface ("circle.pdf", width, height)
ctx = cairo.Context (surface)
ctx.set_source_rgb(1,1,1)
ctx.rectangle(0,0,width,height)
ctx.fill()
ctx.set_source_rgb(1,0,0)
ctx.move_to(width/2,height/2)
ctx.arc(width/2,height/2,512*0.25,0,math.pi*2)
ctx.fill()
ctx.show_page()

rawDescription: Draw simple shapes and save to file (pdf)


code: new_dict = {k: len(v) for k,v in dict.items()}

rawDescription: Count number of values in dictionary for each key


code:
from pylab import *
import scipy.signal as signal

# create an array of 1024 points sampled at 40MHz
# [each sample is 25ns apart]
Fs = 40e6
nyq = Fs / 2
T  = 1/Fs
t  = np.arange(0,(1024*T),T)

# create an ip signal sampled at Fs, using two frequencies
F_low  = 25e3 #  25kHz
F_high = 1e6  #  1MHz
ip_1 = np.sin(2*np.pi*F_low*t) + np.sin(2*np.pi*F_high*t)
ip_2 = np.sin(2*np.pi*F_low*t) * np.sin(2*np.pi*F_high*t)

Fc = 0.9e6
Length = 101

# create a low pass digital filter
a = signal.firwin(Length, cutoff = F_high / nyq, window="hann")

# create a high pass filter via signal inversion
a = -a
a[Length/2] = a[Length/2] + 1

figure()
plot(a, 'ro')

# apply the high pass filter to the two input signals
op_1 = signal.lfilter(a, 1, ip_1)
op_2 = signal.lfilter(a, 1, ip_2)

figure()
plot(ip_1)
figure()
plot(op_1)
figure()
plot(ip_2)
figure()
plot(op_2)

rawDescription: Python: High Pass FIR Filter by Windowing


code:
class Food(object):
    def kimchi(self):
        return 'mmm'

class country(object):
    def __init__(self):
        self.food = Food()

rawDescription: Sub-dots in python classes

description: Sub-dots in python classes


code:
import multiprocessing
...
def wrapper(currentfile):
    #create your commandline -- for the sake of simplicity, I assume that
    #the only thing that changes is the filename you are passing to
    #HandBrakeCLI (and that the filename is the last argument to pass)
    cmd='HandBrakeCLI -i ... -o ... '+currentfile
    proc = subprocess.Popen(cmd)
    proc.wait()
    return 'foo'

files=os.listdir(path)  #Any way that you build up your list of files is fine
output = multiprocessing.Pool(4).map(wrapper,files) #output is ['foo', 'foo', ..., 'foo']

rawDescription: python - using multiple processes / parallel processing

description: Python - using multiple processes / parallel processing


code:
import matplotlib.pyplot as PLT
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
from matplotlib._png import read_png

fig = PLT.gcf()
fig.clf()
ax = PLT.subplot(111)

# add a first image
arr_hand = read_png('/path/to/this/image.png')
imagebox = OffsetImage(arr_hand, zoom=.1)
xy = [0.25, 0.45]               # coordinates to position this image

ab = AnnotationBbox(imagebox, xy,
    xybox=(30., -30.),
    xycoords='data',
    boxcoords="offset points")
ax.add_artist(ab)

# add second image
arr_vic = read_png('/path/to/this/image2.png')
imagebox = OffsetImage(arr_vic, zoom=.1)
xy = [.6, .3]                  # coordinates to position 2nd image

ab = AnnotationBbox(imagebox, xy,
    xybox=(30, -30),
    xycoords='data',
    boxcoords="offset points")
ax.add_artist(ab)

# rest is just standard matplotlib boilerplate
ax.grid(True)
PLT.draw()
PLT.show()

rawDescription: Placing Custom Images in a Plot Window--as custom data markers or to annotate  those markers


code:
from Tkinter import *

root = Tk()

f = Frame(root, bg = "orange", width = 500, height = 500)
f.pack(side=LEFT, expand = 1)

f3 = Frame(f, bg = "red", width = 500)
f3.pack(side=LEFT, expand = 1, pady = 50, padx = 50)

f2 = Frame(root, bg = "black", height=100, width = 100)
f2.pack(side=LEFT, fill = Y)

b = Button(f2, text = "test")
b.pack()

b = Button(f3, text = "1", bg = "red")
b.grid(row=1, column=3)
b2 = Button(f3, text = "2")
b2.grid(row=1, column=4)
b3 = Button(f3, text = "2")
b3.grid(row=2, column=0)

root.mainloop()

rawDescription: Grid within a frame?

description: Grid within a frame


rawDescription: Dividing complex rows of dataframe to simple rows in Pyspark


code:
from unittest.mock import MagicMock

def foo(x):
    a = x.value

m = MagicMock()
p = PropertyMock()
type(m).value = p
foo(m)
p.assert_called_once_with()

rawDescription: Assert attribute on mock instance was accessed


code:
ax.grid(False)
for a in (ax.w_xaxis, ax.w_yaxis, ax.w_zaxis):
    for t in a.get_ticklines()+a.get_ticklabels():
        t.set_visible(False)
    a.line.set_visible(False)
    a.pane.set_visible(False)

rawDescription: Plotting surface without axes

description: Plotting surface without axes


code:
import numpy as np
a = np.random.random(5)
a
a.argsort().argsort()

rawDescription: Return order of numpy array

description: Return order of numpy array


code:
def resize(file_path):
    file, ext = os.path.splitext(file_path)
    im = Image.open(file_path)
    size = (100, 'auto')
    new_path = file + "_.jpg"
    im.thumbnail(size, Image.ANTIALIAS)
    if im.size[1] > 100:
        im = im.crop((0, 0, 100, 100))
    im.save(new_path, "JPEG")

rawDescription: Python PIL: image crop with black area if not enough photo region


code:
for i in database:
    if "number" in i:
        x.append(i["number"])

rawDescription: $exists in python

description: $exists in python


code:
@event.listens_for(Table, "column_reflect")
def reflect_col(inspector, table, column_info):
   column_info['key'] = column_info['name'].replace(' ', '_').replace('1st_time', 'secondcheck')

rawDescription: How do I alter two different column headers of a pre-existing database table in sqlalchemy?

description: Alter two different column headers of a pre-existing database table in sqlalchemy


code:
with open('file1.csv', 'rb') as file_a, open('file2.csv', 'rb') as file_b:
    data_a = csv.reader(file_a)
    data_b = dict(csv.reader(file_b))  # <-- dict
    with open('out.csv', 'wb') as file_out:
        csv_out = csv.writer(file_out)
        for word, num_a in data_a:
            csv_out.writerow([word, num_a, data_b.get(word, '')])  # <-- edit

rawDescription: Merge two tables (CSV) if (table1 column A == table2 column A)


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

# Some sample data
x_side = np.arange(-5, 5, 0.04)
y_side = np.arange(-5, 5, 0.04)
X, Y = np.meshgrid(x_side,y_side)

# Fake mountains
Z = np.exp(-(X**2+Y**2)) + 2*np.exp(-((X-2)**2+Y**2))

# Assign colors based off some user-defined condition
COLORS = np.empty(X.shape, dtype=str)
COLORS[:,:] = 'b'
COLORS[(Z>.1) * (Z<.3)] = 'r'
COLORS[Z>.3] = 'g'
COLORS[X+Y < -1] = 'k'

# 3D surface plot
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, facecolors=COLORS, rstride=1, cstride=1,
        linewidth=0)
plt.show()

rawDescription: Python matplotlib/pylab - a 3D carpet plot


code:
import threading
import socketserver
import ssl
import random

class ThreadedTCPAdminRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):

        ts = self.request # replaced the ssl connection for simpler code
        msg = ts.recv(80).decode()
        # Here should be some kind of loop to be able to handle multiple request of the same admin client
        # like 'Hello' followed by 'Who'
        if msg == 'Hello':
            ts.send('Admin-Greetings\r\n'.encode())
        elif msg == 'Who':
            with self.server.addressesLock:
                # get a local copy of the dict and quickly release the lock
                socket_addresses = self.server.addresses.copy()
            client_string=''
            # print the list of threads with their address:port
            for threadName, socket_addresse in socket_addresses.items():
                client_string += threadName + ' ' + socket_addresse + '\r\n'
                # the admin handler doesn't anything if the following line is commented
                # ts.send(client_string.encode())

            #  for simpler test, that way you can see the connexion listing is working
            # even if there are conection problems
            print(client_string)
            ts.send('plop'.encode())

class ThreadedTCPClientRequestHandler(socketserver.BaseRequestHandler):
    def handle(self):
        cur_thread = threading.current_thread().name
        with self.server.addressesLock:  # use a lock to protect the access to the shared dict
            # add name of the thread ad key and the address:port as value in the global dict
            self.server.addresses[cur_thread] = self.client_address[0] + ':' + str(self.client_address[1])

        score_count = 0
        guess = 0
        if (self.request.recv(80).decode()) == 'Hello':
            self.request.send('Greetings\r\n'.encode())

            goal = random.randrange(1, 21)

            while guess != goal:
                guess = self.request.recv(80).decode()
                guess = int(guess[7:len(guess) - 2])

                if guess == goal:
                    self.request.send('Correct\r\n'.encode())
                elif guess in range(goal-2,goal +2):
                    self.request.send('Close\r\n'.encode())
                else:
                    self.request.send('Far\r\n'.encode())

        with self.server.addressesLock:  # use a lock to protect the access to the shared dict
            del self.server.addresses[cur_thread]  # delete the thread entry in the dict

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

if __name__ == "__main__":
    C_HOST, C_PORT = 'localhost', 4000
    A_HOST, A_PORT = 'localhost', 4001

    clientServer = ThreadedTCPServer((C_HOST, C_PORT), ThreadedTCPClientRequestHandler)
    adminServer = ThreadedTCPServer((C_HOST, A_PORT), ThreadedTCPAdminRequestHandler)

    # Start a thread for each the server (client and admin) -- those threads will then start one
    # more thread for each request
    clientServer_thread = threading.Thread(target=clientServer.serve_forever)
    adminServer_thread = threading.Thread(target=adminServer.serve_forever)

    addresses = {}  # create a dict to store the addresses of connected clients
    addressesLock0 = threading.Lock()  # create a lock to protect access to the dict

    clientServer_thread.daemon = True  # client will terminate when main terminate
    clientServer.addresses = addresses  # share the addreses dict
    clientServer.addressesLock = addressesLock0  # share the lock
    adminServer_thread.daemon = True
    adminServer.addresses = addresses
    adminServer.addressesLock = addressesLock0

    try:
        # strart servers
        clientServer_thread.start()
        print("clientServer loop running in thread:", clientServer_thread.name)
        adminServer_thread.start()
        print("adminServer loop running in thread:", adminServer_thread.name)

        input('Press Enter to exit...\r\n')  # wait input to end the program

    finally:
        # stop servers
        clientServer.shutdown()
        clientServer.server_close()
        adminServer.shutdown()
        adminServer.server_close()
    exit(0)

rawDescription: python threading Guessing game

description: Python threading Guessing game


code:
seen   = set(initial_items)
active = set(initial_items)

while active:
    next_active = set()
    for item in active:
        for result in evil_func(item):
            if result not in seen:
                seen.add(result)
                next_active.add(result)
    active = next_active

rawDescription: iterating over a growing set in python

description: Iterating over a growing set in python


code:
im = PIL.Image.open(fname)
try:
    im.tag[37724]
    layers = True
except:
    layers = False

rawDescription: How to detect if an tif image has layers with python preferably with pil

description: Detect if an tif image has layers with python preferably with pil


rawDescription: Find nth smallest element in numpy array


code:
my_list = [[1,2], [3,7], [6,9], [4,3]]
new_list = [[v*2 if i==0 else v for i,v in enumerate(sublist)] for sublist in my_list]
new_list

rawDescription: Nested Lists and List Comprehensions

description: Nested Lists and List Comprehensions


rawDescription: Django Span Filter in View

description: Django Span Filter in View


code:
def generateFromFile ( fileName ):
    for line in open( fileName ):
        for segment in line.split( ',' ):
            yield segment

for ln in generateFromFile( "input.txt" ):
    ch.Add( ln.strip() )

rawDescription: Reformating an external file and then saving it, from inside a python code


code: s = s.rstrip()

rawDescription: How can you remove the new line characters in python?

description: Remove the new line characters in python


code:
import pygame, sys
x=False
oldLocation=(100, 100)
newLocation=(200, 200)
window=pygame.display.set_mode((500, 500))
while True:
    for event in pygame.event.get():
        if event.type==pygame.KEYDOWN and event.key==pygame.K_SPACE:
            x=True
        if event.type==pygame.QUIT:
            pygame.quit()
            sys.exit()
    window.fill((255, 255, 255))
    if x:
        pygame.draw.circle(window, (0, 0, 0), newLocation, 50)
    else:
        pygame.draw.circle(window, (0, 0, 0), oldLocation, 50)
    pygame.display.update()

rawDescription: pygame - How to make a circle move based on an event?

description: Pygame - How to make a circle move based on an event


code: reduce(lambda x,y: x * factorial(y), lst, 1)

rawDescription: Using math.factorial in a lambda function with reduce()


code:
arr = np.ndarray(shape=(3, 4), dtype=bool)
arr
np.sum(arr, axis=0)
np.sum(arr, axis=1)

rawDescription: Count Booleans by Column in Array of Arrays


code:
class PostAdmin(admin.ModelAdmin):
    def get_list_display(request):
        if request.user.is_superuser:
            return ['post_title', 'body', 'rating']
        else:
            return ['post_title', 'category']

admin.site.register(Post, PostAdmin)

rawDescription: Access request object in admin.py outside the class


code:
for currency in currencies:
    models.IntegerField().contribute_to_class(Car, 'price_%s' % currency.lower())

rawDescription: Programmatically specifying Django model attributes


code:
#!/usr/bin/python
import sys
import usb.core
# find USB devices
dev = usb.core.find(find_all=True)
# loop through devices, printing vendor and product ids in decimal and hex
for cfg in dev:
  sys.stdout.write('Decimal VendorID=' + str(cfg.idVendor) + ' & ProductID=' + str(cfg.idProduct) + '\n')
  sys.stdout.write('Hexadecimal VendorID=' + hex(cfg.idVendor) + ' & ProductID=' + hex(cfg.idProduct) + '\n\n')

rawDescription: Detect external hard drive after letter changed in Python


code:
created_on = models.DateTimeField('Created On', auto_now_add=True)
last_modified = models.DateTimeField('Last Modified', auto_now=True)

rawDescription: Sync Data between SAP and DataModels in Django


code:
import re
pat = re.compile(r'^pattern{n, m}$')
total_count = db.collection.count({'field': {'$regex': pat}})

rawDescription: How to implement regex expression that includes {m,n} in a mongodb query using pymongo?

description: Implement regex expression that includes {m,n} in a mongodb query using pymongo


code:
sentence = ['this ','is ','are ','a ','sentence']
string = ''.join([i for i in sentence if i != 'are '])

rawDescription: Conditionally concatenating a list of strings with a condition


code: print(' < '.join(str(n) for n in (1,2,3)))

rawDescription: Python: how to print non string array?

description: Python: how to print non string array


code:
score=0
def Geography(score):
    #Question 1
    qa1= input("What is the capital of England? ")
    if qa1.lower() == ("london"):
        print ("Correct you gain 1 point")
        score=score+1
    else:
        print ("Incorrect")
    return score

score = Geography(score)
print ("This quiz has ended. Your score is " , score, ".")

rawDescription: How do I use a variable so that it is inside and outside of a function

description: Use a variable so that it is inside and outside of a function


rawDescription: How to click on a parent element

description: Click on a parent element


code:
#!/usr/bin/python
from bs4 import BeautifulSoup
import requests

def download_file(url):
    local_filename = url.split('/')[-1]
    # NOTE the stream=True parameter
    r = requests.get(url, stream=True)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
                f.flush()
    return local_filename

s = requests.Session()

soup = BeautifulSoup(s.get("https://minecraft.net/login").content)

authToken = soup.find('form', attrs={'id': 'loginForm'}).findNext('input')['value']

data = {
    "username": "USERNAME",
    "password": "PASSWORD",
    "remember": "true",
    "authenticityToken": authToken
}

s.post("https://minecraft.net/login", data=data)
soup = BeautifulSoup(s.get("https://minecraft.net//download").content)
download_file(soup.find("div", attrs={'id': 'platform-osx'}).findNext('p').findNext('')['href'])

rawDescription: Extract cookies from open Safari session in Python


code:
last_line = None

with open("somefile.txt") as f:
    for line in f:
        if not last_line == None:
            do_stuff(last_line, extract_needed_part(line))
        last_line = line
do_stuff(last_line) #The final line without anything following it.

rawDescription: File iteration, checking line existence

description: File iteration, checking line existence


code: reload(f)

rawDescription: Reload f imported with 'import foo as f'?


code:
from sorl.thumbnail import get_thumbnail

im = get_thumbnail(my_file, '100x100', crop='center', quality=99)

rawDescription: timthumb for python?

description: Timthumb for python


code:
def waitFor(waitTime): # waitTime in milliseconds
    screenCopy = screen.copy()
    waitCount = 0
    while waitCount < waitTime:
        dt = clock.tick(60) # 60 is your FPS here
        waitCount += dt
        pygame.event.pump() # Tells pygame to handle it's event, instead of pygame.event.get()
        screen.blit(screenCopy, (0,0))
        pygame.display.flip()

rawDescription: Pygame, Draw the same frame for a set amount of time


code:
directory = '/path/to/dir'
base = 'mystring'

for i, f in enumerate(os.listdir(directory), 1):
    ext = f.rsplit('.', 1)[-1]
    absolutify = lambda s: os.path.join(directory, s)
    os.rename(absolutify(f), absolutify('%s_%d.%s' % (base, i, ext)))

rawDescription: Mass renaming using Python

description: Mass renaming using Python


code:
self.filename = StringVar()
self.filename_entry = ttk.Entry(mainFrame, width=30, textvariable=self.filename)
self.filename_entry.grid(row=1, column=1)

rawDescription: How do I grab input with Tkinter from an entry field?

description: Grab input with Tkinter from an entry field


code:
for kk in xrange(0,1000):
    list500steps = []
    for jj in range(0,500):
         list500steps.append(...)
    list1000walks.append(list500steps)

rawDescription: How to make a list of lists in python

description: Make a list of lists in python


code:
relevant_categories = DownloadableResourceCategory.objects.filter(
                           downloadableresource__in=items).distinct()

rawDescription: Determining "reachable" objects linked via many-to-many relations


code:
import Tkinter as tk
import tkFont

BG = "white"
HEIGHT = 75
def main():
    global the_font, root

    root = tk.Tk()
    the_font = tkFont.Font(family="helvetica", size=18)

    toolbar = make_toolbar(root)
    subframe = make_subframe(root)

    toolbar.pack(side="top", fill="x")
    subframe.pack(side="top", fill="x")

    root.geometry("400x400")
    root.mainloop()

def make_subframe(parent):
    frame = tk.Frame(parent, height=HEIGHT, borderwidth=1, relief="sunken", background=BG)
    frame.pack_propagate(False)

    label = tk.Label(frame, font=the_font, text="0123455.67890", background=BG)
    label.pack(side="top", fill="both", expand=True)
    return frame

def font_plus():
    size = the_font.cget("size")
    size += 2
    the_font.configure(size=size)

def font_minus():
    size = the_font.cget("size")
    size -= 2
    the_font.configure(size=size)

def make_toolbar(parent):
    toolbar = tk.Frame(root)
    grow = tk.Button(toolbar, text="Bigger", command=font_plus)
    shrink = tk.Button(toolbar, text="Smaller", command=font_minus)
    grow.pack(side="left")
    shrink.pack(side="left")

    return toolbar

main()

rawDescription: Tkinter Label: Retain Height when I change font to smaller size


rawDescription: How to save the changes I made on an Excel sheet?

description: Save the changes I made on an Excel sheet


code:
from string import find

import numpy as np

a = np.char.array(['cmd.py', 'matrix.txt', 'print.txt', 'test.txt', 'testpickle.test', 'Thumbs.db', 'tmp.py', 'tmp.txt', 'tmp2.py'])
find(a, '.py')
#array([ 3, -1, -1, -1, -1, -1,  3, -1,  4])

np.char.array(a.split('.'))[:,0]
#chararray(['cmd', 'matrix', 'print', 'test', 'testpickle', 'Thumbs', 'tmp', 'tmp', 'tmp2'], dtype='|S10')

rawDescription: Vectorized string processing in a NumPy array


code:
from Tkinter import *

master = Tk()
C = Canvas(master, width=200, height=100)
C.pack()

def Open():
    top = Toplevel()
    # Add a label to the TopLevel, just like you would the root window
    lbl = Label(top, text="Hello World")
    lbl.pack()

b = Button(master, text="Open New Window", command=Open)
b.pack()

mainloop()

rawDescription: Edit contents of new Toplevel window

description: Edit contents of new Toplevel window


rawDescription: Performance implications of unpacking dictionaries in Python


code:
import admin_notifications
from models import Contacts
def notification():
    count = Contacts.objects.filter(status=Contacts.STATUS_NEW).count()
    if count:
        return 'You have {} new contacts message'.format(count)
    else:
        return ''

admin_notifications.register(notification)

rawDescription: How to view recently client created records in django admin?

description: View recently client created records in django admin


code:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_json('{"genre":{"0":"Drama","1":"Comedy","2":"Action","3":"Thriller"},"count":{"0":1603,"1":1200,"2":503,"3":492}}')

df.plot(x='genre', y='count', kind='bar', legend=False)

plt.show()

rawDescription: how to generate histogram in pandas with x-axis labels from column?

description: Generate histogram in pandas with x-axis labels from column


code:
try:
    import io
except ImportError:
    # classic version with our own file-like emulation
    class Serial(PosixSerial, FileLike):
        pass
else:
    # io library present
    class Serial(PosixSerial, io.RawIOBase):
        pass

rawDescription: How does pySerial implement the "with" statement without __enter__ and __exit__?


rawDescription: Selecting data on median value

description: Selecting data on median value


code:
activity = driver.current_activity
assertEquals('.ApiDemos', activity)

rawDescription: Check which app is currently open on device


rawDescription: Disproportionate image subplots in matplotlib


code: ''.join(i.text for i in soup.select('p > span'))

rawDescription: extracting data between span tags with BeautifulSoup Python

description: Extracting data between span tags with BeautifulSoup Python


code:
class Enemy():
    def __init__(self, char, xMoveAmnt, startY=0, startX=0, delay=0):
         ...
         self.delay = delay

    def moveChar(self):
        if self.delay > 0:
             self.delay -= 1
             return
        self.x += self.xMoveAmnt
        if self.x + self.rect.right >= 800:
            self.x=self.startX
            self.y=random.randint(0,300)

enemyList = []
for i in range (0, 3):
    xMoveAmnt=20
    enemyList.append(Enemy(("orc.png"), xMoveAmnt, random.randint(0, 500), 0, random.randint(0,100)))

rawDescription: PYGAME initialize multiple objects at different times.


code:
with open("inputfile") as f:
    contents1, sentinel, contents2 = f.read().partition("Sentinel text\n")
with open("outputfile1", "w") as f:
    f.write(contents1)
with open("outputfile2", "w") as f:
    f.write(contents2)

rawDescription: How do I split one file into two files using Python?

description: Split one file into two files using Python