code:
def create_test_case(testcase_name, scenario_data):
    class ScenarioTestCase(BaseTestCase):
        @classmethod
        def setUpClass(cls):
            cls.fillClassVariables(scenario_data)
    return_class = ScenarioTestCase
    return_class.__name__ = testcase_name #for separating the results
    return return_class

def load_tests(loader, tests, pattern):
    list_scenario_names = [...]
    list_scenario_data = [...]

    loader = unittest.TestLoader()
    tests = TestSuite()
    for scenario_name, scenario_data in zip(list_scenario_names, list_scenario_data):
        tests.addTests(loader.loadTestsFromTestCase(
            create_test_case(scenario_name, scenario_data)))
    return tests

rawDescription: How to parametrize setUpClass() in Python (2.7) unittests

description: Parametrize setUpClass() in Python (2.7) unittests


code:
import cv2
import numpy as np

original = cv2.imread("test.jpg", cv2.CV_LOAD_IMAGE_GRAYSCALE)
retval, image = cv2.threshold(original, 50, 255, cv2.cv.CV_THRESH_BINARY)

el = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
image = cv2.dilate(image, el, iterations=6)

cv2.imwrite("dilated.png", image)

contours, hierarchy = cv2.findContours(
    image,
    cv2.cv.CV_RETR_LIST,
    cv2.cv.CV_CHAIN_APPROX_SIMPLE
)

drawing = cv2.imread("test.jpg")

centers = []
radii = []
for contour in contours:
    area = cv2.contourArea(contour)

    # there is one contour that contains all others, filter it out
    if area > 500:
        continue

    br = cv2.boundingRect(contour)
    radii.append(br[2])

    m = cv2.moments(contour)
    center = (int(m['m10'] / m['m00']), int(m['m01'] / m['m00']))
    centers.append(center)

print("There are {} circles".format(len(centers)))

radius = int(np.average(radii)) + 5

for center in centers:
    cv2.circle(drawing, center, 3, (255, 0, 0), -1)
    cv2.circle(drawing, center, radius, (0, 255, 0), 1)

cv2.imwrite("drawing.png", drawing)

rawDescription: Filled circle detection using CV2 in Python?


code:
s = "Hello world !!"
":".join("{:02x}".format(ord(c)) for c in s)

rawDescription: Print a string as hex bytes?

description: Print a string as hex bytes


code:
class TestPY(Image):
    def __init__(self, **kwargs):
        super(TestPY, self).__init__(**kwargs)
        # self.x = x -- not necessary, x is a property and will be handled by super()
        with self.canvas.before:
            PushMatrix()
            self.rot = Rotate()
            self.rot.angle = 45
            self.rot.origin = self.center
            self.rot.axis = (0, 0, 1)
        with self.canvas.after:
            PopMatrix()

    def on_touch_down(self, touch):
        self.x += 10
        self.rot.origin = self.center  # center has changed; update here or bind instead
        self.rot.angle += 20

rawDescription: Behaviour of rotating image between kivy and python


code:
q = deque(maxlen=2)
q.extend([1, 2, 3])
q

rawDescription: Discarding FIFO queue, with max capacity, in Python?


code:
from string import letters, digits
strs = letters + digits
from itertools import product

pwd_checker('a')
pwd_checker('ab12')
pwd_checker('foo')
pwd_checker('Ab1c')
pwd_checker('aaaa')
pwd_checker('BaBa')

rawDescription: Python Brute forcing (Very basic)

description: Python Brute forcing (Very basic)


code: sample_size = numpy.random.binomial(len(population). p)

rawDescription: Fast, independent random draws / sample from a list in python - fixed probability, not total number


code:
l = "In the end Tom loves Julie. Fred and Tina are a lot better with dogs.I don't think Jack and Jenny belong together."
[[i for i in j.split() if i[0].isupper()][-2:] for j in l.split('.') if j]

rawDescription: Find names in list of strings and return pairs


code:
def recurse(max, _output=None):
    if _output is None:
        _output = []

    #do some work here, add to your list
    _output.append(max)

    if max <= 0: #Some condition where the recursion stops
        return _output
    else:        #recurse with new arguments so that we'll stop someday...
        return recurse(max-1, _output=_output)

rawDescription: Returning a list of values from a tree recursion


code:
from math import sqrt

x1 = float(raw_input('x1: '))
y1 = float(raw_input('y1: '))
x2 = float(raw_input('x2: '))
y2 = float(raw_input('y2: '))
x3 = float(raw_input('x3: '))
y3 = float(raw_input('y3: '))

side1 = sqrt((x1 - x2)**2 + (y1-y2)**2)
side2 = sqrt((x2 - x3)**2 + (y2-y3)**2)
side3 = sqrt((x3 - x1)**2 + (y3-y1)**2)

# Put the sides into a list; sort them.
tri= [side1, side2, side3]
tri.sort()

if tri[0] < tri[1]+tri[2]:
    if tri[0] == tri[2]:
        print('This triangle is equilateral')
    elif tri[1] == tri[2] or tri[1] == tri[0]:
        print('This triangle is isosceles')
    else:
        print('This triangle is scalene')
else:
    print('This is not a triangle!')

rawDescription: Given the coordinates of three points, how to determine if the triangle defined is equilateral, isosceles or scalene?


code:
import subprocess
stdoutdata = subprocess.getoutput("wc --lines /var/log/syslog")
print("stdoutdata: " + stdoutdata.split()[0])

rawDescription: Python3 subprocess output

description: Python3 subprocess output


code:
def iterate_over_all():
    for name in __all__:
        value = globals()[name]
        yield value # or do whatever with it

rawDescription: How to get a reference to the module something is implemented in from within that implementation?

description: Get a reference to the module something is implemented in from within that implementation


code:
def test_write_file(self):
    a = [1,2,3]
    write_file(a)
    with open('testfile') as f:
        assert f.read() == '123' # Replace this line with the method
                                 #   provided by your testing framework.

rawDescription: How to test Python function which writes to file

description: Test Python function which writes to file


code:
...

def setup(app):
    """Establish sphinx hooks"""
    app.connect('build-finished', my_extension)

def setup_module():
    pass

rawDescription: Disable nose running setup()

description: Disable nose running setup()


code:
a={}
for i in range(10):
    a[i]=np.random.rand(10)

rawDescription: Creating multiple numpy arrays

description: Creating multiple numpy arrays


code:
l1 = ['pickle_4500@dill.chile', 'pickle_4501@dill.chile', 'pickle_4502@dill.chile', 'pickle_4503@dill.chile', 'pickle_4504@dill.chile', 'pickle_4505@dill.chile']
l2 = ['pickle_4503@dill.chile', 'pickle_4505@dill.chile']
set(l1)-set(l2)
list(set(l1)-set(l2))
l1 = list(set(l1)-set(l2))
l1

rawDescription: List Subtraction in Python

description: List Subtraction in Python


code:
print("Kilograms   Pounds")

for i in range(1,199+1,2):
    kg = i * 202
    print('{:<3} {:>15.1f}'.format(i, kg))

rawDescription: Align numbers about python 3.3

description: Align numbers about python 3.3


code:
file = open("list_spectral_ron.txt", "r")

array_2d = []
for line in file:
  array_2d.append(line.strip().split(' '))

file.close()

rawDescription: Python - reading data from file

description: Python - reading data from file


code:
reader = csv.DictReader(ifile)
k = 0.5
for r in reader:
    ivd = {v: k for k, v in r.items()}
    print [r['']] + [ivd[i] for i in r.values()[1:] if float(i)>k]

rawDescription: csv file print columnwise raw values for values greater than 0.5

description: Csv file print columnwise raw values for values greater than 0.5


code:
import sys
print(sys.version)
input()

rawDescription: Tkinter Not Found

description: Tkinter Not Found


code:
d = {name: [v[0], {attr: s[placeholder] for attr, placeholder in v[1].items()}]
     for name, v in d.items()}

rawDescription: Replace dictionary values according to dictionary


code:
spline = RectBivariateSpline(y, x, Z, s=5E7)
Z2 = spline(y, x)

fig, ax = plt.subplots(1, 2, sharex=True, sharey=True,
                       subplot_kw={'projection':'3d'})

ax[0].plot_surface(X, Y, Z, rstride=1, cstride=1, alpha=0.3, cmap='Accent')
ax[1].plot_surface(X, Y, Z2, rstride=1, cstride=1, alpha=0.3, cmap='Accent')
ax[0].set_title('Original')
ax[1].set_title('Smoothed')

fig.tight_layout()
plt.show()

rawDescription: scipy interpolation is not smoothing my data

description: Scipy interpolation is not smoothing my data


code:
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

rawDescription: Python URLLib / URLLib2 POST

description: Python URLLib / URLLib2 POST


code:
for(root,dirs,files) in os.walk(path):
    for file in files:
        filesList.append(os.path.join(root, file))

rawDescription: Unable to use getsize method with os.walk() returned files


code:
from Tkinter import *
from random import *

root=Tk()
canvas=Canvas(root,width=400,height=300,bg='white')
def draw(event=None):
    canvas.delete(ALL)# clear canvas first
    canvas.create_oval(randint(0,399),randint(0,299),15,15,fill='red')
draw()
canvas.pack()

root.bind("<space>", draw)
root.mainloop()

rawDescription: How to bind spacebar key to a certain method in tkinter (python)

description: Bind spacebar key to a certain method in tkinter (python)


code:
unique = {}
for d in data:
    key = (d['A'],d['B'])
    if key in unique:
        if unique[key]['D'] < d['D']:
            unique[key] = d
    else:
        unique[key] = d

rawDescription: Removing duplicates from list, keeping newest


rawDescription: How do I url encode in Python?

description: Url encode in Python


code:
students=int(input('Please enter the number of students in the class: '))
class_average = 0
maximum_num = 0
minimum_num = 100
for number in range(students):

  first_grade=int(input("Enter student's first grade: "))
  second_grade=int(input("Enter student's second grade: "))
  third_grade=int(input("Enter student's third grade: "))

  StudentAverage=(first_grade + second_grade + third_grade)/3
  print("The student's average is", round(StudentAverage,2))

  class_average= class_average + StudentAverage
  print("The class average is", round(class_average/(number+1),2))

  if StudentAverage > maximum_num:
    maximum_num = StudentAverage

  if StudentAverage < minimum_num:
    minimum_num = StudentAverage
print("The minimum average is", round(minimum_num,2))
print("The maxiumum average is", round(maximum_num,2))

rawDescription: How to display max and min averages in a set of class averages

description: Display max and min averages in a set of class averages


code:
from collections import Counter

counts = Counter(row[4] for row in massive_nested_list)
counter100 = counter200 = 0
for id, count in counts.most_common():
    if count >= 200:
        counter200 += 1
    elif count >= 100:
        counter100 += 1
    else:
        break

rawDescription: Improve efficiency of python for loop counting items against IDs in nested list


code:
text = "sandwich"
inp = input("Enter word")

# a range from zero to the length of the shortest string
# (if one string is longer than the other, we want the length of the shortest
#  one so that it doesn't try to check characters that don't exist)
for i in range(min(len(text), len(inp))):
    # print if corresponding characters match
    if inp[i] == text[i]:
        print(text[i])

rawDescription: Why doesn't this String Handling work?

description: Why doesn't this String Handling work


code:
from reportlab.pdfbase import pdfdoc
pdfdoc.PDFCatalog.OpenAction = '<</S/JavaScript/JS(this.print\({bUI:true,bSilent:false,bShrinkToFit:true}\);)>>'

rawDescription: Using Reportlab Canvas- How to create an Option to print the pdf generated from the browser itself?


code:
import rumps

class AwesomeStatusBarApp(rumps.App):
    def __init__(self):
        super(AwesomeStatusBarApp, self).__init__("Awesome App")
        self.menu = ["Preferences", "Silly button", "Say hi"]

    @rumps.clicked("Preferences")
    def prefs(self, _):
        rumps.alert("jk! no preferences available!")

    @rumps.clicked("Silly button")
    def onoff(self, sender):
        sender.state = not sender.state

    @rumps.clicked("Say hi")
    def sayhi(self, _):
        rumps.notification("Awesome title", "amazing subtitle", "hi!!1")

