code:
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4, cm
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph, Table, TableStyle
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER
from reportlab.lib import colors

width, height = A4
styles = getSampleStyleSheet()
styleN = styles["BodyText"]
styleN.alignment = TA_LEFT
styleBH = styles["Normal"]
styleBH.alignment = TA_CENTER

def coord(x, y, unit=1):
    x, y = x * unit, height -  y * unit
    return x, y

# Headers
hdescrpcion = Paragraph('''descrpcion''', styleBH)
hpartida = Paragraph('''partida''', styleBH)
hcandidad = Paragraph('''candidad''', styleBH)
hprecio_unitario = Paragraph('''precio_unitario''', styleBH)
hprecio_total = Paragraph('''precio_total''', styleBH)

# Texts
descrpcion = Paragraph('long paragraph', styleN)
partida = Paragraph('1', styleN)
candidad = Paragraph('120', styleN)
precio_unitario = Paragraph('$52.00', styleN)
precio_total = Paragraph('$6240.00', styleN)

data= [[hdescrpcion, hcandidad,hcandidad, hprecio_unitario, hprecio_total],
       [partida, candidad, descrpcion, precio_unitario, precio_total]]

table = Table(data, colWidths=[2.05 * cm, 2.7 * cm, 5 * cm,
                               3* cm, 3 * cm])

table.setStyle(TableStyle([
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                       ('BOX', (0,0), (-1,-1), 0.25, colors.black),
                       ]))

c = canvas.Canvas("a.pdf", pagesize=A4)
table.wrapOn(c, width, height)
table.drawOn(c, *coord(1.8, 9.6, cm))
c.save()

rawDescription: Wrap text in a table reportlab?

description: Wrap text in a table reportlab


code:
surf_rect = surf.get_rect()
# move the surface 20 units to the right, and 15 units down
surf_rect.x += 20
surf_rect.y += 15
# now draw this surface to the screen based on the surf_rect's position
screen.blit(surf, (surf_rect.x, surf_rect.y))

rawDescription: Pygame How to get the left,top,width, and height of an image


code:
def f():
    print ('This line will not be executed during import from another file')

print ('This line is executed!')

if __name__ == '__main__':
    print ('This line is executed only, if the program is main program, but not during import from another program.')

rawDescription: Does a .py get executed when being imported [python3]


code:
def get_item_by_label(self, tree, search_text, root_item):
    item, cookie = tree.GetFirstChild(root_item)

    while item.IsOk():
        text = tree.GetItemText(item)
        if text.lower() == search_text.lower():
            return item
        if tree.ItemHasChildren(item):
            match = self.get_item_by_label(tree, search_text, item)
            if match.IsOk():
                return match
        item, cookie = tree.GetNextChild(root_item, cookie)

    return wx.TreeItemId()

result = get_item_by_label(tree, 'MyStories', tree.GetRootItem())
if result.IsOk():
    print('We have a match!')

rawDescription: wxPython: TreeCtrl: How can I get a tree item by name?

description: WxPython: TreeCtrl: How can I get a tree item by name


rawDescription: Python re.split() misbehaving

description: Python re.split() misbehaving


code:
var_1 = "hello"
[var_1]

rawDescription: How to convert a str to a single element list in python

description: Convert a str to a single element list in python


code:
from Tkinter import *
import ttk
import time
import threading

def start():
    start_stop.config(text="QUIT", command=stop)
    thread = threading.Thread(target=progBar, args=())
    thread.daemon = True
    thread.start()

def progBar():
    for i in xrange(5):
        pbar_det.step(19.99)
        master.update()
        # Busy-wait
        time.sleep(1)
    master.quit()

def stop():
    master.quit()

master = Tk()

start_stop = Button(master, text='START', command=start)
start_stop.grid(row=0, column=1, pady=2, padx=2, sticky=E+W+N+S)

pbar_det = ttk.Progressbar(master, orient="horizontal", length=600, mode="determinate")
pbar_det.grid(row=0, column=0, pady=2, padx=2, sticky=E+W+N+S)

master.mainloop()

rawDescription: How to close the program by pressing button?

description: Close the program by pressing button


code:
pointer = my_dll.get_str()
some_str = ctypes.string_at(pointer)
# This is windows specific -
# on Posix, one have to load "libc.so" and use "free" from there:
ctypes.cdll.msvcrt.free(pointer)

rawDescription: Python ctypes.string_at freeing behavior


code:
alarm_time = time.strptime('23:46:00', '%H:%M:%S')
today = time.localtime()
time.struct_time(today[:3] + alarm_time[3:])

rawDescription: Set day, month and year of a python time_struct without changing the time


code:
def twitterdisplayer():
    all_tweets_text = []
    for tweet in public_tweets:
        all_tweets_text.append(tweet.text)
    return all_tweets_text

rawDescription: Flask with Tweepy only pulls the first tweet, need some more tweets


code: hash(tup)

rawDescription: What is the best integer n-tuple hash in python?


code:
class EventAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'device')
    def queryset(self, request):
        return super(EventAdmin, self).queryset(request).select_related('device')

rawDescription: Why does Django admin list_select_related not work in this case?


code: getattr(apps, variable).main.run()

rawDescription: Dyanamic/ Variable Filepath Python

description: Dyanamic/ Variable Filepath Python


code:
actions = [
  ('ROAMING'  , lambda service,nr_called,cost: service=='R'),
  ('ONNET'    , lambda service,nr_called,cost: service in ('V  O','S') and float(cost)==0.0),
  ('INTERNET' , lambda service,nr_called,cost: service=='' and nr_called==''),
  ('OTHERSERV', lambda service,nr_called,cost: service in ('I','ROAMING - MMS'))

  # fallthrough
  ('OTHERSERV', lambda service_nr_called,cost: True)
]

for value,check in actions:
  if check(service,nr_called,cost):
    return value

# fallthrough
return 'OTHERSERV'

rawDescription: Python code optimization with regexes

description: Python code optimization with regexes


code:
object = Emp.objects.get(pk=profile.id)
object.save(force_insert=True)

rawDescription: Copying contents of a model

description: Copying contents of a model


code:
dizGroup = {}

for obj in mc.ls(type='transform'):
    if mc.objExists(obj + ('.matteGroup')):
        matteGroup = mc.getAttr(obj + ('.matteGroup'))
        matteName = mc.getAttr(obj + ('.matteName'))

        if matteGroup not in dizGroup:
            dizGroup[matteGroup] = {}

        if matteName not in dizGroup[matteGroup]:
            dizGroup[matteGroup][matteName] = []

        dizGroup[matteGroup][matteName].append(obj)

rawDescription: How to make a nested dictionary and dynamically append data

description: Make a nested dictionary and dynamically append data


code:
values = ['1', '2', '3']

with open("file.txt", "w") as output:
    output.write(str(values))

rawDescription: Save a list to a .txt file

description: Save a list to a .txt file


code:
import pandas as pd
df = pd.DataFrame({"Field": "Field1 Field4 Field2 Field5 Field2".split()})
approved_fields = "Field1", "Field2", "Field3"
df['Field'].isin(approved_fields)
df[df['Field'].isin(approved_fields)]

rawDescription: Filter Pandas dataframe with another series


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.TAG_NAME, "img"))
)

list_of_elements = self.driver.find_elements_by_css_selector('img[title]')
# ...

rawDescription: Python 2.7 Selenium - How to get all elements on a webpage?


code:
#/user/bin/env python
import sys
file_object = open(sys.argv[1])
for some_line in file_object:
   if some_line.startswith('>'):
          sys.stdout.write(some_line.strip('\n') + '\t')
   else:
          sys.stdout.write(some_line)

rawDescription: Need help to make my python script work

description: Need help to make my python script work


code:
#:Loads the qico plug-in lets you use .ico icons
QPlugin = QPluginLoader("qico4.dll")

rawDescription: How to include icons in application when using Pyinstaller 2.0 ,PySide 1.1.2 Bindings and Qt 4.8

description: Include icons in application when using Pyinstaller 2.0 ,PySide 1.1.2 Bindings and Qt 4.8


code:
#bitmasks of fields 1-3, they fit in 2 bytes
FIELD1 = 0b1111000000000000 # first 4 bits
FIELD2 = 0b0000111000000000 # next 3 bits
FIELD3 = 0b0000000111111111 # last 9 bits

def bytes_to_int(num):  #convert bytes object to an int
    res = 0
    num = num[::-1]  # reverse the bytes
    for i in range(len(num)):
        res += num[i] * (256**i)
    return res

def get_fields(f):
    chunk = bytes_to_int(f.read(2))  # read 2 bytes, f1-f3, convert to int
    f1 = (chunk & FIELD1) >> 12  # get each field with its bitmask
    f2 = (chunk & FIELD2) >> 9
    f3 = chunk & FIELD3
    f4 = f.read(f3)  # field4 as a bytes object
    f4 = bytes_to_int(f4)  #comment this line if you want field4 as a bytes obj

    return f1, f2, f3, f4

file = open('file.dat','rb')

#using your sample data
print(get_fields(file))  # returns 0, 4, 384, field4 as an int

file.close()

rawDescription: Fastest way to unpack bits (sub-byte) numbers from file


code:
import pygame
import sys

pygame.init()
font = pygame.font.SysFont("monospace", 15)
screen = pygame.display.set_mode((400,100))

cur_x, cur_y = 0,0

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit(0)
        elif event.type == pygame.MOUSEMOTION:
            cur_x, cur_y = event.pos

    screen.fill((0,0,0))
    coord_message = "position: x={}, y={}:".format(cur_x, cur_y)
    coord_label = font.render(coord_message, 1, (255,0,0))
    screen.blit(coord_label, (50, 10))
    pygame.display.flip()

rawDescription: Displaying Current Position For Paint Program in Python


code:
import datetime
sensor_delay = 5 #delay in seconds
last_event = datetime.datetime.now()

def shock():
    global last_event
    if datetime.datetime.now() > last_event + datetime.timedelta(seconds=sensor_delay):
        print ('shock')
        last_event = datetime.datetime.now()

def knock():
    global last_event
    if datetime.datetime.now() > last_event + datetime.timedelta(seconds=sensor_delay):
        print('knock')
        last_event = datetime.datetime.now()

rawDescription: How do I pause a script in python to keep 2 sensors from being detected at same time?

description: Pause a script in python to keep 2 sensors from being detected at same time


rawDescription: Python Matplotlib - Show Tick Marks associated to Plotted Points


code:
filters = (_filter1, _filter2, _filter3)
list_after = filter(lambda x: all(f(x) for f in filters), your_list)

rawDescription: Applying a list of functions to a single variable


code:
estimator = RandomForestRegressor(oob_score=True,n_estimators=10,max_features='auto')
estimator.fit(tarning_data,traning_target)
tree1 = estimator.estimators_[0]
leftChilds = tree1.tree_.children_left # array of left children
rightChilds = tree1.tree_.children_right #array of right children

rawDescription: Access the underlying (tree_) object of a single tree in a Random-Forest model (Python, scikit-learn)


rawDescription: Can Regex be used for this particular string manipulation?


code:
class Test:
    def __init__(self, name, parent):
        self.name = name
        self.parent = parent
    def __repr__(self):
        return "Test('"+self.name+"', '"+self.parent+"')"

li = [Test('a', ''), Test('b', ''), Test('c', 'a'), Test('d', 'a'), Test('e', 'c')]

dict = {"":(None,[])} #name to (node,children)
#add nodes
for item in li:
    dict[item.name] = (item, [])
#add children
for item in li:
    dict[item.parent][1].append(dict[item.name])

def printTree(dict, name, indent):
    newIndent=indent
    if name!="":
        print(indent + str(dict[name][0]))
        if indent == "": newIndent="  |-- "
        else: newIndent = "      "+indent
    for child in dict[name][1]:
        printTree(dict, child[0].name, newIndent)