if __name__ == "__main__":
    AwesomeStatusBarApp().run()

rawDescription: How to make an menu bar (system tray) app for OSX in Python?

description: Make an menu bar (system tray) app for OSX in Python


code: contadores = Profile.objects.filter(specialities__name__iexact = request.POST['buscar'])

rawDescription: Search M2M fields by names not by id in django


code:
import os

os.cmd ("mkdir ~/mnt/data_dir mount -t data:/dir/ /mnt/data_dir")

rawDescription: How to mount a network directory using python?

description: Mount a network directory using python


code:
import subprocess as sb
import threading

def timeout():
    print('timeout')
    exit(3)

sb.check_call("g++ main.cpp", shell=True)
t = threading.Timer(10, timeout)
proc = sb.Popen("./a.out", shell=True, stdin=sb.PIPE, stdout=sb.PIPE,
    stderr=sb.PIPE)
out, err = proc.communicate('hello\n')
t.cancel()
assert proc.returncode == 0
assert out == 'hello\n'
assert err == ''
sb.check_call("chocolate", shell=True)

rawDescription: How to write a python script that test my c++?

description: Write a python script that test my c++


code:
def merge(arr1,arr2):
    it1 = 0
    it2 = 0
    ret = []
    while it1 < len(arr1) or it2 < len(arr2):
        if it1 == len(arr1):
            ret.append(arr2[it2])
            it2+=1
        elif it2 == len(arr2):
            ret.append(arr1[it1])
            it1+=1
        else:
            if arr1[it1] > arr2[it2]:
                ret.append(arr2[it2])
                it2+=1
            else:
                ret.append(arr1[it1])
                it1+=1
    return ret

def merge_sort(arr):
    arr1 = []
    arr2 = []
    mid = int(len(arr)/2)
    if len(arr) == 1:
        return arr
    elif len(arr) > 2:
        arr1 = arr[0:mid]
        arr2 = arr[mid:len(arr)]
        return merge(merge_sort(arr1), merge_sort(arr2))
    elif len(arr) == 2:
        if arr[0]>arr[1]:
            temp = arr[0]
            arr[0] = arr[1]
            arr[1] = temp
    return arr

rawDescription: Merge Sort Implementation in Python

description: Merge Sort Implementation in Python


code:
data = " lorem ipsum \xe2\x80\x9csianhill7 lorem ipsum"
' '.join(e for e in data.split() if 31 < ord(e[0]) < 127)

rawDescription: re.sub greedy characters

description: Re.sub greedy characters


code: os.startfile('path/to/file.ext') # opens file in respective program

rawDescription: How to open a file in python 3

description: Open a file in python 3


code:
mylist = ['a',1,2,'b',3,4,'c',5,6]

v = iter(mylist)
mydict = {s: (next(v),next(v)) for s in v}
mydict

rawDescription: Python list to dict with multiple values for each key


code:
cur = 0
placesCode=['318','432','650 ']
for i in placesDict.values()[0].values():
    for j in i.values():
            j[j.keys()[0]] = placesCode[cur]
            cur+=1

placesDict

rawDescription: use route reference to edit nested dictionary in python

description: Use route reference to edit nested dictionary in python


code:
# without any parameters
def authentication_required(f):
    @functools.wraps(f)
    def _authentication_required(*args, **kwargs):
        # Do you login stuff here
        return f(*args, **kwargs)
    return _authentication_required

# With parameters
def authentication_required(*allowed_groups):
    def _authentication_required(f):
        @functools.wraps(f)
        def __authentication_required(*args, **kwargs):
            # Do you login stuff here
            return f(*args, **kwargs)
        return __authentication_required
    return _authentication_required

rawDescription: Writing a CherryPy Decorator for Authorization


code:
import re

BLOCK_RE = re.compile(r'{%\s*block\s*(\w+)\s*%}')
NAMED_BLOCK_RE = r'{%%\s*block\s*%s\s*%%}'  # Accepts string formatting
ENDBLOCK_RE = re.compile(r'{%\s*endblock\s*(?:\w+\s*)?%}')

def get_block_source(template_source, block_name):
    """
    Given a template's source code, and the name of a defined block tag,
    returns the source inside the block tag.
    """
    # Find the open block for the given name
    match = re.search(NAMED_BLOCK_RE % (block_name,), template_source)
    if match is None:
        raise ValueError(u'Template block {n} not found'.format(n=block_name))
    end = inner_start = start = match.end()
    end_width = 0
    while True:
        # Set ``end`` current end to just out side the previous end block
        end += end_width
        # Find the next end block
        match = re.search(ENDBLOCK_RE, template_source[end:])
        # Set ``end`` to just inside the next end block
        end += match.start()
        # Get the width of the end block, in case of another iteration
        end_width = match.end() - match.start()
        # Search for any open blocks between any previously found open blocks,
        # and the current ``end``
        nested = re.search(BLOCK_RE, template_source[inner_start:end])
        if nested is None:
            # Nothing found, so we have the correct end block
            break
        else:
            # Nested open block found, so set our nested search cursor to just
            # past the inner open block that was found, and continue iteration
            inner_start += nested.end()
    # Return the value between our ``start`` and final ``end`` locations
    return template_source[start:end]

rawDescription: Django - how to get the contents of a {% block %} tag from a template


code:
# Find all files that have been downloaded
subselect = Select(FileDownload.fid, distinct=True)
for f in store.find(File, File.fid.is_in(subselect)):
    print(f.filename, f.filedownloads.count())

rawDescription: Python Storm - Query ReferenceSet (one to many)


code: rounded = numpy.array(myarray, dtype='datetime64[m]')

rawDescription: How to round datetime64 values

description: Round datetime64 values


code:
clisocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
connection_id=0x41727101980
action=0
# transaction_id = random.randrange(1,65535)
transaction_id = 12345
print(transaction_id)
# 12345

packet=struct.pack(">QLL",connection_id,action,transaction_id)
print(repr(packet))
# "\x00\x00\x04\x17'\x10\x19\x80\x00\x00\x00\x00\x00\x0009"

clisocket.sendto(packet, ("tracker.istole.it", 80))
res = clisocket.recv(16)
action,transaction_id,connection_id=struct.unpack(">LLQ",res)
print(action)
# 0
print(transaction_id)
# 12345
print(connection_id)
# 2540598739861590271

rawDescription: Choosing format in pack() using struct module in python


code:
def keygen(key):
    keystream=bytearray(b'')
    for i in key:
        a = md5(i.encode())
        keystream += a.digest()
    return keystream

rawDescription: python independent hash input

description: Python independent hash input


code:
import tkinter as tk

root = tk.Tk()
main_frame = tk.Frame(root, border=3, relief=tk.GROOVE)
main_frame.grid()

for i in range(10):

    #Create Labels for numbering the rows:
    tk.Label(main_frame,
            text=str(i+1),
            border=1,
            relief=tk.GROOVE,
            padx=20,
            pady=20,
            ).grid(column=0, row=i)

    #Create Frames with a Label inside:
    frame = tk.Frame(main_frame,
        border=1,
        relief=tk.GROOVE,
        background="blue",
    )

    frame.grid(row=0, column=i+1, rowspan=i+1, sticky=tk.N+tk.S)

    tk.Label(frame,
            text='Rowspan {}'.format(i+1),
            border=1,
            relief=tk.GROOVE,
            padx=20,
            pady=20,).grid()

root.mainloop()

rawDescription: Python tkinter rowspan not resizing elements correctly


code: entity_two.__setattr(some_variable, some_value) #where some_variable is populated by user at runtime :)

rawDescription: Adding a user supplied property (at runtime) to an instance of Expando class in google app engine?


code:
for event in pygame.event.get(pygame.MOUSEBUTTONDOWN):
    mx, my = pygame.mouse.get_pos()
    if 375 <= mx <= 425 and 500 <= my <= 550:
        run = True
        while run:
            # statements
            # ...
            for event in pygame.event.get(pygame.MOUSEBUTTONDOWN):
                mx, my = pygame.mouse.get_pos()
                if 300 <= mx <= 350 and 500 <= my <= 550:
                    run = False

rawDescription: How to pause a loop with a mouse click using pygame?

description: Pause a loop with a mouse click using pygame


code:
class MyStaticText(wx.PyControl):
    def __init__(self, parent, id=wx.ID_ANY, label="",
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, validator=wx.DefaultValidator,
                 name="MyStaticText"):
        wx.PyControl.__init__(self, parent, id, pos, size, style|wx.NO_BORDER,
                              validator, name)
        wx.PyControl.SetLabel(self, label)
        self.InheritAttributes()
        self.SetInitialSize(size)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

    def OnPaint(self, event):
        dc = wx.BufferedPaintDC(self)
        self.Draw(dc)

    def Draw(self, dc):
        width, height = self.GetClientSize()

        if not width or not height:
            return

        backBrush = wx.Brush(wx.WHITE, wx.SOLID)
        dc.SetBackground(backBrush)
        dc.Clear()

        dc.SetTextForeground(wx.BLACK)
        dc.SetFont(self.GetFont())
        label = self.GetLabel()
        dc.DrawText(label, 0, 0)

    def OnEraseBackground(self, event):
        pass

    def SetLabel(self, label):
        wx.PyControl.SetLabel(self, label)
        self.InvalidateBestSize()
        self.SetSize(self.GetBestSize())
        self.Refresh()

    def SetFont(self, font):
        wx.PyControl.SetFont(self, font)
        self.InvalidateBestSize()
        self.SetSize(self.GetBestSize())
        self.Refresh()

    def DoGetBestSize(self):
        label = self.GetLabel()
        font = self.GetFont()

        if not font:
            font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)

        dc = wx.ClientDC(self)
        dc.SetFont(font)

        textWidth, textHeight = dc.GetTextExtent(label)
        best = wx.Size(textWidth, textHeight)
        self.CacheBestSize(best)
        return best

    def AcceptsFocus(self):
        return False

    def SetForegroundColour(self, colour):
        wx.PyControl.SetForegroundColour(self, colour)
        self.Refresh()

    def SetBackgroundColour(self, colour):
        wx.PyControl.SetBackgroundColour(self, colour)
        self.Refresh()

    def GetDefaultAttributes(self):
        return wx.StaticText.GetClassDefaultAttributes()

    def ShouldInheritColours(self):
        return True

rawDescription: Make disabled text render black

description: Make disabled text render black


code:
my_list=[['a',1], ['b', 2]]
my_dict = dict(my_list)
my_dict

rawDescription: How to easily make dictionary from list?

description: Easily make dictionary from list


code: os.execlp('open', 'open', '-n', '-a', 'Calculator')

rawDescription: python forked processes not executing with os.execlp

description: Python forked processes not executing with os.execlp


code:
def dump_svmlight_file_sparse(X, y, f, zero_based=True):
    X = X.sorted_indices().tocoo()

    if not zero_based:
        X.col += 1

    y = y.astype(int).astype(str)
    col = X.col.astype(str)
    dat = X.data.astype(str)

    last_row = 0
    f.write(y[0])

    for i in xrange(len(X.data)):
        while last_row < X.row[i]:
            last_row += 1
            f.write('\n'+y[last_row])

        f.write(' '+col[i]+':'+dat[i])

    f.write('\n')

rawDescription: Scikit-learn's dump_svmlight_file slow

description: Scikit-learn's dump_svmlight_file slow


code:
import subprocess
subprocess.call(["tclsh", "oommf.tcl", "avf2odt", "-average", "space", "-axis", "z", "-onefile",  "<filename>.txt", "-headers", "none", "-ipat", "*.omf"])

rawDescription: Use python to run a command line

description: Use python to run a command line


code:
import sys, pygame, random

SIZE = width, height = 640, 480
SPEED = [2, 2]
black = 0, 0, 0

class mySprite(pygame.sprite.Sprite):
    def __init__(self, image="ball.bmp", speed=[2,2]):

        pygame.sprite.Sprite.__init__(self)
        self.speed = speed
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()

    def update(self):
        global SIZE
        #i used 110 px because it's the size of the image, but it's better to use the rect property of the pygame
        if (self.rect.x <0) or (self.rect.x > 640-110):
            self.speed[0] *= -1
        if (self.rect.y<0) or (self.rect.y > 480-110):
            self.speed[1] *= -1

        self.rect.x =self.rect.x + self.speed[0]
        self.rect.y =self.rect.y + self.speed[1]