printTree(dict, "", "")

rawDescription: Nested list to string

description: Nested list to string


code:
WEEKDAYS = [
  (1, _("Monday")),
  (2, _("Tuesday")),
  (3, _("Wednesday")),
  (4, _("Thursday")),
  (5, _("Friday")),
  (6, _("Saturday")),
  (7, _("Sunday")),
]

class OpeningHours(models.Model):

    weekday = models.IntegerField(choices=WEEKDAYS)
    from_hour = models.TimeField()
    to_hour = models.TimeField()

    class Meta:
        ordering = ('weekday', 'from_hour')
        unique_together = ('weekday', 'from_hour', 'to_hour')

    def __unicode__(self):
        return u'%s: %s - %s' % (self.get_weekday_display(),
                                 self.from_hour, self.to_hour)

rawDescription: Business Opening hours in Django

description: Business Opening hours in Django


rawDescription: Python ctypes: How do I flush output from stderr?


code:
from collections import defaultdict
d = defaultdict(list)
with open("/Volumes/City_University/data_mining/Ecoli.txt") as f:
    for line in f:
        key, val = line.split()
        d[key].append(val)
for k, v in d.items():
    print(k, v)

rawDescription: How to import a text file as a dictionary python

description: Import a text file as a dictionary python


code:
"""
High quality uniform random variable on [0, 1].

Simulates round(X) where X is a real random variable uniformly distributed on
the interval [0, 1] and round is the usual round-to-nearest rounding function
from real numbers to floating-point.

"""
from __future__ import division
import random

precision = 53
emin = -1021

def random_significand():
    return (random.getrandbits(precision) + 1) // 2 / (2**precision)

def uniform():
    for i in xrange(1 - emin):
        if random.getrandbits(1):
            return (random_significand() + 0.5) / 2**i
    # Subnormal
    return random_significand() / 2**i

rawDescription: Assembling floating point numbers for Random.random() in Python


code:
def runproc(queue):
    plist = []
    while True:
        try: cmdline = queue.get_nowait()
        except Empty: pass
        else: plist.append(Proc(cmdline))

        for p in plist:
            if not p.isRunning():
               p.run()
        time.sleep(1)

queue = Queue()
t = Thread(target=runproc, args=(queue,))
t.daemon = True
t.start()

queue.put(cmdline)
# ...

rawDescription: Returning to Thread method after calling differnet method


code:
import random

class person():
    def __init__(self):
        self.height = 3.0
        self.weight = 240.0
        self.temp = 99.23

        self.attrlist = ['height', 'weight', 'temp']

    def grow(self):
        rand_attr = random.choice(self.attrlist)
        attr_value = getattr(self, rand_attr)
        setattr(self, rand_attr, attr_value + 26.0)

rawDescription: Randomly select class attribute in Python


code:
class GetStatsSpider(CrawlSpider):
    name = 'GetStats'
    allowed_domains = ['tennisinsight.com']
    start_urls = ['http://www.tennisinsight.com/player_activity.php?player_id=1']

    def getPopLink(value):
        m = re.search("javascript:makePopup\('(.+?)'\)", value)
        if m:
            return m.group(1)

    rules = (
            Rule(SgmlLinkExtractor(allow=r"match_stats_popup.php\?matchID=\d+",
                restrict_xpaths='//td[@class="matchStyle"]',
                tags='a', attrs='href', process_value=getPopLink), callback='parse_item', follow=True),
            )

    def parse_item(self, response):
        sel = Selector(response)
        i = TennisItem()
        i['url_stats'] = response.url
        return i

rawDescription: Scrapy: Modify rules for scraping web page


code:
#Also include Regular Expression module, re
import os,sys,re

#Set root to the folder you want to check
folder = "%PATH_TO_YOUR_FOLDER%"

#Walk through the folder checking all files
for root, dirs, filenames in os.walk(folder):
    #For each file in the folder
    for filename in filenames:
        #Create blank strink for servername
        servername = ''
        #Get the full path to the file
        fullpath=os.path.join(root,filename)
        #Open the file as read only in tempfile
        with open (fullpath, "r") as tempfile:
            #Iterate through the lines in the file
            for line in tempfile.readlines():
                #Check if this line contains "Server: XXXXX"
                serverline= re.findall("Server: [a-zA-Z0-9]+", line)
                #If the line was found
                if serverline:
                    #Split the line around ": " and take second part as server name
                    sname = serverline[0].split(": ")
                    #Set servername variable so isn't lost outside scope of with block
                    servername = sname[1]
        #If a servername was found for that text file
        if len(servername) > 0:
            #Rename the file
            os.rename(fullpath,root+'\\'+servername+filename)

rawDescription: Rename a file in Python

description: Rename a file in Python


code:
#!/usr/bin/python
from gi.repository import Gtk, Gdk, GLib

class MyWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="ST")

        self.MAXSPEED = 3000

        self.set_default_size(100,100)
        self.set_resizable(False)

        self.entry = Gtk.Entry()
        self.entry.set_text("0")

        start = Gtk.Button(label="Start")
        start.connect("clicked", self.clicked_start)
        stop = Gtk.Button(label="Stop")
        stop.connect("clicked", self.clicked_stop)
        inc = Gtk.Button(label="inc")
        inc.connect("button-press-event", self.pressed_inc)
        inc.connect("button-release-event", self.left_inc)

        fixed  = Gtk.Fixed()

        fixed.put(start,      0,   0)
        fixed.put(self.entry, 0,   40)
        fixed.put(stop,       0,   70)
        fixed.put(inc,        120, 0)

        self.add(fixed)

    def clicked_start(self, widget):
        self.set_title("GO")

    def clicked_stop(self, widget):
        self.set_title("ST")

    def pressed_inc(self, widget, event):
        self.inc_id = GLib.timeout_add(100, self.increase)

    def left_inc(self, widget, event,):
        GLib.source_remove(self.inc_id)

    def increase(self):
        speed = int(self.entry.get_text()) + 1
        if speed > self.MAXSPEED:
            self.entry.set_text(str(self.MAXSPEED))
        else:
            self.entry.set_text(str(speed))
        return True

win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

rawDescription: Action during button pressed in Python

description: Action during button pressed in Python


code:
def save(self, *args, **kwargs):
    if not self.field1:
        self.field2 = ...
    if not self.field2:
        self.field1 = ...
    super(A,self).save(*args,**kwargs)

rawDescription: How to unite together 2 model fields in Django?

description: Unite together 2 model fields in Django


code:
if isinstance(values, basestring):
    html += values + "
"
else:
    for value in values:
        html += value + "
"

rawDescription: Python/Django Template Iterating through Strings and Lists


code:
class MyAdmin(admin.ModelAdmin):
    def __init__(self, model, admin_site):
        general_fields = ['notes', 'created_at', 'updated_at']
        fields = [f.name for f in self.model._meta.fields if f.name not in general_fields]
        self.fields = fields + general_fields
        super(admin.ModelAdmin, self).__init__(model, admin_site)

rawDescription: Reordering fields in Django model

description: Reordering fields in Django model


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

# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
p1 = plt.plot(x, y1, 'b-', linewidth=1.0)
p2 = plt.plot(x, y2, 'r-', linewidth=1.0)

# make a legend for both plots
leg = plt.legend([p1, p2], ['sin(x)', 'cos(x)'], loc=1)

# set the linewidth of each legend object
for legobj in leg.legendHandles:
    legobj.set_linewidth(2.0)

plt.show()

rawDescription: increase the linewidth of the legend lines in matplotlib

description: Increase the linewidth of the legend lines in matplotlib


code:
class Example(QtGui.QMainWindow):
    def __init__(self):
        ...

        header = self.table.horizontalHeader()
        header.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        header.customContextMenuRequested.connect(self.handleHeaderMenu)

    def handleHeaderMenu(self, pos):
        print('column(%d)' % self.table.horizontalHeader().logicalIndexAt(pos))
        menu = QtGui.QMenu()
        menu.addAction('Add')
        menu.addAction('Delete')
        menu.exec_(QtGui.QCursor.pos())

rawDescription: QMenu for QTableWidget in PySide/PyQt

description: QMenu for QTableWidget in PySide/PyQt


code:
vec = np.vectorize(val_to_rgb)
rgb_data = vec(data)

rawDescription: Efficient colorization of numpy matrix by value?


code:
f_values = some_function_of(indgrid[mask])
result = np.zeros(indgrid.shape)
result[mask] = f_values

rawDescription: Reshape a 1D array to a masked 2D array

description: Reshape a 1D array to a masked 2D array


code:
# x = root node
def acyc(graph,x=0):
    node = graph[x]

    if len(node) == 0:
        return {x:1}

    # call self on children
    count_map = {}
    for i in node:
        count_map.update(acyc(graph,i))
    count_map[x] = sum([node[i]*count_map[i] for i in node])

    return count_map

rawDescription: How to accumulate a count in directed graph in Python

description: Accumulate a count in directed graph in Python


code:
# class labels are 0 and 1
labeled_data = [
    (1, featureset_1),
    (0, featureset_2),
    (1, featureset_3),
    # ...
]

# naive_bayes is your already trained classifier,
# preferrably not on the data you're testing on :)

from pyroc import ROCData

roc_data = ROCData(
    (label, naive_bayes.prob_classify(featureset).prob(1))
    for label, featureset
    in labeled_data
)
roc_data.plot()

rawDescription: Ntlk & Python, plotting ROC curve

description: Ntlk & Python, plotting ROC curve


code:
def what_is(value):
    for attempt, type_ in ((float, "This is a float"),
                           (dateutil.parser.parse, "Date")):
        try:
            _ = attempt(value)
        except ValueError:
            continue
        return type_
    return "This is a string"

rawDescription: Find best type fit for a string in Python


code:
dt = datetime.datetime(2012, 1, 1,0,0)
dt.year

rawDescription: Convert datetime in Python list to year only


code:
def lower_case(a):
    x=str(a).lower()
    y = "This is now Lowercase:" + x;
    return y;

rawDescription: Making one string in python

description: Making one string in python


rawDescription: Unknown and Damaged Archive in django

description: Unknown and Damaged Archive in django


code:
import platform
platform.architecture()

rawDescription: How do I detect if Python is running as a 64-bit application?

description: Detect if Python is running as a 64-bit application


rawDescription: Working with Python dict/list

description: Working with Python dict/list


code:
X = [sqrt(2)]
for i in range(1,10):
    X.append(sqrt(2*X[i-1]))

rawDescription: Recursive sequence $x_n = \sqrt{2}$, $x_{n+1} = \sqrt{2x_n}$


code:
class AppAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.submitter = request.user # no need to check for it.
        obj.save()

rawDescription: Current user in django admin

description: Current user in django admin


code:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

xticks=['Jan','Feb','Mar','April','May']
x=[1,2,3,4,5]
yticks = ['Windy', 'Sunny', 'Rainy', 'Cloudy', 'Snowy']
y=[2,1,3,5,4]

plt.plot(x,y,'b-', marker = 'o') #.2,.1,.7,.8
plt.subplots_adjust(left =0.2)

plt.xticks(x,xticks)
plt.yticks(y,yticks)
ax.set_ylim(0.5,max(y))
plt.show()

rawDescription: matplotlib how to start ticks leaving space from the axis origin

description: Matplotlib how to start ticks leaving space from the axis origin


rawDescription: Python MySQL: Not showing inserted records


code:
valid = '1234567890123456'
invalid = '1848934798237489324324'
len(valid) == 16 and valid.isdigit()
len(invalid) == 16 and invalid.isdigit()

rawDescription: Validate input 16-digit credit card number


code:
# based on : www.daniweb.com/code/snippet263775.html
import math
import wave
import struct

def make_sine(freq=440, datasize=10000, fname="test.wav", framerate=44100.00):
    amp=8000.0 # amplitude
    sine_list=[]
    for x in range(datasize):
        sine_list.append(math.sin(2*math.pi * freq * ( x/frate)))
    # Open up a wav file
    wav_file=wave.open(fname,"w")
    # wav params
    nchannels = 1
    sampwidth = 2
    framerate = int(frate)
    nframes=datasize
    comptype= "NONE"
    compname= "not compressed"
    wav_file.setparams((nchannels, sampwidth, framerate, nframes, comptype, compname))
    #write on file
    for s in sine_list:
        wav_file.writeframes(struct.pack('h', int(s*amp/2)))
    wav_file.close()

frate = 44100.00 #that's the framerate
freq=987.0 #that's the frequency, in hertz
seconds = 3 #seconds of file
data_length = frate*seconds #number of frames
fname = "WaveTest2.wav" #name of file
make_sine(freq, data_length, fname)

rawDescription: How do I create a series of high- and low-pitch beeps using Ruby or Python?

description: Create a series of high- and low-pitch beeps using Ruby or Python


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

#Dummy data
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10.0 * (Z2 - Z1)

CS = plt.contour(X, Y, Z, 20, colors='k')

for line in CS.collections:
    if line.get_linestyle() == [(None, None)]:
        print("Solid Line")
    else:
        line.set_linestyle([(0, (12.0, 3.0))])
        line.set_color('red')

plt.show()

rawDescription: change dash style of negative values in a default contour - matplotlib

description: Change dash style of negative values in a default contour - matplotlib


code:
from Bio import SeqIO
import re
with open(fasta_path, 'rb') as fin:
    s = SeqIO.parse(fin, 'fasta')
    for r in s:
        num_you_want = int(re.findall('\((\d+) - \d+\)', r.description)[0])

rawDescription: Extract a number from fasta read headers


code:
class notePanel(nukescripts.PythonPanel):
    def __init__(self):
        nukescripts.PythonPanel.__init__(self, 'Note Panel', 'com.ohufx.notePanel')

        self.sgpage = nuke.PyScript_Knob('sgpage', 'Open SG page', '')

    def knobChanged(self, knob):
        if knob is self.sgpage:
            self.launchSGPage()

    def launchSGPage(self):
        pr = self.proj.value()
        sh = self.shot.value()
        url = shotgun.getURL(pr,sh)
        webbrowser.get('/usr/bin/google-chrome %s').open(url)

rawDescription: Using self in a Python class (in Nuke making a GUI)


code:
import win32api
win32api.ShellExecute(0, "open", "python.exe", 'blah.py', '', 1)

rawDescription: How to invoke a external application(Windows based) independent of parent python script?

description: Invoke a external application(Windows based) independent of parent python script


rawDescription: What happens if i try to split a string that cannot be split in python?


code:
def accumulator():
    sum = 0
    def addition(n):
         nonlocal sum
         sum += n
         return sum
    return addition

rawDescription: Making an addition accumulator in python


code:
import numpy as np
from itertools import islice

def findOverlap(self, a, b, rtol = 1e-05, atol = 1e-08):
    ovr_a = []
    ovr_b = []
    start_b = 0
    for i, ai in enumerate(a):
        for j, bj in islice(enumerate(b), start_b, None):
            if np.isclose(ai, bj, rtol=rtol, atol=atol, equal_nan=False):
                ovr_a.append(i)
                ovr_b.append(j)
            elif bj > ai: # (more than tolerance)
                break # all the rest will be farther away
            else: # bj < ai (more than tolerance)
                start_b += 1 # ignore further tests of this item
    return (ovr_a, ovr_b)

rawDescription: Find intersection of numpy float arrays

description: Find intersection of numpy float arrays


code: os.listdir("your directory")

rawDescription: How do I replace bytes in multiple files in one directory recursively with Python 3.5.1?

description: Replace bytes in multiple files in one directory recursively with Python 3.5.1


code:
names = [trend["name"] for trend in retrieved[0]["trends"]]
names

rawDescription: Convert tweepy JSON object to dict

description: Convert tweepy JSON object to dict


code:
import jpeg
jpeg.setExif(jpeg.getExif('foo.jpg'), 'foo-resized.jpg')

rawDescription: Resize image in Python without losing EXIF data


code:
# imports
import numpy as np
import pandas as pd
from StringIO import StringIO

# read in your data
data = """,Name,count1,count2,count3
Ward Summary,Aloha 1,35,0,0
Individual Statistics,John,35,0,0
Ward Summary,Aloha I,794,0,0
Individual Statistics,Walter,476,0,0
Individual Statistics,Deborah,182,0,0"""
df = pd.read_csv(StringIO(data))

# give the first column a better name for convenience
df.rename(columns={'Unnamed: 0':'Desc'}, inplace=True)

# create a mask for the Ward Summary lines
ws_mask = df.Desc == 'Ward Summary'

# create a ward_name column that has names only for Ward Summary lines
df['ward_name'] = np.where(ws_mask, df.Name, np.nan)

# forward fill the missing ward names from the previous summary line
df.ward_name.fillna(method='ffill', inplace=True)

# get rid of the ward summary lines
df = df.ix[~ws_mask]

# get rid of the Desc column
df.drop('Desc', axis=1)

rawDescription: Read CSV file that needs data sanitization prior to loading into dataframe


code: random.choice([k for k in d for x in d[k]])

rawDescription: Random Python dictionary key, weighted by values


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

def main():
    # Contour some regular (fake) data
    grid = np.arange(100).reshape((10,10))
    plt.contourf(grid)

    # Verticies of the clipping polygon in counter-clockwise order
    #  (A triange, in this case)
    poly_verts = [(2, 2), (5, 2.5), (6, 8), (2, 2)]

    mask_outside_polygon(poly_verts)

    plt.show()

def mask_outside_polygon(poly_verts, ax=None):
    """
    Plots a mask on the specified axis ("ax", defaults to plt.gca()) such that
    all areas outside of the polygon specified by "poly_verts" are masked.

    "poly_verts" must be a list of tuples of the verticies in the polygon in
    counter-clockwise order.

    Returns the matplotlib.patches.PathPatch instance plotted on the figure.
    """
    import matplotlib.patches as mpatches
    import matplotlib.path as mpath

    if ax is None:
        ax = plt.gca()

    # Get current plot limits
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    # Verticies of the plot boundaries in clockwise order
    bound_verts = [(xlim[0], ylim[0]), (xlim[0], ylim[1]),
                   (xlim[1], ylim[1]), (xlim[1], ylim[0]),
                   (xlim[0], ylim[0])]

    # A series of codes (1 and 2) to tell matplotlib whether to draw a line or
    # move the "pen" (So that there's no connecting line)
    bound_codes = [mpath.Path.MOVETO] + (len(bound_verts) - 1) * [mpath.Path.LINETO]
    poly_codes = [mpath.Path.MOVETO] + (len(poly_verts) - 1) * [mpath.Path.LINETO]

    # Plot the masking patch
    path = mpath.Path(bound_verts + poly_verts, bound_codes + poly_codes)
    patch = mpatches.PathPatch(path, facecolor='white', edgecolor='none')
    patch = ax.add_patch(patch)

    # Reset the plot limits to their original extents
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

    return patch

if __name__ == '__main__':
    main()

rawDescription: Filling complements of areas with matplotlib


code:
for k in mat.keys():
    if not k.startswith('__'):
        print(k + " " + mat[k].dtype.name + " " + str(mat[k].shape))

rawDescription: Showing Type and Size of a Mat file loaded in Python


code:
def f():
    if random.random() < 0.5:
        for a in xrange(10):
            yield a
    else:
        stuff = range(10)
        random.shuffle(stuff)
        for a in stuff:
            yield a
list(f())
list(f())

rawDescription: In Python, how do I determine if an iterable has stable iteration order?


code:
'hello'[:2]
'hello'[-2:]
'abcdefghijklmnop'[::2]
'abcdefghijklmnop'[1::2]
'Reverse this!'[::-1]

rawDescription: Is there a Python function like Lua's string.sub?


code:
import gc
gc.collect()

rawDescription: Need help identifying a memory leak involving matplotlib and flask


code:
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    )

logging.info('Danger Will Robinson!')
# 03-31 20:00 root         INFO     Danger Will Robinson!
root = logging.getLogger()
hdlr = root.handlers[0]
fmt = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
hdlr.setFormatter(fmt)
logging.info('Danger Will Robinson!')
# root        : INFO     Danger Will Robinson!

rawDescription: How do I change the default format of log messages in python app engine?

description: Change the default format of log messages in python app engine


code:
import numpy as np
import mayavi.mlab as ML

verts = [(1,-1,0), (1,1,0), (-1,1,0), (-1,-1,0), (0,0,1), (0,0,-1)]
x, y, z = zip(*verts)
# Each triangle is a 3-tuple of indices. The indices are indices of `verts`.
triangles = [(i, (i+1)%4, j) for i in range(4) for j in (4,5)]
colorval = z
ML.triangular_mesh(x, y, z, triangles, scalars=colorval, opacity=0.75)
ML.show()

rawDescription: Mayavi Mlab : Drawing octahedrons

description: Mayavi Mlab : Drawing octahedrons


code: del type(Q).an_attribute

rawDescription: Delete attribute of a class using its instance


code:
assert num == len([getattr(foo, x)
                   for x in dir(foo)
                   if isinstance(getattr(foo, x), foo.Foo)])

rawDescription: How to use introspection in Python 2.7 to find instances of certain class in a module?

description: Use introspection in Python 2.7 to find instances of certain class in a module


code:
with open('vlgaChcWaves.txt', 'r+') as vlgaStream:
  for line in vlgaStream:
    dosomethingwith(line)

rawDescription: Most efficient way to open a file and read the lines?


code:
def __call__(self, environ, start_response):
        # initialize a session for the current user
        global _current_session
        _current_session = Session(lifetime=self.lifetime, no_datastore=self.no_datastore, cookie_only_threshold=self.cookie_only_thresh, cookie_key=self.cookie_key)

rawDescription: get_current_session returns None

description: Get_current_session returns None


code:
from IPython import get_ipython
ipython = get_ipython()

if '__IPYTHON__' in globals():
    ipython.magic('load_ext autoreload')
    ipython.magic('autoreload 2')

rawDescription: How to use IPython magic within a script to auto reload modules?

description: Use IPython magic within a script to auto reload modules


code:
s = u'Gaga\xe2\x80\x99s'
s.encode('latin-1').decode('utf8')

rawDescription: Python Convert Unicode-Hex utf-8 strings to Unicode strings


code:
from django.contrib.auth import authenticate, login

@login_required
def home_page(request):
    return HttpResponse("hello " + str(request.user))

def login_view(request):
    return render(request, 'login.html')

def verify(request):
    u = request.POST['username']
    p = request.POST['password']
    user = authenticate(username=u, password=p)
    if user is not None:
        if user.is_active:
            # You need to call `login` with `request` AND `user`
            login(request, user)
            print("logged in")
            return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/accounts/login/')

rawDescription: Django redirects to login page even after logging in


rawDescription: Numpy- weight and sum rows of a matrix

description: Numpy- weight and sum rows of a matrix


rawDescription: Keras BatchNormalization, What exactly is sample wise normalization?


code:
import collections

def readFile(filename):
    with open(filename) as infile:
        counts = collections.Counter(char for line in infile for char in line)
    symObjList = []
    for nuc in "ATCG":
        symObjList.append(SymbolObject(nuc, counts[nuc], ""))
        print(nuc, "appears", counts[nuc], "times")

    return {k:counts[k] for k in "ATCG"}, symObjList