#OR:        self.rect = self.rect.move(self.speed)

    def draw(self, screen):
        screen.blit(self.image, self.rect)

#
pygame.init()
screen = pygame.display.set_mode(SIZE)

iaka = mySprite()

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    screen.fill(black)
    iaka.draw(screen)
    iaka.update()
    pygame.display.flip()

rawDescription: how to make a sprite bounce of the edges of the window in pygame

description: Make a sprite bounce of the edges of the window in pygame


code:
url (
    r'^question_detail-(?P<pk>\w+)$',
    user_passes_test(not_in_group_chef, login_url='public_connexion')(
        Question_detail.as_view()
    ),
    name='detail_question'
)

rawDescription: Django - how to use user_pass_test with urls


code:
a = 1
b = 2
c = 3
data = {'a': a, 'b': b, 'c': c}
min(data, key=data.get)

rawDescription: Find the minimum and display the variable name in python


code:
class ModelHandler(webapp.RequestHandler):
  def get(self, kind, key):
    model = db.class_for_kind(kind)
    instance = model.get(key)
    # Do something with the instance - eg, print it out

  def post(self, kind, key):
    model = db.class_for_kind(kind)
    instance = model.create_from_request(self.request)

application = webapp.WSGIApplication([
    ('/foo/([^/]+)/([^/]+)', ModelHandler),
])

def main():
  run_wsgi_app(application)

if __name__ == '__main__':
  main()

rawDescription: AppEngine elegant way to handle similar requests


code:
import datetime
thetime = '20150716170118'
parsed_time = datetime.datetime.strptime(thetime, '%Y%m%d%H%M%S')
formatted_time = datetime.datetime.strftime(parsed_time, '%a, %m/%d %Y %H:%M:%S')
formatted_time

rawDescription: Convert UNIX Varchar to datetime

description: Convert UNIX Varchar to datetime


code:
def check_enableusersite():
    """Check if user site directory is safe for inclusion

    The function tests for the command line flag (including environment var),
    process uid/gid equal to effective uid/gid.

    None: Disabled for security reasons
    False: Disabled by user (command line option)
    True: Safe and enabled
    """
    if sys.flags.no_user_site:
        return False

    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
        # check process uid == effective uid
        if os.geteuid() != os.getuid():
            return None
    if hasattr(os, "getgid") and hasattr(os, "getegid"):
        # check process gid == effective gid
        if os.getegid() != os.getgid():
            return None

    return True

rawDescription: How to disable `site.ENABLE_USER_SITE` for an environment?

description: Disable `site.ENABLE_USER_SITE` for an environment


code:
from autobahn.twisted.websocket import WebSocketServerProtocol, \
                                       WebSocketServerFactory

class TweetStreamProtocol(WebSocketServerProtocol):

   def sendTweets(self):
      for line in open('gistfile1.txt').readlines():
         ## decode UTF8 encoded file
         data = line.decode('utf8').split(',')

         ## now operate on data using Python string functions ..

         ## encode and send payload
         payload = data[2].encode('utf8')
         self.sendMessage(payload)

      self.sendMessage((u"\u03C0"*10).encode("utf8"))

   def onMessage(self, payload, isBinary):
      if payload == "tweetme":
         self.sendTweets()

if __name__ == '__main__':

   import sys

   from twisted.python import log
   from twisted.internet import reactor

   log.startLogging(sys.stdout)

   factory = WebSocketServerFactory("ws://localhost:9000", debug = False)
   factory.protocol = TweetStreamProtocol

   reactor.listenTCP(9000, factory)
   reactor.run()

rawDescription: How do I display UTF-8 characters sent through a websocket?

description: Display UTF-8 characters sent through a websocket


code:
from sqlalchemy import func

users = session.query(User.id, User.name, User.fullname, func.random().label('random_value'))
for user in users:
    print(user.id, user.name, user.fullname, user.random_value)

rawDescription: Column-name mapping in SQLAlchemy

description: Column-name mapping in SQLAlchemy


code:
import collections

def Numbers_deque(h = collections.deque()):
    if len(h) >= 10:
        h.clear()
    h.append(len(h)+1)
    print(h)

Numbers_deque()

rawDescription: Print Python deque items one at a time with all items before it


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

#dummy data
y = [range(20) + 3 * i for i in np.random.randn(3, 20)]
x = list(range(20))

#calculate the min and max series for each x
min_ser = [min(i) for i in np.transpose(y)]
max_ser = [max(i) for i in np.transpose(y)]

#initial plot
fig, axs = plt.subplots()
axs.plot(x, x)
for s in y:
    axs.scatter(x, s)

#plot the min and max series over the top
axs.fill_between(x, min_ser, max_ser, alpha=0.2)

rawDescription: How to draw enveloping line with a shaded area which incorporates a large number of data points?

description: Draw enveloping line with a shaded area which incorporates a large number of data points


code:
from PyQt4 import QtCore
QtCore.QObject.__mro__

rawDescription: Do PyQt classes inherit from object?

description: Do PyQt classes inherit from object


code:
def socketify( socket_protocol_compliant_object ):
    import _socket
    class proxy( _socket.socket ):
        def __init__( self ): pass
        def __getattribute__( self, attr_name ):
            return getattr( socket_protocol_compliant_object, attr_name )
        def __setattribute__( self, attr_name, new_value ):
            setattr( socket_protocol_compliant_object, attr_name, new_value )
    return proxy()

self._sslobj = _ssl.sslwrap( socketify(self._sock), server_side, keyfile, ... )

rawDescription: type enforcement on _ssl.sslwrap function params

description: Type enforcement on _ssl.sslwrap function params


code:
import numpy
import matplotlib.pyplot as plt

bincount = 100
mean, stdev, population = 0, 1, 10000
separation = 3*stdev

norm1 = numpy.random.normal(mean, stdev, population)
norm2 = numpy.random.normal(mean + separation, stdev, population)
comb = numpy.concatenate([norm1, norm2]) #concatenate nd_arrays

fig = plt.figure("Bayesian")

plt.subplot2grid((4, 4), (2, 0), colspan=4, rowspan=1)
plt.title("Combined")
hist3 = plt.hist(comb, bincount) #population, bins, patch = plt.hist()

plt.subplot2grid((4, 4), (0, 0), colspan=2, rowspan=2)
plt.title("Class 1")
hist1 = plt.hist(norm1, bins=hist3[1])

plt.subplot2grid((4, 4), (0, 2), colspan=2, rowspan=2)
plt.title("Class 2")
hist2 = plt.hist(norm2, bins=hist3[1])

index = int(len(hist3[1])/2)#arbitrarily choosing the middle bin
bin = hist3[1][index]
binsize = (max(hist3[1])-min(hist3[1]))/len(hist3[1])
probIndex = 1/len(hist3[1])
probClass = len(norm1)/len(comb)
condProbClass = hist1[0][index]/sum(hist1[0])
condProbIndex = probClass*condProbClass/probIndex

t = "An item is found at index {idx}, which corresponds to {binStart}-{binEnd}. What is the probabilty it belongs to class 1?\n\n"\
    "Given this, the probability of any item being Class 1 is {pC1}\n"\
    "The probabilty of any item being found at index {idx} is {pInd}\n"\
    "The conditional probability of the item falling in this index given it belongs to class 1 is {cpC1}\n"\
    "Using Bayes-Theorem, we can now find the probability of an item found at this index belongs to class 1 is {cpI}"\
    .format(
    idx=index,
    binStart=bin-binsize/2,
    binEnd=bin+binsize/2,
    pC1=probClass,
    pInd=probIndex,
    cpC1=condProbClass,
    cpI=condProbIndex
)

plt.tight_layout()
plt.figtext(0, 0, t, wrap=True)
plt.show()

rawDescription: Add caption to figure which has subplots


code:
data = (130, 150, 200, 100, 130, 147)

def find_elevated_bloodpressure(bloodpressure, upper_limit):
    results = []
    for x in bloodpressure:
        if x > upper_limit:
            results.append(x)
    return results

rawDescription: Finding all elements in a tuple that match a condition


rawDescription: Avoid looping over arrays to get products of elements in numpy


rawDescription: Simple unique non-priority queue system

description: Simple unique non-priority queue system


code:
def render(self, src, **kwargs):
   results = self._tree_read(src, self.src_tree_path)

   for host in result[0][1]:
      subprocess.call(["/bin/bash", "/opt/hosts.sh", host["username"], host["url"], host["hostname"]], shell=False)

rawDescription: How to get required values from dict in Python

description: Get required values from dict in Python


code:
import re

IDs = re.findall('(?<=<option value=")\w+', html)
names = re.findall('(?<=>)\w+(?=</option>)', html)
nameID =  dict(zip(IDs,names))

rawDescription: Python: How to build a dictionary with multiple slip strings


code:
def my_filter(df, **kwargs):
    for column in kwargs:
        filter_value = kwargs[column]
        df = df.loc[df[column] == filter_value, ]
    return df

filtered_df = my_filter(df, col1='N', col2='S')

rawDescription: Python: function default input that stands for everything


code: timeit.timeit("A0(aList)", setup="from HW2 import A0; aList = [randint(1,256) * (-1) ** randint(1,2) for j in range("+str(n)+")] ", number=1000000)

rawDescription: What code does Python's timeit(...) method actually time in this bit of code?


code:
def lower_db_name(cls):
    cls._meta.db_table = cls.__name__.lower()
    return cls

@lower_db_name
class Student(models.Model):
    class Meta:
        pass

rawDescription: Meta class inside class, how to get the name of the top class


code:
import re

PASSED = re.compile(r" passed : (\d+)")

def get_passed_values(s):
    for match in PASSED.finditer(s):
        yield int(match.group(1))   # return the number as an integer

def is_complete(s):
    return any(v > 0 for v in get_passed_values(s))

with open("test.txt") as test:
    s = test.read()
    if is_complete(s):
        print("TASK COMPLETED")
    else:
        raise ValueError("All 0s!")

rawDescription: How to compare multiple numbers from the output of task and print something in Python?

description: Compare multiple numbers from the output of task and print something in Python


code:
if 'bdist_msi' in sys.argv:
    sys.argv += ['--initial-target-dir', 'c:\default\path']

rawDescription: How do I specify the default install path of an msi in cx_freeze and distutils?

description: Specify the default install path of an msi in cx_freeze and distutils


code:
import io
import time

def checklog(fs,logfile):
    trytimes = 10
    line = ''
    while line == '':
        time.sleep(1)
        line = fs.readline().replace('\n','')
        trytimes = trytimes - 1
        while trytimes == 0 and line == '':
            try:
                fs = io.open(logfile,'rb')
                fs.seek(0,2)
                trytimes = 10
                break
            except:
                time.sleep(10)
    return line,fs

logfile="app.log"
fs = io.open(logfile,'rb')
fs.seek(0,2)# seek to tail of the logfile
while True:
    line = fs.readline().replace('\n','')
    while line == '':
        line,fs = checklog(fs,logfile)
        #do something for line;

rawDescription: Log tailing daemon with Python

description: Log tailing daemon with Python


code:
import multiprocessing.pool
concurrent = 200

def makeRequest(ourl):
    try:
        api_call = urlopen(ourl).read()
        result = json.loads(api_call)
        return "success", ourl
    except:
        return "error", ourl

def main():
    api_calls = [
        'http:http://jsonplaceholder.typicode.com/posts/{}'.format(i)
        for i in range(1,5)]

    # a thread pool that implements the process pool API.
    pool = multiprocessing.pool.ThreadPool(processes=concurrent)
    return_list = pool.map(makeRequest, api_calls, chunksize=1)
    pool.close()
    for status, data in return_list:
        print(data)

main()

rawDescription: Combine python thread results into one list


code:
from sympy import *

x,y,a,z = symbols('x y a z')
equation = a*x/y

new_eq = solve(equation - z, x)  # its value is [y*z/a]

rawDescription: Solving an equation for a variable

description: Solving an equation for a variable


code:
ISO_PATH = "your_iso_path_here"

# Mount the ISO in your OS
os.system("mkdir /media/tmp_iso")
os.system("mount -o rw,loop %s /media/tmp_iso" % ISO_PATH)

# Do your Pythonic manipulation here:
new_file = open("/media/tmp_iso/.config", 'w')
new_file.write(data)
new_file.close()

# Unmount
os.system("umount /media/tmp_iso")
os.system("rmdir /media/tmp_iso")

rawDescription: Modify .iso file with Python

description: Modify .iso file with Python


code:
s = "john:doe"
s.split(':')
fname, lname = s.split(':')
fname
lname

rawDescription: Get String Before And After Character Then Set Them As a Variable Python


code: thread.start_new_thread(node_check, ())

rawDescription: Global variable update from thread and access from main in python


code:
def app(environ, start_response):
    start_response('200 OK', [('Content-type', 'text/plain')])
    return ['Hello world!\n']

rawDescription: Why does WSGI have to use start_response and return an iterator?


code: add_and_record.__doc__ = inspect.cleandoc(func.__doc__) + decorator_doc

rawDescription: Amending docstrings from decoators, while retaining formattting


rawDescription: Dot products in Pandas

description: Dot products in Pandas


code: strings = re.findall('word1.*?word2.*?word3', f.read(), re.DOTALL)

rawDescription: How to ignore multiple whitespace chars and words in python regex

description: Ignore multiple whitespace chars and words in python regex


code:
def incomplete_tasks(modeladmin, request, queryset):
    queryset.update(completed=False)
incomplete_tasks.short_description = 'Mark as Not Complete'

class TaskAdmin(admin.ModelAdmin):
    list_display = ['title', 'completed']
    ordering = ['created']
    actions = [incomplete_tasks,]

admin.site.register(Task, TaskAdmin)

rawDescription: Django: Run scripts from admin by selecting object's name


rawDescription: How to properly do user authentication and maintain session with Tornado?

description: Properly do user authentication and maintain session with Tornado


code:
df['dist'] = abs(df['count'] - df['count'].median())
df
df['dist'].median()

rawDescription: median of pandas dataframe

description: Median of pandas dataframe


code:
class UpQSocket(QTcpSocket):
    data_ready = pyqtSignal(unicode)

def __init__(self):
    QTcpSocket.__init__(self)
    self.wait_len = ''
    self.temp = ''
    self.setSocketOption(QTcpSocket.KeepAliveOption, QVariant(1))
    self.readyRead.connect(self.on_ready_read)

def connectToHost(self, host, port):
    self.temp = ''
    self.wait_len = ''
    self.abort()
    QTcpSocket.connectToHost(self, host, port)

def close(self):
    QTcpSocket.close(self)

def send(self, data):
    self.writeData('%s|%s' % (len(data), data))

def on_ready_read(self):
    if self.bytesAvailable():
        data = str(self.readAll())
        while data:
            if not self.wait_len and '|' in data:#new data and new message
                    self.wait_len , data = data.split('|',1)
                    if match('[0-9]+', self.wait_len) and (len(self.wait_len) <= MAX_WAIT_LEN) and data.startswith('{'):#okay, this is normal length
                        self.wait_len = int(self.wait_len)
                        self.temp = data[:self.wait_len]
                        data = data[self.wait_len:]
                    else:#oh, it was crap
                        self.wait_len , self.temp = '',''
                        return
            elif self.wait_len:#okay, not new message, appending
                tl= int(self.wait_len)-len(self.temp)
                self.temp+=data[:tl]
                data=data[tl:]
            elif not self.wait_len and not '|' in data:#crap
                return
            if self.wait_len and self.wait_len == len(self.temp):#okay, full message
                    self.data_ready.emit(self.temp)
                    self.wait_len , self.temp = '',''
                    if not data:
                        return

rawDescription: Python select.select() error 10022 on windows


code:
class SomeScreen(Screen):
    def __init__(self,**kwargs):
        #execute the normal __init__ from the parent
        super().__init__(**kwargs)

        #the callback function that will be used
        def on_text(instance, value):
            print('The widget', instance, 'have:', value)

        #wrap the binding in a function to be able to schedule it
        def bind_to_text_event(*args):
            self.ids['id_from_kvlang'].bind(text=update_price)

        #now schedule the binding
        Clock.schedule_once(bind_to_text_event)

rawDescription: Kivy: How to attach a callback to a widget created in kvlang


code:
from itertools import cycle, islice

peptide = [113, 129, 128, 114]
spectrum = []
for num in range(1, len(peptide)):
    for start in range(len(peptide)):
        group = islice(cycle(peptide), start, start + num)
        spectrum.append(sum(group))
spectrum.append(sum(peptide)) # add the entire list only once

rawDescription: Generating a Cyclic Spectrum

description: Generating a Cyclic Spectrum


code:
import numpy as np
from scipy.stats import rv_discrete

Xvalues = np.array([(-2,0,2), (0,2,3),(-2,0,2)])
Xprobabilities = np.array([(0.4,0.2,0.4), (0.2,0.4,0.4),(0.4,0.4,0.2)])
for values,probabilities in zip(Xvalues, Xprobabilities):
    distrib = rv_discrete(values=(values,probabilities))
    print(distrib.rvs(size=10))

rawDescription: How to connect row values of a matrix with an index for a parameter

description: Connect row values of a matrix with an index for a parameter


code:
while comp not in items:
    print ('Please enter either 1, 2, or 3.')
    comp= (input('Pick an option [1,2,3] '))

rawDescription: User can only use input from list

description: User can only use input from list


code:
class MyClass:
    result = None

    def a(self):
        # do things and store in self.result
        self.result = ...
        return self

    def b(self, value):
        # do things and store in self.result
        self.result = ...
        return self

rawDescription: Python chainable class methods

description: Python chainable class methods


code:
shared_arr = mp.Array(ctypes.c_double, N)
arr = tonumpyarray(shared_arr)

rawDescription: Python read image to numpy array with multiprocessing


code:
import timeit
N = 10; timeit.timeit('[(i,) for i in range(10**6)]', 'gc.enable()', number=N) / N
N = 10; timeit.timeit('[(i,) for i in range(10**6)]', number=N) / N

rawDescription: Inconsistency between %time and %timeit in IPython


code: {{ value|markdown:"debatesyntax" }}

rawDescription: Get python-markdown extension to output html tags with a specific class attribute in Django?


code:
import win32ui
import win32con
import time
from ctypes import *

PUL = POINTER(c_ulong)
class KeyBdInput(Structure):
    _fields_ = [("wVk", c_ushort),
                ("wScan", c_ushort),
                ("dwFlags", c_ulong),
                ("time", c_ulong),
                ("dwExtraInfo", PUL)]

class HardwareInput(Structure):
    _fields_ = [("uMsg", c_ulong),
                ("wParamL", c_short),
                ("wParamH", c_ushort)]

class MouseInput(Structure):
    _fields_ = [("dx", c_long),
                ("dy", c_long),
                ("mouseData", c_ulong),
                ("dwFlags", c_ulong),
                ("time",c_ulong),
                ("dwExtraInfo", PUL)]

class Input_I(Union):
    _fields_ = [("ki", KeyBdInput),
                 ("mi", MouseInput),
                 ("hi", HardwareInput)]

class Input(Structure):
    _fields_ = [("type", c_ulong),
                ("ii", Input_I)]

def send_char(char):
    FInputs = Input * 1
    extra = c_ulong(0)
    ii_ = Input_I()
    KEYEVENTF_UNICODE = 0x4
    ii_.ki = KeyBdInput( 0, ord(char), KEYEVENTF_UNICODE, 0, pointer(extra) )
    x = FInputs( ( 1, ii_ ) )
    windll.user32.SendInput(1, pointer(x), sizeof(x[0]))

if __name__ == '__main__':
    wnd = win32ui.FindWindow(None, '* Untitled - Notepad2 (Administrator)')
    type_this = 'jaraco'
    wnd.SetFocus()
    wnd.SetForegroundWindow()
    for char in type_this:
        send_char(char)

rawDescription: How can I make a T9 style on-screen keyboard for Windows?

description: Make a T9 style on-screen keyboard for Windows


rawDescription: Comparing user's facebook/twitter friends to site's users in Python/Django


rawDescription: What does 7e0 actually do in Python?

description: What does 7e0 actually do in Python


code:
from random import randrange
cats = [1,2,3,4]
i = randrange(len(cats))

for c in cats[i:]+cats[:i]:
   pass

rawDescription: Python -- how to loop over range starting at random point


code:
largest = 0
for x in xrange(0, 1000):
    for y in xrange(0, 1000):
        #print '%d * %d = %d' % (x, y, x*y)
        num = (x * y)
        q = list(str(x * y))
        q.reverse()
        w = q
        #print(w)
        s = filter(str.isdigit, repr(q))
        q = int(s)
        #print(q)
        if num == q and num > largest:
            largest = num
            hold3 = num, q, x , y
            print(hold3)

print(hold3) # correctly shows 906609 is the largest number

rawDescription: Largest palindrome product python

description: Largest palindrome product python


code: myDictionary["key1"]["aKey"] = newValue

rawDescription: Modifying values of dictionary contained in a dictionary


code:
import datetime
from time import sleep

while True:
    lcd_byte(DISPLAY_LINE_1, DISPLAY_CMD)
    lcd_string("CPU Temp: " + str(round(get_cpu_temp(), 2)))
    lcd_byte(DISPLAY_LINE_2, DISPLAY_CMD)
    lcd_string("Time:" + str(datetime.datetime.now().time()))

    sleep(10)

rawDescription: Python LCD Display

description: Python LCD Display


code:
import random
x = [1, 2, 3, 4, 3, 4]
random.shuffle(x)
x
random.shuffle(x)
x

rawDescription: Best way to randomize a list of strings in Python

description: Randomize a list of strings in Python


rawDescription: Deleting surplus blank lines using Python


code:
import Tkinter as tk

root = tk.Tk()

root.state("zoomed")

root.mainloop()

rawDescription: Tkinter window with both title bar and windows taskbar


rawDescription: How to "select distinct" across multiple data frame columns in pandas?


code:
from datetime import datetime
import pytz

dt = datetime.strptime("12/31/2012 16:15", "%m/%d/%Y %H:%M") \
             .replace(tzinfo = pytz.FixedOffset(-240)) \
             .astimezone(pytz.timezone('America/New_York'))

rawDescription: How to convert UTC-4 to US/Eastern in python?

description: Convert UTC-4 to US/Eastern in python


code:
from string import ascii_letters
for element in chars:
   if element in ascii_letters:
       print(element)

rawDescription: How to remove every non-alphabetic character in Python 3

description: Remove every non-alphabetic character in Python 3


code:
import numpy as np
data_set = np.ones((10, 10))
data_set[4,4] = 2
data_set[5,5] = 2
data_set[6,6] = 2
data_set[data_set != 2].sum()
data_set != 2

rawDescription: Determine sum of numpy array while excluding certain values


code:
def renderMeasureLine(self, mouseEvent):
    if (self.measuring and mouseEvent.inaxes == self.ui.canvas2.axes
            and len(self.pointListX) > 0):
        if self.dotted_line in self.ui.canvas2.axes.lines:
            x, y = self.dotted_line.get_data()
            x.append(mouseEvent.xdata)
            y.append(mouseEvent.ydata)
            self.dotted_line.set_data(x, y)
        else:
            self.dotted_line = Line2D(
                [self.pointListX[-1],mouseEvent.xdata],
                [self.pointListY[-1],mouseEvent.ydata],
                color=color, axes=self.ui.canvas2.axes, ls = '--')
            self.ui.canvas2.axes.add_line(self.dotted_line)

        self.ui.canvas2.blit(self.ui.canvas2.axes.bbox)
        self.ui.canvas2.draw_idle()

rawDescription: Slow Line2D rendering in matplotlib

description: Slow Line2D rendering in matplotlib


code:
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
s.bind("foo.sock")
s.close()
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
s.bind("foo.sock")
import os
os.unlink("foo.sock")
s.bind("foo.sock")
s.close()

rawDescription: Gunicorn - Where do Unix sockets come from?


rawDescription: Searching a sequence of characters from a string in python


code:
import re