rawDescription: I need to count letter frequency and save the letter and it's freq as variable


code:
from collections import defaultdict

l = [(1, 'a', 22), (2, 'b', 56), (1, 'b', 34), (2, 'c', 78), (3, 'd', 47)]

d = defaultdict(dict)
for x, y, z in l:
    d[x][y] = z

rawDescription: How to convert a list of tuples to a dictionary of dictionaries in Python?

description: Convert a list of tuples to a dictionary of dictionaries in Python


code:
def multi_func(functions):
    def f(col):
        return functions[col.name](col)
    return f

df = pd.DataFrame(np.random.random((10, 2)), columns=['A', 'B'])
result = df.apply(multi_func({'A': np.mean, 'B': np.sum}))

rawDescription: Pandas: apply different functions to different columns


code:
def ilen(n):
    i=0
    while n != 0:
      n /= 10
      i += 1
    return i

ilen(54352)

rawDescription: Without using module, how can I determine the width of an integer?


code:
import re
from xml.parsers import expat

# illegal XML 1.0 character ranges
# See http://www.w3.org/TR/REC-xml/#charsets
XML_ILLEGALS = u'|'.join(u'[%s-%s]' % (s, e) for s, e in [
    (u'\u0000', u'\u0008'),             # null and C0 controls
    (u'\u000B', u'\u000C'),             # vertical tab and form feed
    (u'\u000E', u'\u001F'),             # shift out / shift in
    (u'\u007F', u'\u009F'),             # C1 controls
    (u'\uD800', u'\uDFFF'),             # High and Low surrogate areas
    (u'\uFDD0', u'\uFDDF'),             # not permitted for interchange
    (u'\uFFFE', u'\uFFFF'),             # byte order marks
    ])

RE_SANITIZE_XML = re.compile(XML_ILLEGALS, re.M | re.U)

# decode, filter illegals out, then encode back to utf-8
data = open('chrisblattman.xml', 'rb').read().decode('utf-8')
data = RE_SANITIZE_XML.sub('', data).encode('utf-8')

pr = expat.ParserCreate('utf-8')
pr.Parse(data)

rawDescription: Gracefully recover from parse error in expat


code:
for row in csvReader:
    row = "".join(row)
    stockList.append(row)

rawDescription: Python List Bracket Removal

description: Python List Bracket Removal


code:
from lxml.html import HtmlComment # or similar
no_comments=[element for element in element_list if not isinstance(element, HtmlComment)]

rawDescription: How to access comments using lxml

description: Access comments using lxml


code:
the_number = decimal.Decimal(1.23456789)
round(the_number, 2)
d=decimal.Decimal("31.100")
d
round(d, 10)
round(d, 20)
round(d, 24)
round(d, 26)
round(d, 1)
round(d, 0)

rawDescription: Rounding Decimal to configurable decimal places in python


code:
import copy

def scrub(x):
    ret = copy.deepcopy(x)
    # Handle dictionaries. Scrub all values
    if isinstance(x, dict):
        for k,v in ret.items():
            ret[k] = scrub(v)
    # Handle None
    if x == None:
        ret = ''
    # Finished scrubbing
    return ret

rawDescription: Python: How json dumps None to empty string


code: numpy.mean([a, b, c], axis=0)

rawDescription: how to compute the mean of values from different lists

description: Compute the mean of values from different lists


code: req_egg = cursor.fetchmany(2)

rawDescription: How can I "fetch two" with python-mysql?

description: "fetch two" with python-mysql


code:
from music21 import *
for fn in filenameList:
    s = converter.parse(fn)
    k = s.analyze('key')
    i = interval.Interval(k.tonic, pitch.Pitch('C'))
    sNew = s.transpose(i)
    # do something with sNew

rawDescription: music21 - Transpose streams to a given key

description: Music21 - Transpose streams to a given key


code:
import csv

dict_data = {'key1': [1, 2, 3], 'key2': [4, 5, 6]}

with open("dict2csv.txt", 'w') as outfile:
   csv_writer = csv.writer(outfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)

   for k,v in dict_data.items():
       csv_writer.writerow([k] + v)

rawDescription: Write dictionary (keys and values) to a csv file


code:
import time
import os

lives = 3

def start():
    global lives

    if lives < 1:
        print("GAME OVER")
        quit()

    print("You wake up in a well.")
    print("Do you climb out or get help?")
    well = raw_input("Help or Climb?  ").upper()[0]

    if well == "H":
        print("You get your phone out.")
        time.sleep(2)
        print("There's no charge left.")
        print(" " * 3)
        lives = lives - 1
        print("You have", lives, "lives left.")
        time.sleep(3)
        os.system("cls")
        start()

    elif well == "C":
        print("You start climbing up the walls of the well.")
        time.sleep(3)
        print("You are close, but you lose your footing and are blinded by the sunlight,")
        footing = raw_input("Move your foot to the left or right?").upper()[0]
        if footing == "L":
            print("You miss the step and fall.")
            lives = lives - 1
            start()

start()

rawDescription: Python is confusing me and need assistance


code:
import os
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir))

rawDescription: How to add/import a Django project into a virtualenv?

description: Add/import a Django project into a virtualenv


code:
...
testfile = TestPage(...)
...
load_file(testpage)
...

def load_file(page):
    ...
    page.set_values()

rawDescription: Update class instance StringVar() from abstract method


rawDescription: How to check for adjacency in list, then fix adjacency in python

description: Check for adjacency in list, then fix adjacency in python


code: return next((i for i, v in enumerate(L) if v != x), -1)

rawDescription: In Python, how can I find the index of the first item in a list that is NOT some value?


code:
plt.imshow(matrix, cmap=plt.cm.jet, aspect='auto', origin='lower', alpha=1,interpolation='none', extent=(xAxis[0],xAxis[-1], yAxis[0], yAxis[-1]))

plt.colorbar()
plt.show()

rawDescription: Plot 3 columns matrix with pyplot

description: Plot 3 columns matrix with pyplot


code:
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.dates import DateFormatter
from matplotlib.finance import candlestick

class Chart3(object):
    def __init__(self, data, maxt=10):
        self.maxt = maxt
        self.data = data
        self.result = data[:self.maxt]

        # Parse the data columns
        self.tdata = [r[0] for r in self.result]
        self.sdata = [r[4] for r in self.result]
        self.mdata = [r[3] for r in self.result]

        # Initialize plot frame
        xfmt = DateFormatter('%Y-%m-%d %H:%M')
        self.fig, self.ax = plt.subplots()
        self.fig.subplots_adjust(bottom=0.2)
        self.ax.xaxis.set_major_formatter(xfmt)
        self.ax.xaxis_date()
        plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='center')
        self.animate()

    def plot(self):
        if len(self.tdata) > self.maxt:  # roll the arrays
            self.tdata = self.tdata[-self.maxt:]
            self.sdata = self.sdata[-self.maxt:]
            self.mdata = self.mdata[-self.maxt:]
            self.result = self.result[-self.maxt:]

        # Plot the next set of line data
        line_min = Line2D(self.tdata, self.sdata, color='r')
        self.ax.add_line(line_min)
        line_max = Line2D(self.tdata, self.mdata, color='g')
        self.ax.add_line(line_max)

        # Plot the next set of candlestick data
        candlestick(self.ax, self.result, width=60 / 86400.0,  colorup='g', colordown='r')

        # Update the x-axis time date and limits
        if len(self.tdata) > 1:
            self.ax.set_xlim(self.tdata[0], self.tdata[-1])

        # Update the y-axis limits
        self.ax.set_ylim(min(self.sdata) * 0.99, max(self.mdata) * 1.01)

    def update_prices(self, cnt):
        """
        adds a data point from data to result list for plotting
        @return:
        """
        results = self.data[self.maxt + cnt]  # add another point of data
        t = (results[0])
        if self.tdata[-1] != t:
            trade = results
            self.result.append([t, trade[1], trade[2], trade[3], trade[4], trade[5], trade[6]])
            self.tdata.append(self.result[-1][0])
            self.sdata.append(self.result[-1][4])
            self.mdata.append(self.result[-1][3])

    def update_plot(self, i):
        try:
            self.update_prices(cnt=i)
            self.plot()
        except:
            pass

    def animate(self):
        # With try ... except in update_plot()
        # anim = animation.FuncAnimation(fig=self.fig, func=self.update_plot, interval=1000)

        # Without try ... except in update_plot()
        anim = animation.FuncAnimation(fig=self.fig, func=self.update_plot, interval=1000,
                                       frames=len(self.data)-self.maxt, repeat=False)
        plt.show()

if __name__ == "__main__":
    testData = [
        [735265.79166666663, 21.901, 21.901, 21.901, 21.901, 21.901, 0],
        [735265.79305555555, 21.901, 21.901, 21.901, 21.901, 21.901, 0],
        [735265.79236111115, 21.901, 21.901, 21.901, 21.901, 21.901, 0],
        [735265.79374999995, 21.9, 21.901, 21.901, 21.9, 21.9005, 11.65],
        [735265.79444444447, 21.901, 21.939, 21.939, 21.901, 21.91525, 23.23606],
        [735265.79513888888, 21.94, 21.95, 21.9703, 21.94, 21.953781250000002, 172.91374199999998],
        [735265.79583333328, 21.96, 21.99, 21.99, 21.96, 21.973333333333336, 142.974981],
        [735265.7965277778, 21.995, 21.995, 21.997, 21.995, 21.995533333333338, 36.541180000000004],
        [735265.7972222222, 21.9703, 21.995, 22.0, 21.9703, 21.993162500000004, 18.305711],
        [735265.79791666672, 21.9999, 21.86, 22.0, 21.86, 21.93492, 103.2468273],
        [735265.79861111112, 21.9045, 21.9045, 21.9045, 21.9045, 21.9045, 2.43879],
        [735265.79930555553, 21.929, 21.861, 21.99, 21.86, 21.92566666666666, 2.838343],
        [735265.80000000005, 21.9241, 21.899, 21.9241, 21.899, 21.907366666666665, 10.0],
        [735265.80069444445, 21.861, 21.86, 21.861, 21.86, 21.860888888888887, 111.367172],
        [735265.80138888885, 21.86, 21.861, 21.861, 21.86, 21.8604, 78.36582],
        [735265.80208333337, 21.861, 21.862, 21.862, 21.859, 21.860483333333335, 112.842532],
        [735265.80277777778, 21.862, 21.863, 21.88, 21.862, 21.8694, 83.64361899999999],
        [735265.80347222218, 21.88, 21.88, 21.88, 21.88, 21.88, 7.46027],
        [735265.8041666667, 21.88, 21.9256, 21.9256, 21.88, 21.9104, 7.06897],
        [735265.8048611111, 21.9256, 21.9256, 21.9256, 21.9256, 21.9256, 0.339032],
        [735265.8055555555, 21.9256, 21.9256, 21.9256, 21.9256, 21.9256, 2.024438],
        [735265.80625000002, 21.88, 21.88, 21.881, 21.88, 21.880249999999997, 25.00003],
        [735265.80694444443, 21.92, 21.92, 21.92, 21.92, 21.92, 0],
        [735265.80763888895, 21.92, 21.92, 21.92, 21.92, 21.92, 0],
        [735265.80833333335, 21.91, 21.92, 21.92, 21.91, 21.915, 80.0],
        [735265.80902777775, 21.881, 21.92, 21.92, 21.881, 21.907, 43.913890200000004],
        [735265.80972222227, 21.914, 22.0, 22.0, 21.914, 21.973115625, 368.000066],
        [735265.81041666667, 21.93, 21.93, 21.93, 21.93, 21.93, 0],
        [735265.81111111108, 21.9, 21.93, 21.93, 21.9, 21.9225, 15.475088999999999],
        [735265.8118055556, 21.93, 22.0, 22.0, 21.91, 21.97401, 56.620048589999996]
    ]

    chart = Chart3(data=testData)