regexes = (
    re.compile("visit my blog at: .*$", re.IGNORECASE),
    re.compile("please post this:", re.IGNORECASE),
    re.compile("please can you include this:", re.IGNORECASE)
    # etc
)

for filePath in files:
    with open(filePath) as file:
        for line in file:
            for regex in regexes:
                print(re.sub(regex, ""))

rawDescription: Text extraction from email in Python

description: Text extraction from email in Python


code: sum([val[-2] * val[-1] for val in a.values()])

rawDescription: Multiply key*value in a list inside a dictionary?


code:
team =  "Hisingsbacka - Guldhedens IK"
homeTeam, awayTeam = team.split(" - " )

rawDescription: How to remove a specific white space in a string python

description: Remove a specific white space in a string python


code:
import itertools
[
   ' '.join(items)
   for _, items in itertools.groupby('DEL MONTE Alfredo'.split(), str.isupper)
]

rawDescription: Split a string of words by uppercase words


code:
class Class:
    _map = {0: "a", 1: "b"}

    def getmap(self):
        # Create an empty map
        mymap = {}
        # Iterate through the parent classes in order of inheritance
        for Base in self.__class__.__bases__[::-1]:
            # Check if the class has a "getmap" attribute
            if issubclass(Base, Class):
                # Initialize the parent class
                b = Base()
                # If so, add its data to mymap
                mymap.update(b.getmap())
        # Finally add the classes map data to mymap, as it is at the top of the inheritance
        mymap.update(self._map)
        return mymap

class SubClass(Class):
    _map = {2: "c"}

class SubSubClass(SubClass):
    _map = {0: "z", 3: "d"}

c = Class()
sc = SubClass()
ssc = SubSubClass()

print(c.getmap())  # -> {0: 'a', 1: 'b'}
print(sc.getmap())  # -> {0: 'a', 1: 'b', 2: 'c'}
print(ssc.getmap())  # -> {0: 'z', 1: 'b', 2: 'c', 3: 'd'}

rawDescription: Python: selectively overloading attributes?


rawDescription: Sort numpy array by row and order matching values based on original array


code:
total = 0
counter = 0

while True:
    entry = int(input("Enter Test score: "))
    if entry == 0: break
    total += entry   # this should be in while loop
    counter += 1

total = total * 1.0
if counter == 0: exit(1)
avg = total / counter
print("Average is: %3.f" % avg + '%')

rawDescription: python average test score

description: Python average test score


code:
from tkinter.filedialog import askopenfilename
from tkinter import Tk

Tk().withdraw()
filename = askopenfilename()

rawDescription: Tkinter askopenfilename() annoying window


code:
from projectname.algorithms import module1

module1.method1(parameter1)

module1.method2(parameter1)

rawDescription: Use classes or modules to group static like methods?


code:
month_dicts = [{} for _ in range(12)] # twelve dicts
numbers = ["%02d" % x for x in range(1,13)] # strings "01" ... "12"

# the dict
MONTHS_DICT = dict(zip(numbers, month_dicts))
# the dict for March
MONTHS_DICT["03"]

rawDescription: Mass variable declaration and assignment in Python


code:
import re
a = 'hi foo hi bar hi ho'
old_stuff = "hi"
new_stuff = "yo"

[a[:m.start()] + new_stuff + a[m.end():] for m in re.finditer(old_stuff, a)]

rawDescription: Create a list composed of one string per regex substitution?


code:
def moveCircle(self, event):
    dif = {
                    "Up":(0,-5),
                    "Down":(0,5),
                    "Left":(-5,0),
                    "Right":(5,0),
            }
    self.moveCanvas(*(dif[event.keysym]))
    self.canvas.update

def moveCanvas(self, xdif, ydif):
    self.canvas.move("circle", xdif, ydif)
    self.canvas.move("text", xdif, ydif)
    self.x1 += xdif
    self.x2 += xdif
    self.y1 += ydif
    self.y2 += ydif

rawDescription: Can you move two canvas objects in one line?

description: Move two canvas objects in one line


code:
class Stopwatch(object):
    def __init__(self, callback):
        self._stop = False
        self.callback = callback

    @property
    def stop(self): return self._stop

    @stop.setter
    def stop(self, value):
        self._stop = value
        if value: self.callback()

rawDescription: Watching a property for changes

description: Watching a property for changes


code:
from django.forms import ModelForm
from myapp.models import Author
class AuthorForm(ModelForm):
    class Meta:
        model = Author
        localized_fields = ('birth_date',)

rawDescription: Enable Django format localization by default


code:
import re
text = 'adsfklaiin2007daf adf adflkajf;j 2008afadfkjkj'
re.sub("[^0-9]"," ",text)

rawDescription: How can I strip unwanted characters from a string in python?

description: Strip unwanted characters from a string in python


code:
#!/usr/bin/env python

import Tkinter
import tkFont

class App:
    def __init__(self):

        # Set up the text box
        self.root = Tkinter.Tk()
        self.text = Tkinter.Text(self.root, width=20, height=5)
        self.text.insert(Tkinter.INSERT, "Hello...")
        self.text.pack()

        # set up a mouse event
        self.text.bind("<Button-1>", self.click)

        # Set Tkniter's main loop
        self.root.mainloop()

    def click(self, event):
        self.text.tag_add("here", "1.0", "1.4")
        self.text.tag_config("here", background="yellow", font=tkFont.Font(size=36))

if __name__ == "__main__":
    App()

rawDescription: resize text in tkinter box

description: Resize text in tkinter box


code:
urlpatterns = [
    url(r'^map/$', geov.map_view, name = "map_view"),
    url(r'^map/(?P<search_place>[\w-]+)/$', geov.map_view, name = "map_view_accurate"),
    url(r'^map/(?P<search_place>[\w-]+)/(?P<digit>\d+)/$', geov.map_view),
]

rawDescription: Django URL Regex not capturing Int

description: Django URL Regex not capturing Int


code:
self.order_entries = [x for x in self.order_entries
                      if x.Order_ID != Order_ID or x.Item_ID != Item_ID]

rawDescription: How to find the index of an object in a list of objects given two attributes?

description: Find the index of an object in a list of objects given two attributes


code:
# -*- coding: utf-8 -*-
import re
import scrapy

# item class included here
class DmozItem(scrapy.Item):
    # define the fields for your item here like:
    link = scrapy.Field()
    attr = scrapy.Field()

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["craigslist.org"]
    start_urls = [
    "http://chicago.craigslist.org/search/vgm?"
    ]

    BASE_URL = 'http://chicago.craigslist.org/'

    def parse(self, response):
        links = response.xpath('//a[@class="hdrlnk"]/@href').extract()
        for link in links:
            absolute_url = self.BASE_URL + link
            yield scrapy.Request(absolute_url, callback=self.parse_attr)

    def parse_attr(self, response):
        match = re.search(r"(\w+)\.html", response.url)
        if match:
            item_id = match.group(1)
            url = self.BASE_URL + "reply/chi/vgm/" + item_id

            item = DmozItem()
            item["link"] = response.url

            return scrapy.Request(url, meta={'item': item}, callback=self.parse_contact)

    def parse_contact(self, response):
        item = response.meta['item']
        item["attr"] = "".join(response.xpath("//div[@class='anonemail']//text()").extract())
        return item

rawDescription: Scrapy follow link and collect email

description: Scrapy follow link and collect email


code:
if request.method == "POST":
    post_dict = request.POST.copy()
    keys = post_dict.keys()
    attributesValues = AttributeValue.objects.filter(feature__pk = feature_id,
                                                     attribute__name__in=keys)

    for av in attributesValues: #update all the records that are present
        if av.attribute.name in keys:
            av.value = post_dict.get(av.attribute.name)
            if av.value:
                av.save()

    #Now fetch all the new keys can create objects.
    avs = attributesValues.values_list('attribute__name', flat=True)
    new_keys = list(set(keys) - set(list(avs)))
    for key in new_keys:
        av = AttributeValue.objects.create(feature_pk=feature_id,
                                           value = post_dict.get(key))
    #rest of the code.

rawDescription: Python - in operator and getitem

description: Python - in operator and getitem


code:
from flask import Flask, request, redirect

app = Flask(__name__)

# really look in db here or do whatever you need to do to validate this as a valid topic.
def is_valid_topic(topic):
    if topic == "foo":
        return False
    else:
        return True

@app.route('/')
def index():
    return '<form action="topic/" method="post"><input name="topic" type="text"><input type="submit"/></form>'

@app.route('/topic/', methods=['POST'])
def find_topic():
    t = request.form['topic']
    if is_valid_topic(t):
        return redirect('topic/%s' % t)
    else:
        return "404 error INVALID TOPIC", 404

@app.route('/topic/<topic>')
def show_topic(topic):
    if is_valid_topic(topic):
        return '''
The topic is %s
''' % topic
    else:
        return "404 error INVALID TOPIC", 404

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: How do I respond to a get request with Flask?

description: Respond to a get request with Flask


code:
import numpy as np
import scipy as sp
import scipy.sparse

x = np.arange(10)

# "0" here indicates the main diagonal...
# "y" will be a dia_matrix type of sparse array, by default
y = sp.sparse.spdiags(x, 0, x.size, x.size)

rawDescription: Efficient way to create a diagonal sparse matrix


code:
import itertools
List1 = [ ['a','b'], ['c','d','e'], ['f'] ]
List2 = [ ['g','h','i'], ['j'], ['k','l'] ]
list(itertools.chain.from_iterable(itertools.product(a,b) for a,b in zip(List1, List2)))

rawDescription: Python: Combination in lists of lists (?)


code:
class Dummy(object):
    def __init__(self, mylist=None):
        self.mylist = mylist if mylist is not None else []

rawDescription: Variable scope in python unittest

description: Variable scope in python unittest


code:
import numpy as np
x = np.array([1,2,31,32,4,0,3,0,0,0])
z = np.array([99] * len(x))
y = np.where(x != 0, x, z)
y

rawDescription: Overlay part of the matrix on top of another


code:
L = ['actor_1', 'actor_3', 'actor_130', 'actor_55', 'actor_5']
def sort_key(s):
    s, n = s.split('_')
    return s, int(n)
L.sort(key=sort_key)
L

rawDescription: How to sort list depending on substring?

description: Sort list depending on substring


code:
count = 0
for line in lines:
    if line.startswith ('"""'):
        count += 1
        if count < 3:
            # Before or during end of the docstring
            continue
    # Line is after docstring

rawDescription: How to skip the docstring using regex

description: Skip the docstring using regex


code:
ops = (do_operation_1, do_operation_2, do_operation_3)

for op in ops:
    if mybool:
        op()
    else:
        return

rawDescription: Is there a way to decorate/perform operations on every line of a function in Python?


code:
from sklearn.feature_extraction.text import TfidfVectorizer
vect = TfidfVectorizer(min_df=1)
tfidf = vect.fit_transform(["I'd like an apple",
                            "An apple a day keeps the doctor away",
                            "Never compare an apple to an orange",
                            "I prefer scikit-learn to Orange"])
(tfidf * tfidf.T).A

rawDescription: Term document matrix and cosine similarity in Python


code:
def sendpayment(sender, recipient, amount):
    #first fetch the sender and recipient accounts
    '''Previously had
    for s in Account.accountList:
        if s.name == sender:
            break
    for r in Account.accountList:
        if r.name == recipient:
            break
    '''
    s = filter(lambda x: x.name == sender, Account.accountList)[0]
    r = filter(lambda x: x.name == recipient, Account.accountList)[0]
    r.balance += amount
    s.balance -= amount
    print(r.balance, s.balance)

rawDescription: Python: Changing the value of an instance from a list comprehension


code:
class EventInvitation(db.Model):
    # ...
    __table_args__ = (
        db.UniqueConstraint(event_id, from_id, to_id),
    )

rawDescription: How is a unique constraint across three columns defined?


code:
import lxml.etree

content='''\

NameDave Davies

Address123 Greyfriars Road, London
'''

root=lxml.etree.fromstring(content,parser=lxml.etree.HTMLParser())
for elt in root.findall('**/span'):
    print(elt.text, elt.tail)

# ('Name', 'Dave Davies')
# ('Address', '123 Greyfriars Road, London')

rawDescription: Python parsing: lxml to get just part of a tag's text


rawDescription: Manually triggering the ttk notebook tab change event


code:
max(mywords, key=len)
min(mywords, key=len)

rawDescription: How do i print the longest and shortest words out of a given set of words?

description: Print the longest and shortest words out of a given set of words


code: found_keys = numpy.where((my_array[:, 0] > start_time)*(my_array[:, 0] < end_time))[0]

rawDescription: Searching Python dictionary keys

description: Searching Python dictionary keys


code:
import re
deletetable = re.compile(r'delete(?:\s+\w+)*?\s+from\s+(?P<tablename>[\w.]+)',
           re.MULTILINE | re.DOTALL)
teststring = 'delete from my_db.my_table \r\n where\r\n(my_column >= 5/2 or my_column is null);'
match =deletetable.search(teststring)
if match:
    print(match.group("tablename"))

rawDescription: parsing mySQL code using regexp in python

description: Parsing mySQL code using regexp in python


code:
###
### Backup to memory
###

# We will copy the disk database into a memory database

memcon=apsw.Connection(":memory:")

# Copy into memory
with memcon.backup("main", connection, "main") as backup:
    backup.step() # copy whole database in one go

# There will be no disk accesses for this query
for row in memcon.cursor().execute("select * from s"):
    pass

rawDescription: In python, how can I load a sqlite db completely to memory before connecting to it?


code:
slice_idx = N.shape(data).index(27)
slices = [ slice( 0, None, None),]*4
slices.insert( slice_idx, slice( 0, tot_slices/2, None))
data_new = data.__getitem__(slices)

rawDescription: Selection of data in a single dimension (which can vary) in a multi-dimensional array


code: slice(*[{True: lambda n: None, False: int}[x == ''](x) for x in (mystring.split(':') + ['', '', ''])[:3]])

rawDescription: python create slice object from string

description: Python create slice object from string


code:
import socket
socket._fileobject.default_bufsize = 0

rawDescription: How to read continous HTTP streaming data in Python?

description: Read continous HTTP streaming data in Python


rawDescription: Using Python + Selenium, how to find whether the page title contains a particular string?


code:
#Add text fields to a dictionary.
text_dict = {}
for kind in ['score','instructions','time' ]:
    text = viz.addText('', viz.SCREEN )
    text.setScale( .5,.5)
    text.alignment( viz.TEXT_CENTER_BASE )
    text.alpha( 1 )
    text_dict[ kind ] = text
text_dict['score'].setPosition( .1,.9 )
text_dict['instructions'].setPosition( .5,.5 )
text_dict['time'].setPosition( .1,.85 )

def game_timer_task():
    #Grab the text field for
    #time.
    text = text_dict[ 'time' ]
    time = 0
    text.message( 'Time: 0' )
    #Loop through as long as time
    #is under a certain number of
    #seconds.
    while time < 10:
        yield viztask.waitTime( 1 )
        time += 1
        text.message( 'Time: ' + str( time ) )

def game():
    time_passing = viztask.waitTask( game_timer_task() )
    data = viz.Data()

    yield viztask.waitAny( [time_passing], data )

    if data.condition == time_passing:
        game_over = text.message( 'Game Over!' )
        game_over.setPosition( .1,.85 )

def main_sequence():
    yield game()

viztask.schedule( main_sequence() )

rawDescription: Adding a click function to a button in Python


code:
i = 3
l = [i+x for x in range(10)]
l

rawDescription: comprehension and variables scope

description: Comprehension and variables scope


code:
import sys
from PyQt4 import QtGui
from mainwindow import Ui_MainWindow
from dialog import Ui_Dialog

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.show_dialog)
    def show_dialog(self):
        dialog = Dialog()
        ret = dialog.exec_()
        if ret == QtGui.QDialog.Accepted:
            self.textEdit.append('accepted')
        else:
            self.textEdit.append('rejected')

class Dialog(QtGui.QDialog, Ui_Dialog):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setupUi(self)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec_())

rawDescription: Having Trouble opening up a Qt4 python file from another python(2.7) file


rawDescription: Seaborn showing scientific notation in heatmap for 3-digit numbers


code:
import resource

resource.setrlimit(
    resource.RLIMIT_CORE,
    (resource.RLIM_INFINITY, resource.RLIM_INFINITY))

rawDescription: set `ulimit -c` from outside shell

description: Set `ulimit -c` from outside shell


code:
from collections import defaultdict

date_parse = re.compile(r'Date:\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)')

c = defaultdict(int)

for line in sys.stdin:
    m = date_parse.match(line)
    if m is None:
        # pattern did not match
        # could handle error or log it here if desired
        continue # skip to handling next input line
    month = m.group(1)
    c[month] += 1

rawDescription: Can you place an instance of a member of a list within a regex to match in python?

description: Place an instance of a member of a list within a regex to match in python


code:
import Tkinter as tk
import tkSimpleDialog

def highlight():
    var = tkSimpleDialog.askstring("Text Highlighter", "format: x.x-x.x")
    a,b = var.split("-")
    aText.tag_add("bt", a, b)

txt = "First line of text \nSecond line of text \nThird line of text"

lord = tk.Tk()

aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()

aText.insert(tk.INSERT, txt)

aButton = tk.Button(lord, text="highlight", command=highlight)
aButton.grid()

aText.tag_config("bt", background="yellow")

lord.mainloop()

rawDescription: Highlighting a specific position of a string?


code:
class Server(object):
    def __init__(self):
        self.cores = []

rawDescription: Cleaining up objects with the __del__ method


rawDescription: Sort python list by individual letters of strings


code:
def bytes_to_key(data, salt="12345678"):
    # Simplified version of M2Crypto.m2.bytes_to_key(). Based on:
    # https://github.com/ajmirsky/M2Crypto/blob/master/M2Crypto/EVP.py#L105
    # http://stackoverflow.com/questions/8008253/c-sharp-version-of-openssl-evp-bytestokey-method
    assert len(salt) == 8, len(salt)
    data += salt
    key = md5(data).digest()
    key += md5(key + data).digest()
    return key

rawDescription: Using Python PyCrypto with Perl Crypt::CBC


code:
import vim
os.environ['DJANGO_SETTINGS_MODULE'] = \
    vim.eval("""expand("%:p:h")""").split('/')[4] + '.settings'

rawDescription: Passing vim functions to vim's inbuilt python


code:
first_value = random.randint(0, 10)
randarray = [i for i in random.sample(range(0, 10), 10) if i != first_value]
randarray.insert(0, first_value)

rawDescription: Generate a random array ignoring a selected value


rawDescription: Pandas sort list of str.split()

description: Pandas sort list of str.split()


code:
{{ form.first_name(class_='validate') }}
{{ form.first_name.label(class_='active') }}

{{ form.begins(class_='datepicker', length=50) }}

rawDescription: Using Flask-WTForms, how do I style my form section of the html?


code:
# lines of code to run at IPython startup.
# c.InteractiveShellApp.exec_lines = []

rawDescription: Configure ipython to automatically use certain settings like doctest_mode on


code:
with open('/path/to/myfile') as infile:
   with open('/path/to/output', 'w') as outfile:
      for line in infile:
         if line.rstrip().endswith('='):
             outfile.write('#' + line + '\n')
         else:
             outfile.write(line + '\n')

rawDescription: Comment some lines in a text file using python


code:
model = QFileSystemModel();
model.setRootPath(QDir.currentPath())
tree = QTreeView()
tree.setModel(model)
tree.setRootIndex(model.index(QDir.currentPath()))
tree.show()

rawDescription: Qt tree view with Pyside

description: Qt tree view with Pyside


code:
names_to_remove = set([r.rel.through._meta.object_name for r in m2m_links if not r.rel.through._meta.auto_created])
filtered_list = [r for r in o2m_links if r.rel.through._meta.object_name in names_to_remove]

rawDescription: Delete intersection between two lists

description: Delete intersection between two lists


code:
total = 123456789
percentages = [0.6, 0.3, 0.1]
values = np.random.multinomial(total, percentages)

rawDescription: numpy - Given a number, find numbers that sum to it, with fuzzy weights

description: Numpy - Given a number, find numbers that sum to it, with fuzzy weights


code:
@task
def do_job(path, task_id=None):
    cache.set(task_id, operation_results)

rawDescription: Celery - Get task id for current task

description: Celery - Get task id for current task


code:
def are_in_same_team(acc_pk1, acc_pk2):
    return Team.objects.filter(members__id=acc_pk1).filter(members__id=acc_pk2).exists()

rawDescription: Check if many to many child objects share a parent in Django


code:
class A(object):
    def __key(self):
        return (self.attr_a, self.attr_b, self.attr_c)

    def __eq__(x, y):
        return x.__key() == y.__key()

    def __hash__(self):
        return hash(self.__key())

rawDescription: Python: What's a correct and good way to implement __hash__()?


code:
invert_op = getattr(self, "invert_op", None)
if callable(invert_op):
    invert_op(self.path.parent_op)

rawDescription: What is the fastest way to check if a class has a function defined?


code:
p=argparse.ArgumentParser()
p.add_argument('p2',nargs=3,action='append')
ns,rest=p.parse_known_args('p21 p22 p23 p31 p32 p33'.split())
ns
rest
ns,rest=p.parse_known_args(rest,ns)  # repeat as needed
ns

rawDescription: Using python argparse on repeating groups


code:
from datetime import datetime, time
from time import sleep

def act(x):
    return x+10

def wait_start(runTime, action):
    startTime = time(*(map(int, runTime.split(':'))))
    while startTime > datetime.today().time(): # you can add here any additional variable to break loop if necessary
        sleep(1)# you can change 1 sec interval to any other
return action

wait_start('15:20', lambda: act(100))

rawDescription: delay a task until certain time

description: Delay a task until certain time


code:
from scipy.ndimage.filters import uniform_filter

def window_stdev(arr, radius):
    c1 = uniform_filter(arr, radius*2, mode='constant', origin=-radius)
    c2 = uniform_filter(arr*arr, radius*2, mode='constant', origin=-radius)
    return ((c2 - c1*c1)**.5)[:-radius*2+1,:-radius*2+1]

rawDescription: improving code efficiency: standard deviation on sliding windows

description: Improving code efficiency: standard deviation on sliding windows


code:
def to_json(self):
    return dict(
        author=[self.author.natural_key(), self.author.first_name, self.author.last_name],
        text=self.text,
    )

rawDescription: django - Natural key serialization of User

description: Django - Natural key serialization of User


code:
import sys
from PyQt4 import QtGui, QtCore

class QHighlightSquareWidget (QtGui.QWidget):
    def __init__ (self, parent = None):
        QtGui.QWidget.__init__(self, parent = None)
        self.setSizePolicy (
            QtGui.QSizePolicy (
                QtGui.QSizePolicy.Expanding,
                QtGui.QSizePolicy.Expanding))
        self.setMinimumSize(self.minimumSizeHint())
        allQGridLayout = QtGui.QGridLayout()
        allQGridLayout.addItem(QtGui.QSpacerItem(10,10), 0, 0)
        allQGridLayout.addItem(QtGui.QSpacerItem(10,10), 0, 1)
        allQGridLayout.addItem(QtGui.QSpacerItem(10,10), 1, 0)
        allQGridLayout.addItem(QtGui.QSpacerItem(10,10), 1, 1)
        self.setLayout(allQGridLayout)
        self.resize(150, 150)
        self.update()

    def paintEvent (self, eventQPaintEvent):
        myQPainter = QtGui.QPainter(self)
        myQPainter.setRenderHint(QtGui.QPainter.Antialiasing)
        winHeight = self.size().height()
        heightStep = winHeight / 2
        winWidth  = self.size().width()
        widthStep = winWidth / 2

        myQPainter.setPen(QtCore.Qt.black)
        for i in range(4):
            myQPainter.drawLine(QtCore.QPoint(i * widthStep, 0             ), QtCore.QPoint(i * widthStep, winHeight     ))
            myQPainter.drawLine(QtCore.QPoint(0,             heightStep * i), QtCore.QPoint(winWidth,      heightStep * i))

        highlightCoordinate = (1, 1)
        myQPen = QtGui.QPen(QtCore.Qt.blue, 3)
        myQPainter.setPen(myQPen)
        coordHighlight = [
            QtCore.QPoint( highlightCoordinate[0]      * widthStep,  highlightCoordinate[1]      * heightStep),
            QtCore.QPoint((highlightCoordinate[0] + 1) * widthStep,  highlightCoordinate[1]      * heightStep),
            QtCore.QPoint((highlightCoordinate[0] + 1) * widthStep, (highlightCoordinate[1] + 1) * heightStep),
            QtCore.QPoint( highlightCoordinate[0]      * widthStep, (highlightCoordinate[1] + 1) * heightStep),
            QtCore.QPoint( highlightCoordinate[0]      * widthStep,  highlightCoordinate[1]      * heightStep)]
        myQPainter.drawPolyline(*coordHighlight)

    def minimumSizeHint (self):
        return QtCore.QSize(120, 120)