rawDescription: Python matplotlib animate a candlestick plot


code:
with open('data', 'r') as f:
    li = f.read()

li =  re.findall(r'(Head.*?\n+.*?)(?:\n+^$|\Z)',li, re.MULTILINE|re.DOTALL)

# # split strings on newline
li = list(map(lambda x: re.split('\n+',x),li))
# # create dictionaries
lid = [ {l[0]:{','.join(l[1:])}} for l in li]

pp(lid)

[{'Head 1': {'bla1,bla2,bla3'}},
 {'Head 2': {'blo 1,blo 2,blo 3,blo 4'}},
 {'Head 3': {'blu 1,blu 2'}}]

rawDescription: read file, matching string (heading) and save block below each heading

description: Read file, matching string (heading) and save block below each heading


code:
from django.db.models import Q

...

Table.objects.filter(Q(col1=myValue) | Q(col2=myValue))

rawDescription: How to filter based on either one of the columns

description: Filter based on either one of the columns


rawDescription: How to use AndroidViewClient Culebra to scroll down

description: Use AndroidViewClient Culebra to scroll down


rawDescription: Maximum of two tuples

description: Maximum of two tuples


code:
array = [5,2,3,12,1,6]
highest_pos = 0
i=0

for i in range(len(array)):
    if array[i] > array[highest_pos]:
        highest_pos = i
    i+=1

print(array[highest_pos])
temp = array[-1]
array[-1] = array[highest_pos]
array[highest_pos] = temp

print(array)

rawDescription: How do I find the highest value and swap it with the end value in an array?

description: Find the highest value and swap it with the end value in an array


code:
month_abbreviations = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4,
                       'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8,
                       'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
year = int(line[7:11])
month = month_abbreviations[line[3:6]]
day = int(line[0:2])
hour = int(line[12:14])
minute = int(line[15:17])
second = int(line[18:20])
new_entry['time'] = datetime.datetime(year, month, day, hour, minute, second)

rawDescription: Python datetime.strptime() Eating lots of CPU Time


code:
import threading
class MyThread(threading.Thread): pass
def do_nothing():
    while True:
        pass
MyThread(target=do_nothing).start()
threading.Thread(target=do_nothing).start()
threading.enumerate()
[t for t in threading.enumerate() if isinstance(t, MyThread)]

rawDescription: Is a specific thread inside the threading.enumerate()?


code:
import re
S='ABCDEFGhijklmnopQRSTUVwxyz'
re.sub('[a-z]', 'X', S)

rawDescription: Replace lowercase ASCII characters with X in Python


code:
def group_by_heading( some_source ):
    buffer= []
    for line in some_source:
        if line.startswith( "Heading" ):
            if buffer: yield buffer
            buffer= [ line ]
        else:
            buffer.append( line )
    yield buffer

with open( "some_file", "r" ) as source:
    for heading_and_lines in group_by_heading( source ):
        heading= heading_and_lines[0]
        lines= heading_and_lines[1:]
        # process away.

rawDescription: How to grab the lines AFTER a matched line in python

description: Grab the lines AFTER a matched line in python


code:
cues = self._get_assignable_cues(keyword)
group_ids = tuple(cues.values_list('group_id', flat=True).distinct())
cues_per_group = Cue.objects.raw(
    'SELECT * FROM main_cue WHERE group_id IN %s GROUP BY group_id', (group_ids,)
)

rawDescription: GROUP BY single column without doing raw sql


code:
categoryChoice = input("what is your category choice?")
if categoryChoice not in ("category1", "category 2", "category 3"):
    print("not a valid choice")

rawDescription: Python 3: how to compare multiple strings in one line of code?


code:
if __name__ == '__main__':
    do_stuff()

rawDescription: Check if script run as standalone or from django interface


code:
def __init__(self, prop, fun):
    self.prop = prop
    self.fun = types.MethodType(fun, self)

rawDescription: python context of passed-to-class function

description: Python context of passed-to-class function


code:
grouped = df.groupby('game_id')
won = grouped.won.sum()
DataFrame({True: won, False: grouped.person.nunique() - won}).stack()

rawDescription: Tricky aggregation using pandas

description: Tricky aggregation using pandas


code:
query1 = query1.filter(model.name == "in-addr.arpa.")
query2 = query2.filter(model.tenant_id.in_(tenant_ids))
query3 = query3.filter(model.tenant_id == context.tenant_id)
query = query1.union(query2,query3)

rawDescription: Performing union with three queries - SQLAlchemy


rawDescription: How can i search and replace using python regex

description: Search and replace using python regex


code:
#!/bin/env python
import csv
from itertools import islice

total = count = 0

with open('3111111a.csv', newline='') as f:
    reader = csv.reader(f)
    # `isslice` will skip any header/title row.
    # Generates a list of integers from the fourth CSV value
    numbers = (int(row[4]) for row in islice(reader, 1, None))
    # Generates another list of values that are >= 337
    gt337 = [i for i in numbers if i >= 337]

# Sums all the numbers in our list then divides by the number to get the average
print (sum(gt337)/len(gt337))

rawDescription: Need Help on Average Python

description: Need Help on Average Python


code: KEY_END  : (lambda: move_to_line(widget.last_line), None)

rawDescription: Store function mappings and arguments in a dict


code:
import HTMLParser
h= HTMLParser.HTMLParser()
h.unescape('alpha < β')

rawDescription: HTML Entity Codes to Text

description: HTML Entity Codes to Text


code:
from scipy import interpolate
import numpy as np

# example dataset (wavy cylinder)

def surf(u, v):
    x = np.cos(v*np.pi*2) * (1 + 0.3*np.cos(30*u))
    y = np.sin(v*np.pi*2) * (1 + 0.3*np.cos(30*u))
    z = 2*u
    return x, y, z

ux, vx = np.meshgrid(np.linspace(0, 1, 20),
                     np.linspace(0, 1, 20))
x, y, z = surf(ux, vx)

# reconstruct (u, v) using the existing (!) neighbourhood information
du = np.sqrt(np.diff(x, axis=0)**2 + np.diff(y, axis=0)**2 + np.diff(z, axis=0)**2)
dv = np.sqrt(np.diff(x, axis=1)**2 + np.diff(y, axis=1)**2 + np.diff(z, axis=1)**2)
u = np.zeros_like(x)
v = np.zeros_like(x)
u[1:,:] = np.cumsum(du, axis=0)
v[:,1:] = np.cumsum(dv, axis=1)

u /= u.max(axis=0)[None,:] # hmm..., or maybe skip this scaling step -- may distort the result
v /= v.max(axis=1)[:,None]

# construct interpolant (unstructured grid)
ip_surf = interpolate.CloughTocher2DInterpolator(
        (u.ravel(), v.ravel()),
        np.c_[x.ravel(), y.ravel(), z.ravel()])

# the BivariateSpline classes might also work here, but the above is more robust

# plot projections
import matplotlib.pyplot as plt

u = np.random.rand(2000)
v = np.random.rand(2000)

plt.subplot(131)
plt.plot(ip_surf(u, v)[:,0], ip_surf(u, v)[:,1], '.')
plt.title('xy')
plt.subplot(132)
plt.plot(ip_surf(u, v)[:,1], ip_surf(u, v)[:,2], '.')
plt.title('yz')
plt.subplot(133)
plt.plot(ip_surf(u, v)[:,2], ip_surf(u, v)[:,0], '.')
plt.title('zx')
plt.show()

rawDescription: Parametric Surface Creation in Python

description: Parametric Surface Creation in Python


code:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")

rawDescription: Jupyter (Python): Display .tex tables from .txt files


code:
from lxml import etree
root = etree.fromstring("...your xml...")

el, = root.xpath("//div[text() = 'the string']/preceding-sibling::*[9]")

rawDescription: Is there a way to specify a fixed (or variable) number of elements for lxml in Python


code:
from rest_framework.permissions import IsAuthenticated
from rest_framework import generics

class IsAuthenticatedNotPost(IsAuthenticated):
    def has_permission(self, request, view):
        if request.method == 'POST':
            return True
        return super(IsAuthenticatedNotPost, self).has_permission(request, view)

class SomeView(generics.ListCreateAPIView):
    permission_classes = (IsAuthenticatedNotPost, )

rawDescription: django-rest-framework: generic view and method-based permission

description: Django-rest-framework: generic view and method-based permission


code:
myOutput = myOutput.strip()
self.assertEqual(myOutput, expOutput, "Script output is not the expected")

rawDescription: Error comparing long string output in Python test


code:
from hashlib import sha256
from random import random
random_key = random()
sha256('%s%s%s'%('YOUR SECRET KEY',random_key,password))

rawDescription: how to store password on gae when someone register

description: Store password on gae when someone register


code:
class MyClass:

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

rawDescription: Is there a way to check if two object contain the same values in each of their variables in python?


rawDescription: Python regex findall alternation behavior


code: cursor = collection.find({'multiple.layers.of.data' : {'$regex': REGEX}})

rawDescription: REGEX Searching in pymongo

description: REGEX Searching in pymongo


code:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid
import numpy as np
from matplotlib.cbook import get_sample_data

#Setup figure/grid
fig = plt.figure()
grid = AxesGrid(fig, 111, nrows_ncols = (2, 2), share_all=True)

#Plot some data
f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
Z = np.load(f)
for i in range(4):
    im = grid[i].imshow(Z)

#Set tick one of axis 3 in grid to off
ax = grid[3]
xticks = ax.xaxis.get_major_ticks()
xticks[1].label1.set_visible(False)
plt.draw()
plt.show()

rawDescription: Matplotlib: Different ticklabels on shared axes


code:
from django.db.models import Sum

total = ( Task.objects
            .filter(your-filter-here)
            .aggregate(
                total=Sum('progress', field="progress*estimated_days")
             )['total']
         )

rawDescription: Django Aggregation: Summation of Multiplication of two fields


code:
import re
name_owner = 'Jimmy'
r = re.compile(r'[A-Za-z\s]+\nName: {}'.format(name_owner))
len([m for m in r.finditer(listing_read) if 'BTS' not in m.group(0)])

rawDescription: Counting occurrences whilst ignoring some occurrences in python


rawDescription: Google Datastore: get_by_id with an ancestor


code:
import boto
autoscale = boto.connect_autoscale()
ec2 = boto.connect_ec2()
group = autoscale.get_all_groups(['mygroupname'])[0]
instance_ids = [i.instance_id for i in group.instances]
reservations = ec2.get_all_instances(instance_ids)
instances = [i for r in reservations for i in r.instances]

rawDescription: List instances in auto scaling group with boto


rawDescription: Python Import From Path

description: Python Import From Path


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

x = list(reversed([1.81,1.715,1.78,1.613,1.629,1.714,1.62,1.738,1.495,1.669,1.57,1.877,1.385]))
y = [0.924,0.915,0.914,0.91,0.909,0.905,0.905,0.893,0.886,0.881,0.873,0.873,0.844]

def plot_with_text(x, y, text, text_count=None):
    text_count = (2 * (len(x) / len(text))) if text_count is None else text_count
    fig, ax = plt.subplots(1,1)
    l, = ax.plot(x,y)
    text_size = len(text) * 10
    idx_step = len(x) / text_count
    for idx_num in range(text_count):
        idx = int(idx_num * idx_step)
        text_pos = [x[idx], y[idx]]
        xscreen = ax.transData.transform(zip(x[max(0, idx-1):min(len(x), idx+2)], y[max(0, idx-1):min(len(y), idx+2)]))
        a = np.abs(np.gradient(xscreen)[0][0])
        rot = np.rad2deg(np.arctan2(*a)) - 90
        ax.annotate(text, xy=text_pos, color="r", bbox=dict(ec="1", fc="1", alpha=0.9), rotation=rot, ha="center", va="center")

plot_with_text(x, y, "test")

rawDescription: Plot dashed line interrupted with data (similar to contour plot)


code:
import sys
sys.ps1 = 'SOMETHING'

rawDescription: interactive mode doesn't switch on from script (matplotlib 1.4.0 python 2.7.5 on mac osx 10.8.5)

description: Interactive mode doesn't switch on from script (matplotlib 1.4.0 python 2.7.5 on mac osx 10.8.5)


code:
a = np.array(['hello ', 'world', 'blah', 'blah', 'blah'])
f = lambda *args: args[0] + args[1]
f(*a)

rawDescription: Calling lambda functions with iteration over a numpy array of shape `(n,)`


code:
from celery.task.control import revoke
revoke(task_id, terminate=True)

rawDescription: Cancel an already executing task with Celery?


code: help(open)

rawDescription: Is there Python official API documentation?


code:
# Read data from file
with open('yourfile.txt', 'r') as file:
    # read all line in the file to data array
    data = file.readlines()

# change data on line 58 (array start from 0)
data[57] = 'Data you need to change'

# Write data back
with open('yourfile.txt', 'w') as file:
    file.writelines(data)

rawDescription: Python-2.7 write to file

description: Python-2.7 write to file


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        def make_frame(text, parent):
            frame = QtGui.QFrame(parent)
            frame.setFrameStyle(QtGui.QFrame.StyledPanel)
            layout = QtGui.QHBoxLayout(frame)
            label = QtGui.QLabel(text, frame)
            label.setAlignment(QtCore.Qt.AlignCenter)
            layout.addWidget(label)
            return frame
        self.splitter = QtGui.QSplitter(self)
        for text in 'ONE TWO THREE'.split():
            self.splitter.addWidget(make_frame(text, self.splitter))
        self.stack = QtGui.QStackedLayout()
        self.stack.addWidget(self.splitter)
        self.stack.addWidget(make_frame('FOUR', self))
        self.button = QtGui.QPushButton('Switch', self)
        self.button.clicked.connect(
            lambda: self.stack.setCurrentIndex(
                int(self.stack.currentIndex() == 0)))
        layout = QtGui.QVBoxLayout(self)
        layout.addLayout(self.stack)
        layout.addWidget(self.button)

if __name__ == '__main__':

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

rawDescription: How to delete QFrame in pyqt

description: Delete QFrame in pyqt


code:
def walk_list(list_of_g):
    to_idx = 0
    for g_current in list_of_g:
        if not subtle_condition(g_current):
            list_of_g[to_idx] = g_current
            to_idx += 1
    del list_of_g[to_idx:]

rawDescription: Remove items from a list while iterating without using extra memory in Python


code:
from collections import defaultdict

with open(ref_file, 'r') as ref, open(dat_file, 'r') as dat:
    dat_dic = defaultdict(list)  # maintain a list of offsets for each size
    for d_line in dat:
        _, offset, size = d_line.split()
        dat_dic[size].append(offset)

    for r_line in ref:
        index, size = r_line.split()
        for offset in dat_dic[size]:
            # dict lookup is O(1) and not O(N) ...
            # ... as looping over the dat_file is
            print('{offset}\t{index}'.format(offset=offset, index=index))

rawDescription: How to improve Python iteration performance over large files

description: Improve Python iteration performance over large files


code:
urls = ['http://www.doopa.pl/1','http://www.doopa.pl/2',
    'http://www.dupa2.pl/4/php.pl', 'http://www.dupa3.pl/4/php?gfdgfd=44',
    'www.dupa4.pl/4/php.pl']
from urlparse import urlparse
dict((urlparse(u).netloc, u) for u in urls).values()

rawDescription: Unique by domains urls list

description: Unique by domains urls list


rawDescription: Remove just the alphabet characters from a string


code:
def main():
    infile = open('numbers.dat', 'r')

    largest = 0
    count = 0
    for line in infile:
        number = int(line)

        if number > largest:
            # If the number on the line we are currently reading is greater than,
            # our previously highest. Set the highest to this number instead.
            largest = number

        # Increment the number of lines we have read.
        count += 1

    infile.close()

    # Finally print the values we got from parsing the file
    print('The largest number in the file is: %s' % largest)
    print('The amount of numbers in the file is: %s' % count)
main()

rawDescription: How to make my program not an array/list but do the same as it should

description: Make my program not an array/list but do the same as it should


code:
#Allows the laminate to get exported as a DAE.
def toDAE(self):
    """
    Exports the current lamiante to a DAE file format
    """
    import collada
    mesh = collada.Collada()
    layerdef = self.layerdef
    nodes = [] # Each node of the mesh scene. Typically one per layer.
    for layer in layerdef.layers:
        layer_thickness = layer.thickness
        shapes = self.geoms[layer]
        zvalue = layerdef.z_values[layer]
        height = float(zvalue) #* 100 #*
        if (len(shapes) == 0) : #In case there are no shapes.
            continue
        for s in shapes:
            geom = self.createDAEFromShape(s, height, mesh, layer_thickness)
            mesh.geometries.append(geom)
            effect = collada.material.Effect("effect", [], "phone", diffuse=(1,0,0), specular=(0,1,0))
            mat = collada.material.Material("material", "mymaterial" + str(s.id), effect)
            matnode = collada.scene.MaterialNode("materialref" + str(s.id), mat, inputs=[])
            mesh.effects.append(effect)
            mesh.materials.append(mat)
            geomnode = collada.scene.GeometryNode(geom, [matnode])
            node = collada.scene.Node("node" + str(s.id), children=[geomnode])
            nodes.append(node)
    myscene = collada.scene.Scene("myscene", nodes)
    mesh.scenes.append(myscene)
    mesh.scene = myscene
    filename = popupcad.exportdir + os.path.sep +  str(self.id) + '.dae' #
    mesh.write(filename)