if __name__=="__main__":
    myQApplication = QtGui.QApplication(sys.argv)
    myQHighlightSquareWidget = QHighlightSquareWidget()
    myQHighlightSquareWidget.show()
    sys.exit(myQApplication.exec_())

rawDescription: Painting on a widget that contains a QGridLayout in PySide/PyQt


code:
cur.execute("SELECT 'ALTER TABLE RENAME ' || tablename || ' TO ' || \
             REGEXP_REPLACE ( tablename, '_foo$', '_bar' ) || ';' \
             FROM pg_tables \
             WHERE tablename LIKE '%_foo'")

rawDescription: python - how to properly quote sql string

description: Python - how to properly quote sql string


code:
mac = '0024e865a023'
blocks = [mac[x:x+2] for x in xrange(0, len(mac), 2)]
macFormatted = '-'.join(blocks)

rawDescription: Convert Hexadecimal MAC address to user readable formating (Python)


code:
def my_facebook_api(input):
    if input=='A':
        return 'X'
    elif input=='B':
        return 'D'

facebook_api =  Mock(side_effect=my_facebook_api)

rawDescription: How to mock the output of one of my functions for unittests?

description: Mock the output of one of my functions for unittests


code: sortedfreqlist = sorted(freqlist, key=lambda item: int(item[1]), reverse=True)

rawDescription: Python sorting a file by frequency

description: Python sorting a file by frequency


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator

X = np.linspace(0, 50, 256, endpoint=True)

y1 = np.cos((np.pi*X)/25)
y2 = -np.cos((np.pi*X)/25)
y3 = np.sin((np.pi*X)/25)
y4 = -np.sin((np.pi*X)/25)

fig, [ax,bx] = plt.subplots(2,1)

a, = ax.plot(X, y1,color="green", linewidth=3.0, label="A")
b, = ax.plot(X, y2,color="cyan", linewidth=3.0, label="B")
c, = ax.plot(X, y3,color="blue", linewidth=3.0, label="C")
d, = ax.plot(X, y4,color="red", linewidth=3.0, label="D")

ax.set_xticks([0, np.pi*4, np.pi*8, np.pi*12, np.pi*16],
      [r'$0$', r'$4\pi$', r'$8\pi$', r'$12\pi$', r'$16\pi$'])

ax.set_yticks([-1, -0.5, 0, 0.5, +1],
      [r'$-1$', r'$-\frac{1}{2}$',  r'$0$', r'$\frac{1}{2}$', r'$+1$'])

ax.xaxis.set_minor_locator(MultipleLocator(np.pi))

ax.set_title('Set default color cycle to rgby')

e, = bx.plot(X, y1,color="magenta", linewidth=3.0, label="E")
f, = bx.plot(X, y2,color="black", linewidth=3.0, label="F")
g, = bx.plot(X, y3,color="cyan", linewidth=3.0, label="G")
h, = bx.plot(X, y4,color="yellow", linewidth=3.0, label="H")

bx.set_xticks([0, np.pi*4, np.pi*8, np.pi*12, np.pi*16],
      [r'$0$', r'$4\pi$', r'$8\pi$', r'$12\pi$', r'$16\pi$'])
bx.set_yticks([-1, -0.5, 0, 0.5, +1],
      [r'$-1$', r'$-\frac{1}{2}$',  r'$0$', r'$\frac{1}{2}$', r'$+1$'])

bx.xaxis.set_minor_locator(MultipleLocator(np.pi))
bx.set_title('Set axes color cycle to cmyk')
fig.subplots_adjust(hspace=0.4)
plt.figlegend((a,b,c,d,e,f,g,h), (r'$\cos(\frac{\pi x}{25})$',r'$-\cos(\frac{\pi x}{25})$', r'$\sin(\frac{\pi x}{25})$', r'$-\sin(\frac{\pi x}{25})$', r'$\cos(\frac{\pi x}{25})$' , r'$-\cos(\frac{\pi x}{25})$' , r'$\sin(\frac{\pi x}{25})$' , r'$-\sin(\frac{\pi x}{25})$'), loc=(0.8, 0.1))
fig.show()

rawDescription: One legend in python subplots

description: One legend in python subplots


code:
class Sparse3DMatrix():
  def __init__(self, default_value=False, max_x=100, max_y=100):
    self._dim = 3
    self._max_x = max_x
    self._max_y = max_y
    self._init_non_empty_z()
    self._default_value = default_value
    self._elements = {}
  def __getitem__(self, triplet):
    assert(len(triplet) == self._dim)
    return self._elements.get(triplet, self._default_value)
  def __setitem__(self, triplet, value):
    assert(len(triplet) == self._dim)
    if value == self._default_value:
      if triplet in self._elements:
        self._delete_element(triplet)
    else:
      if triplet not in self._elements:
        self._add_element(triplet, value)
      else:
        self._elements[triplet] = value
  def _init_non_empty_z(self):
    self.non_empty_z = {}
    for i in range(self._max_x):
      for j in range(self._max_y):
        self.non_empty_z[i, j] = []
  def _delete_element(self, triplet):
    """ Deletes an element. Element is assumed to exist. """
    del self._elements[triplet]
    self.non_empty_z[triplet[0], triplet[1]].remove(triplet[2])
  def _add_element(self, triplet, value):
    """ Adds an element. triplet is assumed to be default value before call. """
    self._elements[triplet] = value
    self.non_empty_z[triplet[0], triplet[1]].append(triplet[2])
  def delete_by_axis(self, index, axis):
    """ Slow deletion of entire row / column / depth """
    old_triplets = self._elements.copy().items()
    self._elements = {}
    self._init_non_empty_z()
    for triplet, value in old_triplets:
      if triplet[axis] < index:
        self._add_element(triplet, value)
      elif triplet[axis] > index:
        new_triplet = list(triplet)
        new_triplet[axis] -= 1
        self._add_element(tuple(new_triplet), value)
  def all_non_default_value(self):
    return list(self._elements.keys())

rawDescription: Sparse 3D matrix in python just for insertion/deletion of elemets, deletion of rows, and fast access to non empty z dimension


code:
import threading

def print_hello():
    print('Hello')
    timer = threading.Timer(2, print_hello) # # Call `print_hello` in 2 seconds.
    timer.start()

print_hello()

rawDescription: How to call a particular method in a background thread every X minutes in Python?

description: Call a particular method in a background thread every X minutes in Python


code:
itemBank = []
for row in rows:
    itemBank.append((
        tempRow2['Item_Name'],
        tempRow1['Item_Price'],
        tempRow3['Item_In_Stock'],
        tempRow4['Item_Max'],
        getTimeExtra
        )) #append data

q = """ insert ignore into TABLE1 (
        Item_Name, Item_Price, Item_In_Stock, Item_Max, Observation_Date )
        values (%s,%s,%s,%s,%s)
    """

try:
    x.executemany(q, itemBank)
    conn.commit()
except:
    conn.rollback()

rawDescription: How can I use executemany to instert into mysql a list of dictionaries in python

description: Use executemany to instert into mysql a list of dictionaries in python


code:
L=[]
itr=cursor.execute("SELECT name, COUNT(name) FROM class_1 GROUP BY name").fetchall()
for x in itr:
    L.append(x[2])

rawDescription: add cursor.fetchall data into list python sql

description: Add cursor.fetchall data into list python sql


code: server.sendmail(email_from, email_to_list + email_cc_list, msg.as_string())

rawDescription: Python email - can only sendmail to one address


code:
import csv
with open('141881.csv') as file_handle:
    file_reader = csv.reader(file_handle)
    for row in file_reader:
        print(row)

rawDescription: Mapping CSV data into Python

description: Mapping CSV data into Python


code:
import sys, os, string
from PyQt4.QtCore import *
from PyQt4.QtGui import *

# move wordcount function into the class