def createDAEFromShape(self, s, layer_num, mesh, thickness): #TODO Move this method into the shape class.
    import collada
    vertices = s.extrudeVertices(thickness, z0=layer_num)

    #This scales the verticies properly. So that they are in millimeters.
    vert_floats = [float(x)/(popupcad.SI_length_scaling) for x in vertices]
    vert_src_name = str(self.id) + '|' + str(s.id) + "-array"
    vert_src = collada.source.FloatSource(vert_src_name, numpy.array(vert_floats), ('X', 'Y', 'Z'))
    geom = collada.geometry.Geometry(mesh, "geometry-" + str(s.id), str(self.id), [vert_src])
    input_list = collada.source.InputList()
    input_list.addInput(0, 'VERTEX', "#" + vert_src_name)
    indices = numpy.array(range(0,(len(vertices) // 3)));
    triset = geom.createTriangleSet(indices, input_list, "materialref" + str(s.id))
    triset.generateNormals()
    geom.primitives.append(triset)
    return geom

rawDescription: How to create a collada file from an objects faces' vertices information?

description: Create a collada file from an objects faces' vertices information


code:
class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self.panel = wx.Panel(self)
        self.panel.BackgroundColour = wx.RED
        self.panel.Bind(wx.EVT_LEFT_UP, self.onClick)

    def onClick(self, event):
        self.panel.BackgroundColour = wx.GREEN

rawDescription: on click event in wx.Panel?

description: On click event in wx.Panel


code: "\n".join(["{0}. {1}".format(i+1, person) for i, person in enumerate(defaultersList)])

rawDescription: Constructing a multiline string from array in python


code:
def filter(request):
    if 'date_from' in request.GET and 'date_to' in request.GET:
        # form data has been submitted
        form = PersonForm(request.GET)
        if form.is_valid():
            date_from = form.cleaned_data['date_from']
            date_to = form.cleaned_data['date_to']
            people = Person.objects.filter(date__range=(date_from, date_to))
            table = PersonTable(people)
        else:
            table = PersonTable(Person.objects.all())
    else:
        form = PersonForm()
        table = PersonTable(Person.objects.all())
    RequestConfig(request, paginate={"per_page": 100}).configure(table)
    args = {}
    args.update(csrf(request))
    args['form'] = form
    args['table'] = table
    return render(request, 'people.html', args)

rawDescription: Filtering data with __range

description: Filtering data with __range


code:
def innerHTML(node):
    buildString = ''
    for child in node:
        buildString += html.tostring(child)
    return buildString

rawDescription: Get divs HTML content with lxml

description: Get divs HTML content with lxml


code:
data = htmlfile.read(512)
while data is not None:
    htmltext += data

rawDescription: Why can't I access the HTML of some websites


rawDescription: map a method over list of different objects

description: Map a method over list of different objects


code:
archive = 'dum/2164/archive.tar'

# Read input data.
input_tar = tarfile.open(archive, 'r')
tarinfo = input_tar.next()
fileobj = input_tar.extractfile(tarinfo)

# Write output file.
output_tar = tarfile.open('foo.tar', 'w')
output_tar.addfile(tarinfo, fileobj)

input_tar.close()
output_tar.close()

rawDescription: Python: tarfile stream

description: Python: tarfile stream


code:
import re, sys

# your convert function goes here

regex = re.compile(r'(\d+)')
for line in sys.stdin:
  sys.stdout.write(regex.sub(lambda m:
  convert(int(m.group(1))), line))

rawDescription: Regex Subtitution in Python

description: Regex Subtitution in Python


code:
import re
r = re.compile(r'(\w+(\W+\w+)?)(\W+with\b|\Z)')
r.search('bar baz baf bag').group(1)
r.search('bar baz baf with bag').group(1)
r.search('bar baz baf without bag').group(1)
r.search('bar with bag').group(1)
r.search('bar with baz baf with bag').group(1)

rawDescription: Regex match words and end of string

description: Regex match words and end of string


code: return ", ".join([str(x) for x in things])

rawDescription: returning a list in a single line in python

description: Returning a list in a single line in python


code:
import pylab as plt

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

def get_axis_limits(ax, scale=.9):
    return ax.get_xlim()[1]*scale, ax.get_ylim()[1]*scale

ax1.annotate('A', xy=get_axis_limits(ax1))
ax2.annotate('B', xy=get_axis_limits(ax2))
plt.show()

rawDescription: add label to subplot in matplotlib

description: Add label to subplot in matplotlib


rawDescription: Is there a way to substring a string in Python?


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

class Main(QWidget):
    def __init__(self,parent=None):
        QWidget.__init__(self)
        self.setFixedSize(600,500)

        self.tabBar=QTabBar(self)
        self.tabBar.setStyleSheet("QTabBar::tab{width:400px;}")
        self.tabBar.setExpanding(True)

        self.layout=QVBoxLayout(self)
        self.layout.addWidget(self.tabBar)

        self.tabBar.addTab("Kontext Menu")
        self.tabBar.addTab("Settings in detail")
        self.tabBar.addTab("Help and tips")
        self.tabBar.addTab("About")
        self.tabBar.addTab("Credits")

        self.show()

if __name__ == '__main__':
    app=QApplication(sys.argv)
    sd=Main()
    app.exec()

rawDescription: QTabBar neither expands totally nor spaces tabs equally


code:
def flush_logger(logger):
    c = logger
    while c:
        for hdlr in c.handlers:
            try:
                hdlr.flush()
            except AttributeError:
                pass
        if not c.propagate:
            c = None    #break out
        else:
            c = c.parent

rawDescription: how to notify python logging handlers that a crash may occur and logs should be flushed?

description: Notify python logging handlers that a crash may occur and logs should be flushed


code:
res = {}
for item in l:
    res.setdefault(item['a'], []).append(item)

rawDescription: Python: group list items in a dict

description: Python: group list items in a dict


code:
out = []
for x in xrange(1,21):
    x = x +1
    g = grouped.nth(x).sum()
    out.append((x +1, ("%1.3f " % g)))

pd.DataFrame(out)

rawDescription: Extract float from 'for loop', write to dataframe in python


code:
class ArticleSerializer(serializers.HyperlinkedModelSerializer):
    user = UserSerializer(many=False, read_only=True)
    teaser = serializers.SerializerMethodField('get_teaser')

    class Meta:
        model = models.Article
        fields = (
            'id'
            ,'title'
            , 'date_added'
            , 'user'
            , 'teaser'
        )

    def get_teaser(self, obj):
        return force_text(obj.content[:20])

rawDescription: Modifying the output from a serializer in the Django Rest Framework


code:
from IPython.core.display import HTML
...
...
def foo():
    raw_html = "
Yah, rendered HTML
"
    return HTML(raw_html)

rawDescription: Make output cells like Markdown

description: Make output cells like Markdown


rawDescription: How to extend an array with linear interpolation

description: Extend an array with linear interpolation


code:
class SubjectSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=200)

    class Meta:
        fields = [
            'name',
        ]

class StudentSerializer(serializers.Serializer):
    first_name = serializers.CharField(max_length=200)
    middle_name = serializers.CharField(max_length=200)
    last_name = serializers.CharField(max_length=200)
    # nested relationship
    subjects = SubjectSerializer(many=True)

    class Meta:
        fields = [
            'first_name',
            'last_name',
            'middle_name',
            'subjects'
        ]

rawDescription: How will I serialize complex Django Models to json?


code: minimize(func, [-1.0,1.0], args=(-1.0,), jac=func_deriv, constraints=cons, method='SLSQP', options={'disp': True})

rawDescription: Python constrained non-linear optimization


code:
import csv

Keyfile = open('keyfile.csv', 'rb')
file_out = csv.reader(open('file1.csv', 'rb'), delimiter=",")
file_in = csv.writer(open('file2.csv', 'w'), delimiter=",")

mapDict = {}

# the first line in KeyFile convert to dict
reader = csv.reader(Keyfile, delimiter=',')
for i, v in enumerate(reader.next()):
    if v != ' ':
        mapDict[i] = int(v)

# re-index the row in file_in based on mapDict
for row in file_out:
    file_in.writerow([row[c] for c in mapDict.values()])

rawDescription: Not able to write to all rows in .csv file in Python?


code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import BoundaryNorm
a=np.random.randn(2500).reshape((50,50))

# define the colormap
cmap = plt.get_cmap('PuOr')

# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# create the new map
cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

# define the bins and normalize and forcing 0 to be part of the colorbar!
bounds = np.arange(np.min(a),np.max(a),.5)
idx=np.searchsorted(bounds,0)
bounds=np.insert(bounds,idx,0)
norm = BoundaryNorm(bounds, cmap.N)

plt.imshow(a,interpolation='none',norm=norm,cmap=cmap)
plt.colorbar()
plt.show()

rawDescription: Colorplot that distinguishes between positive and negative values


code:
code = ord(self.trackLabel.get())
self.trackLabel.set(chr(code+1))

rawDescription: Increment a character's ascii code

description: Increment a character's ascii code


code:
from django.db import models

class SuperModel(models.Model):
    class Meta:
        app_label = 'APP_ROOT'

rawDescription: Python module import redefining namespace/__repr__ for refactoring


code:
state_license = {u'License ': u'29393, 25633',
                 u'Expiration': u'08-01-2012, 04-02-2012',
                 u'Trade': u'Registered Contractor, Plumber'}
{key: value.split(", ") for key, value in state_license.items()}

rawDescription: Converting a dictionary value in to a list?


code:
class Meta:
    unique_together = ('id', 'password', 'device_id')

rawDescription: Django Model Field Uniqueness Validation


code:
# method 1
answer = input("What's up, doc? ")[:10]  # no more than 10 characters

# method 2
while True:
    answer = input("What's up, doc? ")
    if len(answer) <= 10:
        break
    else:
        print("Too much info - keep it shorter!")

rawDescription: How do I limit the amount of letters in a string

description: Limit the amount of letters in a string


code:
#Assuming df is a pandas data frame with columns 'x', 'y', and 'label'
for key,grp in df.groupby('label'):
    plt.plot(grp.x,grp.y,'o-',label = key)
plt.legend(loc = 'best')

rawDescription: How to create multiple series scatter plot with connected points using seaborn?

description: Create multiple series scatter plot with connected points using seaborn


code: context = {'books': Books.objets.all()}

rawDescription: Send additional variables to page response in Django CMS


code:
class Event(object):
    __metaclass__ = ABCMeta
    def __init__(self):
        self.type = self.get_full_type()

    @classmethod
    def get_full_type(cls):
        return None

    def as_dict(self):
        return self.__dict__

class BaseEvent(Event):
    __metaclass__ = ABCMeta
    SUB_TYPE = None

    @classmethod
    def get_full_type(cls):
        super_type = cls.get_super_type()
        base_type = super_type.get_full_type()
        if base_type:
            return '.'.join([base_type, cls.SUB_TYPE])
        else:
            return cls.SUB_TYPE

    @classmethod
    def get_super_type(cls):
        return cls.__base__

rawDescription: How to make this code work in python 2

description: Make this code work in python 2


code:
from sympy import sympify
sympify('a&b')
sympify('a|b')
sympify('~a')

rawDescription: sympy: how to sympify logical "NOT"

description: Sympy: how to sympify logical "NOT"


code:
width = 40
'{0:<{width}}'.format('aa', width=width)

rawDescription: How to format string width with a runtime calculated variable?

description: Format string width with a runtime calculated variable


rawDescription: Remove unicode characters

description: Remove unicode characters


code:
pattern = re.compile(r"\[.*?([0-9]+(?:\.[0-9]+)?).*?\]")
pre, post = [float(x) for x in re.findall(pattern, thestring)]

rawDescription: Best means of extracting values from the following string in python?


code:
from PIL import ImageGrab
import win32gui

toplist, winlist = [], []
def enum_cb(hwnd, results):
    winlist.append((hwnd, win32gui.GetWindowText(hwnd)))
win32gui.EnumWindows(enum_cb, toplist)

firefox = [(hwnd, title) for hwnd, title in winlist if 'firefox' in title.lower()]
# just grab the hwnd for first window matching firefox
firefox = firefox[0]
hwnd = firefox[0]

win32gui.SetForegroundWindow(hwnd)
bbox = win32gui.GetWindowRect(hwnd)
img = ImageGrab.grab(bbox)
img.show()

rawDescription: How to Get a Window or Fullscreen Screenshot in Python 3k? (without PIL)


code:
row_a = ["rowname","items1","items2"]
def set_rowname(row, value):
    row[1] = value
set_rowname(row_a, "another_rowname")

rawDescription: Return lvalue from function in Python?

description: Return lvalue from function in Python


code: list_foo = [ [goo] for j, goo in enumerate(x) if (v1[j] == v2[j]) ]

rawDescription: Python: List of lists with condition between arrays and no for loop


code:
t = Table(
    't', metadata,
    Column('id', Integer, primary_key=True),
    # ...
    prefixes=['TEMPORARY'],
)

rawDescription: Can I CREATE TEMPORARY TABLE in SQLAlchemy without appending to Table._prefixes?


code:
class GameResource(ModelResource):
    activities = fields.ToManyField(ActivityResource, 'activities', full=True)

rawDescription: POST multiple objects in one TastyPie API request


code:
def read_file():
    with open("most_recent_follower.txt", "r") as f:
        SMRF1 = f.readlines()
    return SMRF1

initial = read_file()
while True:
    current = read_file()
    if initial != current:
        for line in current:
            if line not in initial:
                print(line)
        initial = current

rawDescription: Check if a file is modified in Python

description: Check if a file is modified in Python


code:
next(file)
next(file)

rawDescription: skipping a line while reading a file with a for loop

description: Skipping a line while reading a file with a for loop


rawDescription: ForeignKey form restrictions in Django

description: ForeignKey form restrictions in Django


code: url = "http://www.keywordspy.com/research/tab.aspx?name=keyword-similar&q=" + name + "&market=it"

rawDescription: BeautifulSoup get content of a row table


code: nthRoot = Decimal(x) ** (Decimal(1.0) / Decimal(n) )

rawDescription: calculating n-th roots using Python 3's decimal module

description: Calculating n-th roots using Python 3's decimal module


code:
waypoints = {'c': 3.0}
if E1.get():
    waypoints['Way point1']: (2, E1.get())
if E2.get():
    waypoints['Way point2']: (2, E2.get())

data = [waypoints]

rawDescription: Omit empty way point entry from JSON

description: Omit empty way point entry from JSON


code:
# hvad compatibility for rest_framework - JHA

class TranslatableModelSerializerOptions(serializers.ModelSerializerOptions):
    def __init__(self, meta):
        super(TranslatableModelSerializerOptions, self).__init__(meta)
        # We need this ugly hack as ModelSerializer hardcodes a read_only_fields check
        self.translated_read_only_fields = getattr(meta, 'translated_read_only_fields', ())
        self.translated_write_only_fields = getattr(meta, 'translated_write_only_fields', ())

class HyperlinkedTranslatableModelSerializerOptions(serializers.HyperlinkedModelSerializerOptions):
    def __init__(self, meta):
        super(HyperlinkedTranslatableModelSerializerOptions, self).__init__(meta)
        # We need this ugly hack as ModelSerializer hardcodes a read_only_fields check
        self.translated_read_only_fields = getattr(meta, 'translated_read_only_fields', ())
        self.translated_write_only_fields = getattr(meta, 'translated_write_only_fields', ())

class TranslatableModelMixin(object):
    def get_default_fields(self):
        fields = super(TranslatableModelMixin, self).get_default_fields()
        fields.update(self._get_translated_fields())
        return fields

    def _get_translated_fields(self):
        ret = OrderedDict()
        trans_model = self.opts.model._meta.translations_model
        opts = trans_model._meta

        forward_rels = [field for field in opts.fields
                        if field.serialize and not field.name in ('id', 'master')]

        for trans_field in forward_rels:
            if trans_field.rel:
                raise RuntimeError()
            field = self.get_field(trans_field)
            if field:
                ret[trans_field.name] = field

        for field_name in self.opts.translated_read_only_fields:
            assert field_name in ret
            ret[field_name].read_only = True

        for field_name in self.opts.translated_write_only_fields:
            assert field_name in ret
            ret[field_name].write_only = True

        return ret

    def restore_object(self, attrs, instance=None):
        new_attrs = attrs.copy()
        lang = attrs['language_code']
        del new_attrs['language_code']

        if instance is None:
            # create an empty instance, pre-translated
            instance = self.opts.model()
            instance.translate(lang)
        else:
            # check we are updating the correct translation
            tcache = self.opts.model._meta.translations_cache
            translation = getattr(instance, tcache, None)
            if not translation or translation.language_code != lang:
                # nope, get the translation we are updating, or create it if needed
                try:
                    translation = instance.translations.get_language(lang)
                except instance.translations.model.DoesNotExist:
                    instance.translate(lang)
                else:
                    setattr(instance, tcache, translation)

        return super(TranslatableModelMixin, self).restore_object(new_attrs, instance)

class TranslatableModelSerializer(TranslatableModelMixin, serializers.ModelSerializer):
    _options_class = TranslatableModelSerializerOptions

class HyperlinkedTranslatableModelSerializer(TranslatableModelMixin,
                                             serializers.HyperlinkedModelSerializer):
    _options_class = HyperlinkedTranslatableModelSerializerOptions

rawDescription: Django Rest Framework and Django-Hvad

description: Django Rest Framework and Django-Hvad


code:
# create a dict containing index and corresponding item
tempDict = {}
for item in self.sensors.selectedItems():
    tempDict[self.sensors.row(item)] = item
# sort the index and store as a list (`sorted()` does this for you)
tempIndexes = sorted(tempDict)

# define a list to contain the resultant items i.e sorted items
resultItems = []

for index in tempIndexes:
    resultItems.append(tempDict[index])

for it in resultItems:
    print(it.text())

rawDescription: QListWidget selected items orderd by row


code:
checkbox_directory_pairs = [
    (self.folderactive, 'Desktop'),
    (self.folderactive_2, 'Documents'),
    (self.folderactive_3, 'Downloads'),
    ...
]

for checkbox, directory in checkbox_directory_pairs:
    if checkbox.isChecked:
        folders.createDir(directory)
    else:
        folders.deleteDir(directory)

rawDescription: Alternatives to long if statement

description: Alternatives to long if statement


code:
headers = {'ID': '1234' , 'Password' : 'ABC' }
requests.get("http://url.com/curl", headers=headers)

rawDescription: How to convert curl command to Requests

description: Convert curl command to Requests


code:
try:
    command_string = 'my_virusscanner -parameters ' + uploaded_file
    result = subprocess.check_output(command_string,stderr=subprocess.STDOUT,shell=True)
    #if needed, do something with "result"
except subprocess.CalledProcessError as e:
    #if your scanner gives an error code when detecting a virus, you'll end up here
    pass
except:
    #something else went wrong
    #check sys.exc_info() for info
    pass

rawDescription: PDF's and viruses in Django

description: PDF's and viruses in Django


code:
import os
from textwrap import dedent

def check_extensions():
    """check if the C module can be build by trying to compile a small
    program against the libyaml development library"""

    import tempfile
    import shutil

    import distutils.sysconfig
    import distutils.ccompiler
    from distutils.errors import CompileError, LinkError

    libraries = ['yaml']

    # write a temporary .c file to compile
    c_code = dedent("""
    #include <yaml.h>

    int main(int argc, char* argv[])
    {
        yaml_parser_t parser;
        parser = parser;  /* prevent warning */
        return 0;
    }
    """)
    tmp_dir = tempfile.mkdtemp(prefix = 'tmp_ruamel_yaml_')
    bin_file_name = os.path.join(tmp_dir, 'test_yaml')
    file_name = bin_file_name + '.c'
    with open(file_name, 'w') as fp:
        fp.write(c_code)

    # and try to compile it
    compiler = distutils.ccompiler.new_compiler()
    assert isinstance(compiler, distutils.ccompiler.CCompiler)
    distutils.sysconfig.customize_compiler(compiler)

    try:
        compiler.link_executable(
            compiler.compile([file_name]),
            bin_file_name,
            libraries=libraries,
        )
    except CompileError:
        print('libyaml compile error')
        ret_val = None
    except LinkError:
        print('libyaml link error')
        ret_val = None
    else:
        ret_val = [
            Extension(
                '_yaml',
                sources=['ext/_yaml.c'],
                libraries=libraries,
                ),
        ]
    shutil.rmtree(tmp_dir)
    return ret_val

rawDescription: setup.py check if non-python library dependency exists

description: Setup.py check if non-python library dependency exists


code:
class Aclass(object):
    p = None
    @classmethod
    def init_p(cls, value):
        p = value
    @classmethod
    def meth1(cls):
        # some code
        res = cls.meth2()
        # some more code w/ res
    @classmethod
    def meth2(cls):
        # do something with p
        pass

from a import Aclass as ac

ac.init_p(some_command_line_argument_value)

ac.meth1()
ac.meth2()

rawDescription: How to avoid excessive parameter passing?

description: Avoid excessive parameter passing


rawDescription: python re split string by alpha digit and symbol

description: Python re split string by alpha digit and symbol


code:
product = 1
for item in some_list:
    product *= factorial(item)

rawDescription: Find factorial of each element in a list and multiply them


code: String2 = String + "{0}, {0}".format(String1)

rawDescription: Do I need to pass multiple variable in string concatenation


code:
def visit(node,indent):
    # Load your node data
    print("{0} {1}".format("-" * indent, node.columns[0])) # Do something with your data
    # Unload your node data
    if len(node.children) > 0 :
        return (node.children[0], indent+1) # Visit the first child, if there is one
    while node.next is None: # If no sibling, your parent is done
        node = node.parent
        indent -= 1
        if node is None: # Root node reached, end the traversal
            return None
    return (node.next, indent) # Visit your next sibling, if there is one

cursor = (root_node, 0)
while cursor is not None:
    cursor = visit(*cursor)

rawDescription: Iterative printing of a tree model

description: Iterative printing of a tree model


code:
from Tkinter import *

master = Tk()

w = Label(master, text="Hello, world!")
w.pack()

mainloop()

rawDescription: How to set font of a messagebox with Python tkinter?

description: Set font of a messagebox with Python tkinter


rawDescription: make from a list the dictionary lists by key

description: Make from a list the dictionary lists by key


code:
class downloadAllToWorldThread(threading.Thread):
    def __init__(self, threadID, name, counter, *args):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.args = args
    def run(self):
        print('Args are: {}'.format(self.args))
        downloadToMyHouse(self.args[0],self.args[1],self.args[2])

def downloadAllToWorld(aaa,bbb,ccc,ddd,eee):
    thread1 = downloadAllToWorldThread(1,"blah1-1", 1, ccc, ddd, eee)

rawDescription: Python pass argument to Thread class

description: Python pass argument to Thread class


code:
import requests
import json

html = requests.get('http://steamcommunity.com/market/listings/730/AK-47%20%7C%20Redline%20%28Field-Tested%29/render?start=0&count=5&currency=&language=english')

# Load the parsed page into a JSON object.
steam_json = json.loads(html.text)

# Extract whatever you want like this:
success_status = steam_json['success']

rawDescription: How do i parse this URL with beautiful Soup? What format is the URL?

description: Parse this URL with beautiful Soup? What format is the URL


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

app = QApplication(sys.argv)

data = ['folder1/file1', 'file2', 'file3', 'folder2/file4']

treeWidget = QTreeWidget()
treeWidget.setColumnCount(1)
treeWidget.setMinimumSize(600, 400)

items = []

for item in data:
    itemparts = item.split('/')

    entry = QTreeWidgetItem(None, [itemparts[0]])
    partentitem = entry

    if len(itemparts) > 1:
        for i in itemparts[1:]:
            childitem = QTreeWidgetItem(None, [i])
            partentitem.addChild(childitem)
            partentitem = childitem

    items.append(entry)

treeWidget.insertTopLevelItems(0, items)

treeWidget.show()
app.exec_()

rawDescription: Qt directory tree from data

description: Qt directory tree from data


code:
map = numpy.random.randint(10, size=(2 * World.MAP_WIDTH, 2 * World.MAP_HEIGHT))
map[0 : World.MAP_WIDTH / 4, :] = -1
map[7 * World.MAP_WIDTH / 4 : 2 * World.MAP_WIDTH, :] = -1
map[:, 0 : World.MAP_HEIGHT / 4] = -1
map[:, 7 * World.MAP_HEIGHT / 4 : 2 * World.MAP_WIDTH] = -1

rawDescription: How do I slice a Numpy array up to a boundary?

description: Slice a Numpy array up to a boundary


code:
import wx

class Frame(wx.Frame):
    def __init__(self, title):
        wx.Frame.__init__(self, None, title=title, size=(350,200))
        self.text = wx.TextCtrl(self, -1, style=wx.TE_READONLY)
        self.btn1 = wx.Button(self, -1, "Right button")
        self.btn2 = wx.Button(self, -1, "Wrong button")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.text, 1, wx.ALL | wx.EXPAND, 5)
        sizer.Add(self.btn1, 1, wx.ALL | wx.EXPAND, 5)
        sizer.Add(self.btn2, 1, wx.ALL | wx.EXPAND, 5)
        self.SetSizer(sizer)
        self.Fit()

        self.Bind(wx.EVT_BUTTON, self.RightButtonPress, self.btn1)
        self.Bind(wx.EVT_BUTTON, self.WrongButtonPress, self.btn2)

    def RightButtonPress(self, evt):
        self.text.AppendText("Right!")

    def WrongButtonPress(self, evt):
        self.text.Clear()
        self.text.AppendText("Press again!")

app = wx.App()
top = Frame("Hello World")
top.Center()
top.Show()
app.MainLoop()

rawDescription: Changing wx.TextCtrl style flags dynamically


code:
# start the two threads
t1.start()
t2.start()

# wait until both ended
t1.join()
t2.join()

# then start the third
t3.start()

rawDescription: Python thread synchronisation

description: Python thread synchronisation


code:
from Tkinter import *

class ScrollableFrame(Frame):
    def __init__(self, parent, minimal_canvas_size, *args, **kw):
        '''
        Constructor
        '''

        Frame.__init__(self, parent, *args, **kw)

        self.minimal_canvas_size = minimal_canvas_size

        # create a vertical scrollbar
        vscrollbar = Scrollbar(self, orient = VERTICAL)
        vscrollbar.pack(fill = Y, side = RIGHT, expand = FALSE)

        # create a horizontal scrollbar
        hscrollbar = Scrollbar(self, orient = HORIZONTAL)
        hscrollbar.pack(fill = X, side = BOTTOM, expand = FALSE)

        #Create a canvas object and associate the scrollbars with it
        self.canvas = Canvas(self, bd = 0, highlightthickness = 0, yscrollcommand = vscrollbar.set, xscrollcommand = hscrollbar.set)
        self.canvas.pack(side = LEFT, fill = BOTH, expand = TRUE)

        #Associate scrollbars with canvas view
        vscrollbar.config(command = self.canvas.yview)
        hscrollbar.config(command = self.canvas.xview)

        # set the view to 0,0 at initialization

        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

        self.canvas.config(scrollregion='0 0 %s %s' % self.minimal_canvas_size)

        # create an interior frame to be created inside the canvas

        self.interior = interior = Frame(self.canvas)
        interior_id = self.canvas.create_window(0, 0, window=interior,
                anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar

        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (max(interior.winfo_reqwidth(), self.minimal_canvas_size[0]), max(interior.winfo_reqheight(), self.minimal_canvas_size[1]))
            self.canvas.config(scrollregion='0 0 %s %s' % size)
            if interior.winfo_reqwidth() != self.canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                self.canvas.config(width = interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

class my_gui(Frame):

    def __init__(self):
        # main tk object
        self.root = Tk()

        # init Frame
        Frame.__init__(self, self.root)

        minimal_canvas_size = (500, 500)

        # create frame (gray window)

        self.frame = ScrollableFrame(self.root, minimal_canvas_size)
        self.frame.pack(fill=BOTH, expand=YES)

        self.__add_plot()

    def __add_plot(self):
        # create a rectangle
        self.frame.canvas.create_polygon(10, 10, 10, 150, 200, 150, 200, 10,  fill="gray", outline="black")

    def mainLoop(self):
        # This function starts an endlos running thread through the gui
        self.root.mainloop()

    def __quit(self):
        # close everything
        self.root.quit()

# init gui
my_gui = my_gui()
# execute gui
my_gui.mainLoop()

rawDescription: resizeable scrollable canvas with tkinter

description: Resizeable scrollable canvas with tkinter


code:
from dateutil.parser import parse
dt = parse('Sat, 16 Jan 2016 07:50:17 GMT')
print(dt)
print(type(dt))

rawDescription: Python identify timestamp format from string


rawDescription: is there any way to jump to a specified function name using help() command in python

description: Is there any way to jump to a specified function name using help() command in python