class Form( QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle("Word Count GUI")
        # use placeholder text
        self.lineedit2 = QLineEdit()
        self.lineedit2.setPlaceholderText('Enter Filename Here')
        self.pbutton2 = QPushButton('Press to Load File')
        # use placeholder text
        self.lineedit1 = QLineEdit()
        self.lineedit1.setPlaceholderText("Enter Word Here")
        self.pbutton1 = QPushButton("Press for Count")
        self.pbuttonQuit = QPushButton("Exit")
        # don't forget the layout...
        layout = QVBoxLayout()
        layout.addWidget(self.lineedit2)
        layout.addWidget(self.pbutton2)
        layout.addWidget(self.lineedit1)
        layout.addWidget(self.pbutton1)
        layout.addWidget(self.pbuttonQuit)
        self.setLayout(layout)
        self.pbutton2.setFocus()
        # use new-style connections
        self.pbutton1.clicked.connect(self.button1Pressed)
        self.pbutton2.clicked.connect(self.button2Pressed)
        # connect to self.close to quit
        self.pbuttonQuit.clicked.connect(self.close)
        # keep a list of lines
        self.lines = []

    def wordcount(self, word):
        total = 0
        # iterate over stored lines
        for line in self.lines:
            line = line.translate(None, string.punctuation)
            line = line.lower()
            words = line.split()
            if word in words:
                total += 1
        return total

    def button1Pressed(self):
        x1 = self.lineedit1.text()
        x1 = str(x1).lower()
        # use the wordcount method
        x2 = self.wordcount(x1)
        outtext =  str(x1) + " appears " + str(x2) + " times in the file."
        self.lineedit1.setText(outtext)

    def button2Pressed(self):
        # this reads the file and stores the lines
        g = str(self.lineedit2.text())
        g = os.path.join('/Users/xxx/Documents/Python', g)
        try:
            with open(g) as stream:
                self.lines = stream.readlines()
        except EnvironmentError as exception:
            print('ERROR: could not read file:')
            print('  : %s' % exception)
            self.lines = []

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

rawDescription: Typing in File Path in GUI and Using it to Run a Program Within Same GUI


code:
tablist = []
tablabellist = []
layoutlist=[]
self.tablelist = []
Tab = QtGui.QTabWidget()
headerlist = [ 'ID','Question','Answer 1','Answer 2','Answer 3','Difficulty','Statistics','Date Added','Added By','Date Modified']

num_tab_widgets = 10

for i in range(num_tab_widgets):
    tablist.append(QtGui.QWidget())
    Tab.addTab(tablist[i], QtCore.QString('SECTION %s'%chr(ord('A')+i)))
    tablabellist.append(QtGui.QLabel('title'))
    self.tablelist.append(QtGui.QTableWidget())
    setattr(self,'Table%d'%i,self.tablelist[i])
    layoutlist.append(QtGui.QVBoxLayout())

    self.tablelist[i].setColumnCount(len(headerlist))
    self.tablelist[i].setHorizontalHeaderLabels(headerlist)
    self.tablelist[i].setEditTriggers(QtGui.QTableWidget.NoEditTriggers)
    self.tablelist[i].setSelectionBehavior(QtGui.QTableWidget.SelectRows)
    self.tablelist[i].setSelectionMode(QtGui.QTableWidget.SingleSelection)

    layoutlist[i].addWidget(tablabellist[i])
    layoutlist[i].addWidget(self.tablelist[i])
    tablist[i].setLayout(layoutlist[i])

CLayout = QtGui.QVBoxLayout()
CLayout.addWidget(Tab)

Cwidget = QtGui.QWidget()
Cwidget.setLayout(CLayout)
self.setCentralWidget(Cwidget)

rawDescription: PyQt multiple tablewidgets and tabwidgets


code:
re.findall(r'Food: ([^|]*)', 'Food: is great|foo')
re.findall(r'Food: ([^|]*)', 'Food: is great')

rawDescription: Python regex for string up to character or end of line


code:
with open(r'd:\file.csv','rb') as f:
    reader = csv.DictReader(f,dialect='excel-tab')
    rows = list(reader)
[x['User ID'] for x in rows if x['Application'] == 'Central']

rawDescription: How to easily filter from csv with python?

description: Easily filter from csv with python


code:
import pstats
p = pstats.Stats('thing.txt')
p.sort_stats('cumulative').print_stats(10)

rawDescription: cProfile saving data to file causes jumbles of characters

description: CProfile saving data to file causes jumbles of characters


code:
class hostCreateForm(forms.ModelForm):
    class Meta:
        model = filled
        widgets = {
            'user': forms.HiddenInput()
        }
    # additional hidden field
    datetime = forms.DatetimeField(widget=forms.HiddenInput)

rawDescription: How to save Django "forms.ModelForm" in database after editing it content and passing a  javascript variable to it's new entered field

description: Save Django "forms.ModelForm" in database after editing it content and passing a  javascript variable to it's new entered field


code:
compile('foo', 'bar', 'exec')
exec(compile('foo', 'bar', 'exec'))

rawDescription: Significance of first two args for compile() python3


code:
funcs = {
    'CONNECT': connect,
    'RAWFEED': rawfeed,
    'RAWCONFIG' : rawconfig,
    'TESTFEED': testfeed
}
funcs[status](*args, **kwargs)

rawDescription: Python dynamic function names

description: Python dynamic function names


code:
from ast import literal_eval
literal_eval('[1,2,3]')
literal_eval("['1','2','3']")

rawDescription: Get List from a String Python

description: Get List from a String Python


code:
def OnKeyDown(self, event):
    now = time.time()
    keyCode = event.GetKeyCode()
    if (keyCode >= 65 and keyCode <= 90) or ( keyCode >= 48 and keyCode <= 57):
        if self.searchString == "":
            self.searchString = chr(event.GetKeyCode())
        elif (now - self.lastKeyDown) < 2:
            self.searchString += str(chr(event.GetKeyCode()))
        else:
            self.searchString = str(chr(event.GetKeyCode()))
    else:
        event.Skip()
        return
    self.lastKeyDown = now
    self.GetItem(self.searchString, self.GetRootItem())

rawDescription: Override KeyDown Event in wxPython

description: Override KeyDown Event in wxPython


code:
from datetime import datetime
tm_yday = 59
tm_year = datetime.now().year # current year
datetime.strptime('{} {}'.format(tm_year, tm_yday), '%Y %j')

rawDescription: How do I construct a Python time struct from the day of year?

description: Construct a Python time struct from the day of year


code:
def removeButtons(self):
    for cnt in reversed(range(self.dvbox.count())):
        # takeAt does both the jobs of itemAt and removeWidget
        # namely it removes an item and returns it
        widget = self.dvbox.takeAt(cnt).widget()

        if widget is not None:
            # widget will be None if the item is a layout
            widget.deleteLater()

rawDescription: What is best way to remove items from layout in pyqt


code:
import csv
with open("data.csv", "wb") as f:
    csv.writer(f).writerows((k,) + v for k, v in maxDict.iteritems())

rawDescription: Python: How to write a dictionary of tuple values to a csv file?


code:
from itertools import izip
[' '.join(pair) for pair in izip(words[:-1], words[1:])]

rawDescription: Split string words in pairs for all side by side words


code:
def __init__(self):
    global engine
    global central_db
    engine = engine_from_config(config, 'sqlalchemy.central.')
    central_db = create_engine(engine)

rawDescription: Only connect to database when necessary

description: Only connect to database when necessary


rawDescription: The Tkinter Menu Widget

description: The Tkinter Menu Widget


code:
class TransactionalMiddlewareInterface(object):
    def __init__(self, application, **config):
        self.application = application
        self.config = config

    def __call__(self, environ, start_response):
        def local_start(stat_str, headers=[]):
            local_start.status = int(stat_str.split(' ')[0])
            return start_response(stat_str, headers)
        try:
            result = self.application(environ, local_start)
        finally:
            if local_start.status and local_start.status > 199:
                pass

rawDescription: What is the appropriate way to intercept WSGI start_response?


code:
class DB(object):
    def __init__(self):
        self._register_event()

    def _get_created_by(self):
        return datetime.datetime.now()

    def _register_event(self):
        @event.listens_for(Item, 'load')
        def receive_load(target, context):
            target.created_by = self._get_created_by()

    def test_select(self):
        items = session.query(Item).all()
        for item in items:
            print(item)

db = DB()
db.test_select()

rawDescription: SQLAlchemy: how to pass extra parameters when instantiating new object


code:
def subset_sum(lst, n):
    for i in range(len(lst)):
        for j in range(i + 1, len(lst)):
            for k in range(j + 1, len(lst)):
                if lst[i] + lst[j] + lst[k] == n:
                    return True
    return False

rawDescription: Python subsetSum Function

description: Python subsetSum Function


code:
import os
import csv
from itertools import groupby

readpath = 'path-to-read-file'
writepath = 'path-to-write-file'

for filename in os.listdir(readpath):
    with open(os.path.join(readpath, filename)) as fin:
        tabin = csv.reader(fin, delimiter='\t')
        for file_id, rows in groupby(tabin, lambda L: L[1]):
            with open(os.path.join(writepath, file_id + '-' + filename), 'w') as fout:
                tabout = csv.writer(fout, delimiter='\t')
                tabout.writerows(rows)

rawDescription: How to split text file by id in python

description: Split text file by id in python


code:
tree = QTreeWidget()

def delItem(e):
    if e.reason() == QContextMenuEvent.Mouse:
        itemClicked = tree.itemAt(e.pos())
        for topItem in range(0,tree.topLevelItemCount()):
            topItem = tree.topLevelItem(topItem)
            if topItem.isSelected():
                tree.takeTopLevelItem(tree.indexOfTopLevelItem(topItem))
            else:
                def checkChildren(item):
                    if item.childCount() >= 0:
                        for childItem in range(0,item.childCount()):
                            childItem = item.child(childItem)
                            if childItem.isSelected():
                                item.removeChild(childItem)
                            else:
                                childItem.checkChildren()
                checkChildren(topItem)

tree.contextMenuEvent = delItem

rawDescription: Deleting a non-toplevel item from a QTreeWidget


code:
opener = urllib.request.build_opener(
    urllib.request.ProxyHandler({'http': r'http://username:password@url:port'}),
    urllib.request.HTTPRedirectHandler(),
    urllib.request.HTTPHandler(debuglevel=0),
    urllib.request.HTTPSHandler(debuglevel=0),
    urllib.request.HTTPCookieProcessor(cookies)
)

rawDescription: Unable to login to a website using python script as I am behind a proxy which needs authentication


code:
kontenier = db.GqlQuery('SELECT * FROM oceni')
kolekcija = {}
for it in kontenier:
    if it.user not in kolekcija:
        kolekcija[it.user] = {}
    kolekcija[it.user][it.item] = it.weight

rawDescription: How to create a nested dictionary from a datastore model?

description: Create a nested dictionary from a datastore model


code:
response = HttpResponse(mimetype="image/png")
img.save(response, "PNG")
return response

rawDescription: Serve a dynamically generated image with Django


code:
from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import Listing
...
@receiver(pre_save, sender=Listing)
def check_image_requirement(sender, instance, **kwargs):
    if instance.images.count() == 0:
        raise your_own_exception("Listing is required to have at least one image")

rawDescription: Django models - at least one in many to many


code:
def cleanMe(html):
    soup = BeautifulSoup(html) # create a new bs4 object from the html data loaded
    for script in soup(["script", "style"]): # remove all javascript and stylesheet code
        script.extract()
    # get text
    text = soup.get_text()
    # break into lines and remove leading and trailing space on each
    lines = (line.strip() for line in text.splitlines())
    # break multi-headlines into a line each
    chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
    # drop blank lines
    text = '\n'.join(chunk for chunk in chunks if chunk)
    return text

rawDescription: How do I completely remove all style, scripts, and html tags from an html page

description: Completely remove all style, scripts, and html tags from an html page


code:
process = subprocess.Popen([SPIM_BIN] + extra_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
pin = process.stdin
pout = process.stdout

rawDescription: Python subprocess, give an input to a child process


code:
def unique(*args):
    result = set()  # A set guarantees the uniqueness of elements
    result = result.union(*args)  # Include elements from all args
    result = list(result)  # Convert the set object to a list
    return result

rawDescription: Unique Function Iterator for Scheme and Python


rawDescription: scipy -- how to extract randomly an array from a list

description: Scipy -- how to extract randomly an array from a list


code:
import re
line = "characterstextToSaveotherCharacters"
regex = re.compile(r'characters(textToSave)otherCharacters')
matchObj = regex.search(line)
if matchObj:
    print(matchObj.group(1)) # Now, matchObj.group(1) contains textToSave

rawDescription: How to memorize a portion of string when it match a regex?

description: Memorize a portion of string when it match a regex


code:
from selenium import webdriver
from PIL import Image
import StringIO
import numpy as np

browser = webdriver.Firefox()
browser.get('https://www.google.ca/?gws_rd=ssl')

data = browser.get_screenshot_as_png()

img = Image.open(StringIO.StringIO(data))

numpy_array = np.asarray(img)

rawDescription: Selenium Webdriver, screenshot as numpy array (Python)


code:
a = np.zeros((1000,784))
b = np.zeros((8000,784))
c = np.concatenate((a,b))
c.shape

rawDescription: Joining two 2D-arrays in numpy

description: Joining two 2D-arrays in numpy


rawDescription: Django generates 'WHERE ... BETWEEN ...' sentences?


code:
# sel_att holds the user selected attributes.

result = Person.objects.all()

for att in sel_att:
    result = result.filter(
        attributes__attribute_name=att.attribute_name,
        attributes__attribute_type=att.attribute_type
    )

rawDescription: Appending filters to django models

description: Appending filters to django models


code:
from django.views.decorators.cache import never_cache

@never_cache
def myview(request):
    ...

rawDescription: @login_required decorator doesnot work while hitting the back button on browser


rawDescription: Django send_mail fails in 1.7 Says no django_smtp_ssl


rawDescription: How can I select series in a pandas dataframe where every element in the series meets a criterion?

description: Select series in a pandas dataframe where every element in the series meets a criterion


code:
handle = subprocess.Popen(["ssh", login + "@localhost", "-o StrictHostKeyChecking=no", "passwd --stdin"])
handle.communicate("\n".join([oldpass, newpass, newpass, ""]))

rawDescription: Python select() not waiting for terminal input after forkpty()


code:
def new_cycle( seq, last=None):
    if last is None:
        return cycle(seq)
    else:
        it = cycle(seq)
        while next(it) != last:
            pass
        return it

rawDescription: Pythonic way of copying an iterable object


code:
import socket

server = "www.google.com"
server = socket.gethostbyname(server)
port = 80
request = "GET / HTTP/1.1\nHost: " + server + "\n\n"

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((server, port))
sock.send(request.encode())

response = sock.recv(4096).decode("utf-8")
print(response)

test = response.index("\r\n\r")

print(test)

rawDescription: Python get index of empty live

description: Python get index of empty live


code:
get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
import keyword
get_close_matches('wheel', keyword.kwlist)
get_close_matches('apple', keyword.kwlist)
get_close_matches('accept', keyword.kwlist)

rawDescription: What is a good strategy to group similar words?


code:
import os
hit = pygame.mixer.Sound(os.path.join(os.path.dirname(__file__), "hit.wav"))

rawDescription: Why does the terminal search the working directory for files that an executing file is searching for?


code: cur_syslog.execute("SELECT data FROM firewall WHERE source_ip = %s", (ip))

rawDescription: Select from MySql with a variable

description: Select from MySql with a variable


code:
import itertools as it

a = [[1, 2], [4, 5, 6], [], [7, 12, 14, 16]]
reversed(it.islice(it.chain.from_iterable(reversed(a)), 5))

rawDescription: python get last 5 elements in list of lists

description: Python get last 5 elements in list of lists