code:
import matplotlib.pyplot as plt

def plot_graph1():
    xvals = range(4)
    xnames=["one","two","three","four"]
    yvals = [10,30,40,20]
    width = 0.25
    yinterval = 10

    figure = plt.figure()
    plt.grid(True)
    plt.xlabel('x vals')
    plt.ylabel('y vals')

    plt.bar(xvals, yvals, width=width, align='center')
    plt.xticks(xvals, xnames)
    plt.yticks(range(0,max(yvals),yinterval))
    plt.xlim([min(xvals) - 0.5, max(xvals) + 0.5])

    figure.savefig("barchart.png",format="png")
    plt.show()

if __name__=='__main__':
    plot_graph1()

rawDescription: how to put gap between y axis and first bar in vertical barchart matplotlib

description: Put gap between y axis and first bar in vertical barchart matplotlib


rawDescription: How to calculate mean and max increase, decrease of time series in python

description: Calculate mean and max increase, decrease of time series in python


code:
import string
chars = string.ascii_uppercase + string.digits
genned_chars=[''.join(i) for i in itertools .product(chars,repeat=3)]

rawDescription: Iterate Array/List in Python for Alpha Numeric


code:
import numpy as np
groups = [[1,2],[3,4,5]]
map(np.mean, groups)

rawDescription: NumPy: Calculate mean of certain elements in array


code: subprocess.Popen(['ping www.google.com > /dev/null &'], shell=True, preexec_fn=os.setsid)

rawDescription: create background process with Python's Popen

description: Create background process with Python's Popen


code:
import csv

f = open("iter.csv", "r")
g = open("out.csv", "w", newline="")
transpose_columns = ['date1', 'date2', 'date3']
target_columns = ['date', 'value']
reader = csv.DictReader(f)
writer = csv.DictWriter(g, fieldnames=[a for a in reader.fieldnames
                                       if a not in transpose_columns] + target_columns,
                        extrasaction='ignore')
writer.writeheader()
for row in reader:
    for col in transpose_columns:
        row[target_columns[0]] = col
        row[target_columns[1]] = row[col]
        writer.writerow(row)
f.close()
g.close()

rawDescription: Manipulating data in csv using itertools (python)


code:
# New stuff:
import numpy as np
frameN = 50  # To set angle in first loop iteration
speed = 14  # initial speed in whatever unit the stimulus use.
angle = 45  # initial angle in degrees
x_change = np.cos(angle) * speed  # initial
y_change = np.sin(angle) * speed  # initial

while True:
    # More new stuff: Change direction angle (in degrees)
    if frameN == 50:
        angle_current = np.rad2deg(np.arctan(y_change / float(x_change)))  # float to prevent integer division
        angle_change = np.random.randint(-180, 180)  # change interval to your liking or set to a constant value or something
        angle = angle_current + angle_change  # new angle

        x_change = np.cos(angle) * speed
        y_change = np.sin(angle) * speed
        frameN = 0
    frameN += 1

    dot1.pos+=(x_change,y_change)

    if dot1.pos[0] > 790 or dot1.pos[0] < -790:
        x_change = x_change * -1
    if dot1.pos[1] > 440 or dot1.pos[1] < -440:
        y_change = y_change * -1

    dot1.draw()
    win.flip()

    if event.getKeys(keyList=["escape"]):
        core.quit()

rawDescription: Getting dot to move along curved trajectory


code:
import numpy as np
arrs = [np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9])]
arrs
arr2d = np.array(arrs)
arr2d.shape
arr2d

rawDescription: Numpy list of 1D Arrays to 2D Array

description: Numpy list of 1D Arrays to 2D Array


code: sum(my_list[i] for i in (0, 2, 3))

rawDescription: Python: access list value by reference

description: Python: access list value by reference


code:
def greet(f,name):
    d = dummy()
    f(d, name)

greet(dummy.func1,'Bala')

rawDescription: How to pass member function as argument in python?

description: Pass member function as argument in python


code:
import matplotlib.pyplot as plt

# activate usage of latex
plt.rcParams['text.usetex'] = True

# generate a simple graph
fig, ax = plt.subplots(1,1, figsize=(6,3))
ax.text(0.5, 0.5, r"\textit{\textbf{one}} two (on the axes)")
fig.text(1., 1., r"\textit{\textbf{one}} two (on the figure)",
        horizontalalignment='right', verticalalignment='top')

plt.show()

rawDescription: change text style inline in matplotlib

description: Change text style inline in matplotlib


code:
from sqlalchemy import create_engine
engine = create_engine('postgresql://user:pass@host:5433/MYDB')
df.to_sql('table_name', engine)

rawDescription: How do I write a pandas dataframe to Vertica?

description: Write a pandas dataframe to Vertica


code:
def a(s1, s2):
    s1 = '{0}test{0}'.format(s1)
    s2 = '{}({})'.format(s1, s2)
    return s1, s2

foo, bar = a(foo, bar)

rawDescription: Pascal "var parameter" in Python

description: Pascal "var parameter" in Python


code:
adj = numpy.random.randint(0, 2, (100, 100)) # a random directed graph
g = Graph()
g.add_edge_list(transpose(adj.nonzero()))

rawDescription: Create a weighted graph from an adjacency matrix in graph-tool, python interface


code:
import re
abc = re.sub(r"['\[\]]", '', abc)

rawDescription: Deletion of multiple characters inside of a string


code:
weapons = { 'Sword': 10, 'Pike': 13 }
armors = { 'Crude': 2, 'Heavy': 5 }

rawDescription: Python Summing variables in a list

description: Python Summing variables in a list


code: sorted(y1, key=x.index)

rawDescription: Sorting list of strings based on another list of strings


code: ''.join(filter(str.isdigit, '12454v'))

rawDescription: Delete letters from string

description: Delete letters from string


code:
ax1.set_title('title1', color='c', rotation='vertical',x=-0.1,y=0.5)
ax2.set_title('title2', color='c', rotation='vertical',x=-0.1,y=0.5)

rawDescription: Python- Matplotlib Moving Graph title to the y axis


rawDescription: Python Data structure index Start at 1 instead of 0?


code:
import os
import pwd
pwd.getpwuid(os.getuid())[4]

rawDescription: full unix username of a user

description: Full unix username of a user


code:
timed_events = {}
# Count them up
for event in events_from_database:
    timed_events[event] = timed_events.setdefault(event, 0) + 1

# Form a new list with the original data plus the count
aggregate_list = [(evt[0], evt[1], count) for evt,count in events.items()]

rawDescription: How can I reshape and aggregate list of tuples in Python?

description: Reshape and aggregate list of tuples in Python


code: donors = qs.values('month').annotate(count=Count('email', distinct=True)).order_by('month')

rawDescription: Django queryset group by and count distincts


rawDescription: Accessing files in python: extra spaces

description: Accessing files in python: extra spaces


code:
class Attribute(object):
    pass

class MyClass(object):
    def __init__(self):
        self.attribute1 = Attribute()

variable = MyClass()
variable.attribute1.attribute2 = 5

rawDescription: Classes with multiple attribute levels [Beginner]


code:
locations = {1: (3, 5), 2: (4,3)}

def get_location(num):
    x, y = locations.get(num, (-1, -1, ))
    if coords != (-1,-1):
       return board[x,y]
    else:
       return None

rawDescription: Store Array Locations in Variable

description: Store Array Locations in Variable


code:
class MyResource(Resource):
  # ...
  def render(self, request):
    session = request.getSession()
    if not hasattr(session, 'count'):
      session.count = itertools.count()
    request.write(u"Count is %s" % (session.count.next(),))

rawDescription: Twisted time counter

description: Twisted time counter


code:
class SomeModelAdmin(admin.ModelAdmin):
    ...
    def has_delete_permission(self, request, obj=None):
        """
        Return False for events in the past
        """
        if obj is None:
            # obj is None in the model admin changelist view
            return False
        now = datetime.datetime.now()
        if obj.end < now:
            return False # past events cannot be deleted
        else:
            return super(SomeModelAdmin, self).has_delete_permission(request, obj)

rawDescription: Django: Getting succefully deleted message even if deletion is prevented


code:
dateInput = raw_input("Date? (MM/DD/YYYY) ").strip()
amount_re = re.compile(r"(^%s)" % (dateInput,))
cell_list = wks.findall(amount_re)

rawDescription: how do I return cell values in a spreadsheet based on user input in Python?

description: Return cell values in a spreadsheet based on user input in Python


code: filename = unicodedata.normalize('NFC', unicode(filename, 'utf-8')).encode('utf-8')

rawDescription: Unicode encoding for filesystem in Mac OS X not correct in Python?


code:
someVar = "none"

def someFunction():
    global someVar
    if whatever is whatever:
        someVar = "somethingElse"
    return someVar

rawDescription: Mutating a global variable from within a function


code:
f = open("thefile.txt")

f.read(1) # read the first opening bracket

nf = open("newfile.txt","w")
nf.write("[\n")

currentline = ""
for line in f:
    currentline += line[:-1]
    if line[-2] == "]":
        if line [-3] == "]": #last line"
            nf.write(currentline[:-1])
            break
        nf.write(currentline + "\n")
        currentline = ""
nf.write("\n]")

rawDescription: How to combine lines within square braces?

description: Combine lines within square braces


code:
import wx

class MainWindow(wx.Frame):
  def __init__(self,parent,title):
    wx.Frame.__init__(self,parent,title=title,size=(200,-1))
    self.sizer = wx.BoxSizer(wx.HORIZONTAL)
    self.buttons = [
      wx.Button(self,-1,"Button &One"),
      wx.Button(self,-1,"Button &&Two"),
    ]
    for btn in self.buttons:
      self.sizer.Add(btn,1,wx.EXPAND)
    self.SetSizer(self.sizer)
    self.SetAutoLayout(1)
    self.sizer.Fit(self)
    self.Show()

app = wx.App(False)
frame = MainWindow(None,"Hello Ampersand")
app.MainLoop()

rawDescription: How to write a "&" in button text in wxpython

description: Write a "&" in button text in wxpython


code:
import cherrypy
#from cherrypy.lib import sessions

class HelloWorld(object):

    @cherrypy.expose
    def default(self, *args, **kwargs):
        out = ''
        for key, value in kwargs.items():
            out += key + '=' + value + '\n'
            cherrypy.session[key] = value

        #you'll also need to store a value in session
        cherrypy.session['Something'] = 'asdf'

        print(cherrypy.session.id)
        return out

cherrypy.config.update({'tools.sessions.on': True,
                        'tools.sessions.storage_type': "File",
                        'tools.sessions.storage_path': 'sessions',
                        'tools.sessions.timeout': 10
               })

cherrypy.quickstart(HelloWorld())

rawDescription: How to use sessions in cherrypy?

description: Use sessions in cherrypy


code:
from itertools import takewhile, dropwhile, chain, islice

with open('input') as fin, open('output', 'w') as fout:
    fout.writelines(chain(
        takewhile(lambda L: L != '---From here---\n', fin),
        ['Woo Hoo!\n'],
        islice(dropwhile(lambda L: L != '---To here---\n', fin), 1, None)
        )
    )

rawDescription: Replace all lines [fromString ,toString] in file


code:
import pexpect
proc = pexpect.spawn('./myclient <arg1> <arg2> <arg3>')
proc.logfile = the_logfile_you_want_to_use
proc.expect(['the string that tells you that myclient is waiting for input'])
proc.sendline('line you want to send to myclient')
proc.expect(['another line you want to wait for'])
proc.sendline('quit') # for myclient to quit
proc.expect([pexpect.EOF])

rawDescription: Scripting and interactive terminal client in python


code:
vowels = 'aeiou'
def vowel_count(txt):
    counts = map(txt.count, vowels)
    return ", ".join(vowels) + " appear, respectively, " + ",".join(map(str, counts)) + " times"

rawDescription: function vowel_count that take a string as inputs count the number of occurrence and prints the occurrence

description: Function vowel_count that take a string as inputs count the number of occurrence and prints the occurrence


rawDescription: How to match a regex in python, either completely or partially

description: Match a regex in python, either completely or partially


code: next(filter(lambda x: x == 35, [3, 5, 5, 8]), None)

rawDescription: Return the first element or None from filter


code:
class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    boston_addresses = relationship("Address",
                    primaryjoin="and_(User.id==Address.user_id, "
                        "Address.city=='Boston')")

class Address(Base):
    __tablename__ = 'address'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('user.id'))

    street = Column(String)
    city = Column(String)
    state = Column(String)
    zip = Column(String)

rawDescription: SQLAlchemy Conditional Relationships

description: SQLAlchemy Conditional Relationships


code:
s = 'id,obj1,"string, etc",obj2'
import csv
dict(enumerate(next(csv.reader([s])),start=1))

rawDescription: Splitting a string with exceptions

description: Splitting a string with exceptions


code:
import re

comments = re.findall('#.*?\n', allLines)
for item in re.findall('/\*.?*\*/', allLines):
    for row in item.split('\n'):
        comments.append(row)
print(len(comments))

rawDescription: How to count the comment lines in a java file?

description: Count the comment lines in a java file


code:
from matplotlib import pyplot as plt

plt.boxplot([[1,4],[2,5],[3,6]], positions=[2,4,5.5])

rawDescription: Matplotlib boxplot x axis

description: Matplotlib boxplot x axis


rawDescription: Weird Output Value: b'[value]\r\n' - Python Serial Read


rawDescription: Performance improvement python

description: Performance improvement python


code: df['columnName'] = df.index

rawDescription: Excel to Pandas DataFrame using first column as index


code:
r = r"([^:|]+)\s*:\s*([^:|]+)"
st = "full name:jones hardy|city and dialling code :london 0044"
re.findall(r, st)
st="name:jones|location:london|age:23"
re.findall(r, st)

rawDescription: regex match for words with spaces in between them

description: Regex match for words with spaces in between them


code:
from datetime import datetime

starttime = datetime.strptime('2015-06-22', '%Y-%m-%d')
endtime = datetime.strptime('2015-06-23', '%Y-%m-%d')
query = Event.query.filter(Event.starttime>=starttime, Event.endtime<endtime).all()

rawDescription: With specific dates AND times in a database column, how do I query for all records on a specific day?


code:
from collections import OrderedDict

data = []
for line in eventVar.readline():
    # Remove braces
    line = line.strip()[1:-1]
    results = OrderedDict()
    # Split by comma sign
    for pair in line.split(','):
        # Get key and value by splitting on colon
        key, value = pair.split(':')
        # Use eval to get rid of quotation surrounding the key and value
        results[eval(key)] = eval(value)
        # Add the results from reading this line to a list
        data.append(results)

rawDescription: Python: Text file to dictionary whilst preserving order?


code:
for df in (variables, Q1):
    df.fillna(0, inplace=True)

rawDescription: pandas: fill multiple empty dataframes

description: Pandas: fill multiple empty dataframes


code:
def binarySearch(data, val):
    highIndex = len(data)-1
    lowIndex = 0
    while highIndex > lowIndex:
            index = (highIndex + lowIndex) / 2
            sub = data[index]
            if data[lowIndex] == val:
                    return [lowIndex, lowIndex]
            elif sub == val:
                    return [index, index]
            elif data[highIndex] == val:
                    return [highIndex, highIndex]
            elif sub > val:
                    if highIndex == index:
                            return sorted([highIndex, lowIndex])
                    highIndex = index
            else:
                    if lowIndex == index:
                            return sorted([highIndex, lowIndex])
                    lowIndex = index
    return sorted([highIndex, lowIndex])

rawDescription: Get index of closest value with binary search


code:
class DetailsForm(forms.ModelForm):
    class Meta:
        model = Detail

@login_required
def details(request, pk=None):
    customer = request.user.customer

    try:
        existing_detail = Detail.objects.get(customer_id=customer.id)
    except:
        existing_detail = None

    details_form = DetailsForm(instance = existing_detail)

    if request.method == 'POST':
        form = DetailsForm(request.POST, instance=existing_details)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/settings/details/')
    context = {
        'title':'details',
        'view':'detail',
        'form': form
    }
    return render(request, 'customers/detail.html', context)

rawDescription: simplest way to save or display data for form in django

description: Simplest way to save or display data for form in django


code:
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax1.set_title('PC')
ax2.set_title('MC')
im=ax1.imshow(topo.sim.PC.activity,interpolation='nearest')
im1=ax2.imshow(topo.sim.MC.activity,interpolation='nearest')

plt.colorbar(im, ax=ax1)
plt.colorbar(im1, ax=ax2)

rawDescription: Colorbar With subplots

description: Colorbar With subplots


code: obj_l = NewTable.objects.values_list('country', flat=True).distinct()

rawDescription: Access Value from ValuesQuerySet

description: Access Value from ValuesQuerySet


code: by_name = {g.name: g.users for g in Group.query.options(db.joinedload(Group.users))}

rawDescription: create dictionary based on filter in sqlalchemy

description: Create dictionary based on filter in sqlalchemy


code:
# todo: write a testfile so the example works
open("testfile.txt", "w"). write("""1,5 # matriks size
OFFENSE INVOLVING CHILDREN # key for dictionary
95  # list of value
96
35
80
100
2,2
BATTERY,THEFT
173,209   # list of tuple value
173,224""")

def strip_comment(line):
    return line.split('#', 1)[0].rstrip()

mydict = {}

with open("testfile.txt") as testfile:
    for line in testfile:
        # first line is the next record "matrix size"
        columns, rows = (int(x) for x in strip_comment(line).split(','))
        # next line is the header for this record
        key = tuple(strip_comment(next(testfile)).split(','))
        # the next lines are the rows for this record
        vals = [tuple(int(x) for x in   strip_comment(next(testfile)).split(','))
            for _ in range(rows)]
        mydict[key] = vals

print(mydict)

rawDescription: Reading data from csv file put into dictionary python


code:
def get_passwd(input_dict=None, **kwargs):
    kwargs = kwargs if input_dict is None else dict(kwargs.items() + input_dict.items())
    if "passphrase_confirm" in kwargs:
        return kwargs["passphrase_confirm"]
    else:
        return kwargs.get("passphrase", None)

rawDescription: python dict parameter and or kwargs

description: Python dict parameter and or kwargs


code: np.einsum('ij,ij->i', X, X)

rawDescription: Sum over squared array

description: Sum over squared array


code: p = subprocess.Popen(command, shell=True, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)

rawDescription: Trying to call a shell command with Python, gets nothing


code:
with open('somefile') as fin:
    rows = (line.split() for line in fin)
    take = (row for row in rows if int(row[1] == 2) and 4 <= int(row[2]) <= 15)
    # data = list(take)
    for row in take:
        pass # do something

rawDescription: Search in two dimensional array in Python


code:
#!/usr/bin/python
from gi.repository import Gtk
import cairo
import math

def OnDraw(w, cr):
    cr.set_source_rgb(1, 1, 0)
    cr.arc(320,240,100, 0, 2*math.pi)
    cr.fill_preserve()

    cr.set_source_rgb(0, 0, 0)
    cr.stroke()

    cr.arc(280,210,20, 0, 2*math.pi)
    cr.arc(360,210,20, 0, 2*math.pi)
    cr.fill()

    cr.set_line_width(10)
    cr.set_line_cap(cairo.LINE_CAP_ROUND)
    cr.arc(320, 240, 60, math.pi/4, math.pi*3/4)
    cr.stroke()

w = Gtk.Window()
w.set_default_size(640, 480)
a = Gtk.DrawingArea()
w.add(a)

w.connect('destroy', Gtk.main_quit)
a.connect('draw', OnDraw)

w.show_all()

Gtk.main()

rawDescription: Python GTK+ Canvas

description: Python GTK+ Canvas


code:
class Bullet(pygame.sprite.Sprite):

    def init(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.image.load("Bullet.png")
        self.rect = self.image.get_rect()

        self.dx = random.randrange(-10,10)
        self.dy = random.randrange(-10,10)

    def update(self):
        self.rect.x += self.dx
        self.rect.y += self.dy

rawDescription: Random direction bullets?

description: Random direction bullets


code:
balance = int(raw_input("Enter balance"))
int_rate = float(raw_input("enter rate"))
int_rate /= 100
lower_b = balance / 12.
upper_b = ((balance * (1 + (int_rate / 12.0)) ** 12) / 12.0)
payment = (lower_b + upper_b) / 2
def Credit(bal, rate, low, high, pay):
    new_b = bal
    # calculate monthly interest rate
    month_int = rate / 12
    while abs(new_b) > 0.001:  # use epsilon
        # always reset balance
        new_b = bal
        for _ in range(12):  # loop over 12 month range
            new_b -= pay  # deduct pay
            new_b += month_int * new_b
        # if we still have a balance we need to take more so set low to current payment
        if new_b > 0:
            low = pay
        # else we took to much so set high to current payment
        else:
            high = pay
        pay = (low + high) / 2.0
    return "Lowest monthly payment over 12 months: {}".format(pay)

print(Credit(balance, int_rate, lower_b, upper_b, payment))

rawDescription: Regarding not changing value of N

description: Regarding not changing value of N


code:
solutions = {'wet' : 'put into microwave', 'ring' : 'hit with hammer', 'battery' : 'more jiggawatts'}

def find_solution():
    problems = input('State your problem: ').lower().split(' ')
    for problem in set(problems):
        if problem in solutions:
            print(solutions[problem])

while True:
    find_solution()

rawDescription: Python - Using a dictionary to check query and retrieve an answer


code:
class Playlist(models.Model):
    videos = models.ManyToManyField("Video", through="PlaylistVideos")

rawDescription: Django easy retrival of items in a Many-to-many relationship model


code:
import boto

rds = boto.connect_rds()
instances = rds.get_all_dbinstances()
instances[0].status

rawDescription: Access to rds-describe-db-instances from Boto


code:
import com.gargoylesoftware.htmlunit.WebClient as WebClient
import com.gargoylesoftware.htmlunit.BrowserVersion as BrowserVersion

def main():
   webclient = WebClient(BrowserVersion.FIREFOX_3_6) # creating a new webclient object.
   url = "http://www.gartner.com/it/products/mq/mq_ms.jsp"
   page = webclient.getPage(url) # getting the url
   articles = page.getByXPath("//table[@id='mqtable']//tr/td/a") # getting all the hyperlinks

if __name__ == '__main__':
   main()

rawDescription: Python - how to trick anti adblock filter while scraping?


code:
# pip install spark-submit-app-id-wrapper

# ssaiw spark-submit --master yarn-cluster --class etc etc > /dev/null
application_1448925599375_0050

rawDescription: Running a spark job and getting the job id via script


code:
def create_champion_index(d, n):
    new_d = {}
    # iterate over dict items key/values
    for k, v in d.items():
        # add `n` highest summed sublists from each value/list
        new_d[k] = sorted(v, key=sum,reverse=True)[:n]
    return new_d # return new dict to access later

champs = create_champion_index({'a': [[0, 10], [1, 20], [2,15]], 'b': [[0, 20], [1, 15], [2, 10]]}, 2)

print(champs['a'])
print(champs['b'])
[[1, 20], [2, 15]]
[[0, 20], [1, 15]]

rawDescription: how to find max element from dictionary that has list of lists in python

description: Find max element from dictionary that has list of lists in python


code:
from django.contrib import auth
#...
url(r'^admin/login/', auth.views.login, kwargs={"template_name":"admin/login.html"}, name='login'),

rawDescription: How to re-use Django Admin login form from custom LoginRequired middleware

description: Re-use Django Admin login form from custom LoginRequired middleware


code:
from SimpleCV import *
img = Image('simplecv')
(r,g,b) = img.splitChannels(False) #we pass false to break into color channels, not greyscale
updated = ((r * 2) - (g * 0.5) - b)/4
updated.show()

rawDescription: Color Transform in OpenCV or SimpleCV

description: Color Transform in OpenCV or SimpleCV


code:
class Section(models.Model):
    survey = models.ForeignKey(Survey)
    name = models.CharField(max_length=100)

    class Meta:
        abstract = True        # no db table created for this model

    def __unicode__(self):
        return self.name

class RatingSection(Section):
    pass

class MultiChoiceSection(Section):
    can_select_multiple = models.BooleanField()

rawDescription: Django Model/Database design for subclasses


code:
import module
import inspect
src = inspect.getsource(module)

rawDescription: is there a way to view the source of a module from within the python console?

description: Is there a way to view the source of a module from within the python console


code:
res = []
for x in elems:
     res.append(my_function(x))

res = my_function(x)  # this solution is way better for performance

rawDescription: Python (2.7): are functions computationally expensive


code:
def func1(a, b):
    pass

def func2(a, b):
    pass

def functionA(val1, val2, func):
    func(val1, val2)

# now call functionA passing in a function
functionA("foo", "bar", func1)

rawDescription: Can I use a function passed by parameters?

description: Use a function passed by parameters


code:
print({'AvgPositive': posNumAvg,
       'AvgNonPos': nonPosNumAvg,
       'AvgAllNum': allNumAvg})

rawDescription: Python Printing 3 values inside a dictionary


code:
from flask import Flask,jsonify
import requests
import simplejson
import json

app = Flask(__name__)

@app.route("/")
def home():
    uri = "https://api.stackexchange.com/2.0/users?   order=desc&sort=reputation&inname=fuchida&site=stackoverflow"
    try:
        uResponse = requests.get(uri)
    except requests.ConnectionError:
       return "Connection Error"
    Jresponse = uResponse.text
    data = json.loads(Jresponse)

    displayName = data['items'][0]['display_name']# <-- The display name
    reputation = data['items'][0]['reputation']# <-- The reputation

    return Jresponse

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

rawDescription: How to get json data from a url using flask in python

description: Get json data from a url using flask in python


code:
while True:

    item = request_queue.get()

    if item == None:
        break

    # process the Queue as per normal...

rawDescription: How to get this thread waiting on a queue to quit?

description: Get this thread waiting on a queue to quit


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

sns.set(style="ticks")

x = np.random.randn(100)

f, (ax_box, ax_hist) = plt.subplots(2, sharex=True,
                                    gridspec_kw={"height_ratios": (.15, .85)})

sns.boxplot(x, ax=ax_box)
sns.distplot(x, ax=ax_hist)

ax_box.set(yticks=[])
sns.despine(ax=ax_hist)
sns.despine(ax=ax_box, left=True)

rawDescription: Histogram with Boxplot above in Python

description: Histogram with Boxplot above in Python


code:
input_string = re.sub('\(', '[', input_string)
input_string
input_string = re.sub('\)', ']', input_string)
input_string
input_string = re.sub(r'([a-zA-Z!]+)', r'"\1",', input_string)
input_string
input_string = re.sub(r'(",\ )\[\ ([^\x00-\x7F]+)',r'\1"\2"' ,input_string)
input_string

rawDescription: Python re.sub(): Replacing a char between two different categories


code: " ".join("--%s=%s" % item for item in args.iteritems())

rawDescription: Pythonic way to create a command args strings from key => values sored in a dictionary


code: "say (?P<value>.+) endsay"

rawDescription: Python regular expressions assigning to named groups


code:
from odf.opendocument import load
from odf.table import Table
from odf.table import TableCell
from odf.table import TableRow
from odf.text import P

#loading it
book = load('your.ods')
#create a new sheet in memory
sheet = Table(name="test sheet")
#create a new row
tablerow=TableRow()
#create a new cell
cell=TableCell()
#fill-in a cell
cell.addElement(P(text="hello world"))
#add a cell to the row
tablerow.addElement(cell)
#add the row to the sheet
sheet.addElement(tablerow)
#adding the new to the book
book.spreadsheet.addElement(sheet)
#save it
book.save('your_new.ods')

rawDescription: add a sheet to an ods file via python

description: Add a sheet to an ods file via python


code:
def iconToQImage(hIcon):
    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    hbmp.CreateCompatibleBitmap(hdc, hIcon.width, hIcon.height)
    hdc = hdc.CreateCompatibleDC()
    hdc.SelectObject(hbmp)

    win32gui.DrawIconEx(hdc.GetHandleOutput(), 0, 0, hIcon.hIcon, hIcon.width, hIcon.height, 0, None, 0x0003)

    bitmapbits = hbmp.GetBitmapBits(True)
    image = QtGui.QImage(bitmapbits, hIcon.width, hIcon.height, QtGui.QImage.Format_ARGB32_Premultiplied)
    return image

rawDescription: HICON/HBITMAP to QIcon/QPixmap/QImage/Anything with a Q in it


code:
lst = ['1','err','-1',' ','155']
lst1 = []
for i in lst:
    try:
        int_i = int(i)
        if int_i > 0:
            lst1.append(int_i)
    except:
        pass

rawDescription: getting only positive number from a list that containing heterogeneous data type item in python 3

description: Getting only positive number from a list that containing heterogeneous data type item in python 3


code:
import numpy as np

a = np.arccos((a1 * a2) / (np.abs(a1) * np.abs(a2)))

rawDescription: Easy angle and point / Numpy

description: Easy angle and point / Numpy


code:
import re
mystr = "Hi. How2 are you doing??    "
re.findall(r'[.?]|\w+', mystr)

rawDescription: Tokenize a string based on punctuation

description: Tokenize a string based on punctuation


rawDescription: Reading and Grouping a List of Data in Python


code:
def complete(self):
    """Flag this task as incomplete if any requirement is incomplete or has been updated more recently than this task"""
    import os
    import time

    def mtime(path):
        return time.ctime(os.path.getmtime(path))

    # assuming 1 output
    if not os.path.exists(self.output().path):
        return False

    self_mtime = mtime(self.output().path)

    # the below assumes a list of requirements, each with a list of outputs. YMMV
    for el in self.requires():
        if not el.complete():
            return False
        for output in el.output():
            if mtime(output.path) > self_mtime:
                return False

    return True

rawDescription: Can luigi rerun tasks when the task dependencies become out of date?


code:
from lib import A

def my_method(instance, *args, **kwargs):
    some_code_here()

A.method = my_method

rawDescription: How to modify class's method behaviour? Python, class belongs to library that can't be changed

description: Modify class's method behaviour? Python, class belongs to library that can't be changed


rawDescription: Serialize long number in python

description: Serialize long number in python


rawDescription: No xpath results in scrapy

description: No xpath results in scrapy


rawDescription: Adding 2D matrices as numpy arrays

description: Adding 2D matrices as numpy arrays


code:
us_dollar_label = soup.find("td", text="U.S. dollar (close)")
rates = [td.get_text() for td in us_dollar_label.find_next_siblings("td")]

rawDescription: How to scrap data selectively from tables in Python 2

description: Scrap data selectively from tables in Python 2


rawDescription: A python's beginner exercise

description: A python's beginner exercise


code:
class A: pass; # old-style class (default style in py2)
class B(object): pass; # new-style class (default style in py3)
type(A())
A().__class__
type(B())
B().__class__

rawDescription: Python: return true if obj has exactly type t


rawDescription: How to restart pydev interactive console after a code change?

description: Restart pydev interactive console after a code change


code:
import urllib2
from bs4 import BeautifulSoup

url = "http://www.reuters.com/article/2014/03/06/us-syria-crisis-assad-insight-idUSBREA250SD20140306"

soup = BeautifulSoup(urllib2.urlopen(url))

with open('ctp_output.txt', 'w') as f:
    for tag in soup.find_all('p'):
        f.write(tag.text.encode('utf-8') + '\n')

rawDescription: Article scraping with beautifulsoup: scraping all <p> tags


code:
x = int(input("What is the first number? "))
y = int(input("What is the second number? "))
answer = 0

while y != 0:
   if (y%2 != 0):
      answer=answer+x
      x=x*2
      y=y//2
   if (y%2 == 0):
      x=x*2
      y=y//2

print("the product is",(answer))

rawDescription: Russian Peasant Multiplication Python 3.3


code:
class BlobstoreUpload(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    upload_files = self.get_uploads('file')
    blob_info = upload_files[0]
    return self.response.write(blob_info.key())

  @classmethod
  def encode_multipart_formdata(cls, fields, files, mimetype='image/png'):
    """
    Args:
      fields: A sequence of (name, value) elements for regular form fields.
      files: A sequence of (name, filename, value) elements for data to be
        uploaded as files.

    Returns:
      A sequence of (content_type, body) ready for urlfetch.
    """
    boundary = 'paLp12Buasdasd40tcxAp97curasdaSt40bqweastfarcUNIQUE_STRING'
    crlf = '\r\n'
    line = []
    for (key, value) in fields:
      line.append('--' + boundary)
      line.append('Content-Disposition: form-data; name="%s"' % key)
      line.append('')
      line.append(value)
    for (key, filename, value) in files:
      line.append('--' + boundary)
      line.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
      line.append('Content-Type: %s' % mimetype)
      line.append('')
      line.append(value)
    line.append('--%s--' % boundary)
    line.append('')
    body = crlf.join(line)
    content_type = 'multipart/form-data; boundary=%s' % boundary
    return content_type, body

class UserProfile(webapp2.RequestHandler):
  def post(self):
    picture = self.request.POST.get('picture')

    # Write new picture to blob
    content_type, body = BlobstoreUpload.encode_multipart_formdata(
      [], [('file', name, image)])
    response = urlfetch.fetch(
      url=blobstore.create_upload_url(self.uri_for('blobstore-upload')),
      payload=body,
      method=urlfetch.POST,
      headers={'Content-Type': content_type},
      deadline=30
    )
    blob_key = response.content

rawDescription: Google App Engine - Error uploading file to blobstore from Python code


code:
extended_user = ExtendedUser(user_ptr_id=auth_user.pk)
extended_user.__dict__.update(auth_user.__dict__)
extended_user.save()

rawDescription: Django model inheritance: create sub-instance of existing instance (downcast)?


code:
df["DATE"] = pd.to_datetime(df["DATE"]) # switch to datetime to ease sorting
df = df.sort(["STOCK", "DATE"])
rsum_columns = "DATA1", "DATA3"
grouped = df.groupby("STOCK")[rsum_columns]
new_columns = grouped.transform(lambda x: pd.rolling_sum(x, 4))
df[new_columns.columns + "_TTM"] = new_columns
df

rawDescription: Group by - select most recent 4 events

description: Group by - select most recent 4 events


code:
# project/.gitignore

passwords.py

# project/passwords.py

GITHUB_KEY = '123'
GITHUB_KEY_SECRET = 'ABC'
GITHUB_TOKEN = '456'
GITHUB_TOKEN_SECRET = 'XYZ'

# project/my_script.py

from passwords import GITHUB_KEY, GITHUB_KEY_SECRET, GITHUB_TOKEN, GITHUB_TOKEN_SECRET

KEY = GITHUB_KEY
KEY_SECRET = GITHUB_KEY_SECRET
TOKEN = GITHUB_TOKEN
TOKEN_SECRET = GITHUB_TOKEN_SECRET

rawDescription: Using github with secret keys

description: Using github with secret keys


code: d_list = [item for item in d_list if item['weight'] <= 180]

rawDescription: How to delete a dictionary from a list of dictionaries?

description: Delete a dictionary from a list of dictionaries


code:
class MyForm(forms.ModelForm):
  start_datetime=forms.SplitDateTimeField(input_time_formats=['%I:%M %p'])
  end_datetime=forms.SplitDateTimeField(input_time_formats=['%I:%M %p'])

  class Meta:
    model=MyModel
    exclude=('start_datetime','end_datetime')

  def clean(self):
    self.instance.start_datetime=self.cleaned_data.get('start_datetime')
    self.instance.end_datetime=self.cleaned_data.get('end_datetime')

rawDescription: How can I get the Django SplitDateTimeWidget to recognize AM/PM inputs?

description: Get the Django SplitDateTimeWidget to recognize AM/PM inputs


rawDescription: Python - subprocesses and the python shell


code:
from bs4 import BeautifulSoup

html = """<tr> <stuff1> <tr><stuff2> </tr> </tr>"""
soup =BeautifulSoup(html)

print(soup.find_all("tr"))

rawDescription: using re to find nested results in strings

description: Using re to find nested results in strings


code:
def exportMesh(filepath):

    # Only one mesh per scene
    objList = [object for object in bpy.context.scene.objects if object.type == 'MESH']

    if len(objList) == 0:
        return
    elif len(objList) > 1:
        return
    #raise exepction? dialog box?

    # Process the single mesh object:
    mesh = objList[0]

    # File name is same as the mesh's name in Blender
    meshFilePath = filepath[0 : filepath.rindex('/') + 1] + mesh.name + ".mesh"
    file = open(meshFilePath, 'w')

    WorldTransform = Matrix().Identity(4)
    WorldTransform *= Matrix.Rotation(radians(90), 4, "X")
    file.write('World Transform:\n')
    for rcol in WorldTransform_T.row:
        file.write('{:9f} {:9f} {:9f} {:9f}\n'.format(row[0], row[1], row[2], row[3]))
    file.write('\n')

    # Mesh (local) transform matrix
    file.write('Mesh Transform:\n')
    localTransform_T = mesh.matrix_local.copy()
    localTransform_T.transpose()
    for row in localTransform_T.row:
        file.write('{:9f} {:9f} {:9f} {:9f}\n'.format(row[0], row[1], row[2], row[3]))
    file.write('\n')

    vertexAttributeList = []
    for triangle in mesh.data.polygons:
        vertices = list(triangle.vertices)
        i = 0
        for vertex in vertices:
            vertexAttribute = list(mesh.data.vertices[vertex].co)

            if triangle.use_smooth:
                vertexAttribute.extend(list(mesh.data.vertices[vertex].normal))
            else:
                vertexAttribute.extend(list(triangle.normal))

            for uv_layer in mesh.data.uv_layers:
                uvCoord = uv_layer.data[triangle.loop_indices[i]].uv
                vertexAttribute.extend([uvCoord[0], 1 - uvCoord[1]])

            totalVertexWeight = 0
            jointWeights = [group.weight for group in mesh.data.vertices[vertex].groups]
            jointIndices = [group.group for group in mesh.data.vertices[vertex].groups]
            for weight in jointWeights:
                totalVertexWeight += weight

            vgNum = len(mesh.vertex_groups)
            jointWeightsAttribute = []
            jointIndicesAttribute = []
            for vgIndex in range(4):
                if vgIndex < len(jointIndices):
                    jointWeightsAttribute.append(jointWeights[vgIndex] / totalVertexWeight)
                    jointIndicesAttribute.append(jointIndices[vgIndex])
                else:
                    jointWeightsAttribute.append(0)
                    jointIndicesAttribute.append(0)

            vertexAttribute.extend(jointWeightsAttribute)
            vertexAttribute.extend(jointIndicesAttribute)

            vertexAttributeList.append(vertexAttribute)
            i += 1

    # VBO
    vNum = len(vertexAttributeList)
    tNum = len(mesh.data.uv_layers)
    file.write('VBO Length: {:d}\n'.format(vNum))
    for vertexAttribute in vertexAttributeList:
        file.write('{:9f} {:9f} {:9f} {:9f} {:9f} {:9f} {:9f} {:9f} {:9f} {:9f} {:9f} {:9f} {:d} {:d} {:d} {:d}\n'.format(vertexAttribute[0],
                                                                                vertexAttribute[1],
                                                                                vertexAttribute[2],
                                                                                vertexAttribute[3],
                                                                                vertexAttribute[4],
                                                                                vertexAttribute[5],
                                                                                vertexAttribute[6],
                                                                                vertexAttribute[7],
                                                                                vertexAttribute[8],
                                                                                vertexAttribute[9],
                                                                                vertexAttribute[10],
                                                                                vertexAttribute[11],
                                                                                vertexAttribute[12],
                                                                                vertexAttribute[13],
                                                                                vertexAttribute[14],
                                                                                vertexAttribute[15]))
    file.write('\n')

    # Done writing mesh file
    file.close()

rawDescription: how to export per-vertex UV coordinates in Blender export script

description: Export per-vertex UV coordinates in Blender export script


code:
from bottle import request, route, run

@route('/upload', method='POST')
def do_upload():
    data = request.files.get('data')
    raw = data.file.read()
    filename = data.filename
    return "You uploaded %s (%d bytes)." % (filename, len(raw))

run(host='localhost', port=8080)

rawDescription: how to simply handle the request with python

description: Simply handle the request with python


code:
chunk = fileobj.read(3)
# decode bytes as little-endian, signed integer
chunk += '\x00'
number = struct.unpack('<i', chunk)

rawDescription: copy 3 byte char to int

description: Copy 3 byte char to int


rawDescription: three argument filtering

description: Three argument filtering


code:
uuid.uuid4()
uuid.uuid4()
uuid.uuid4()
uuid.uuid4()

rawDescription: How would I go about randomly generating strings with certain parameters?


code:
string = "Hello my name is Josh I like pizza and python I need this string to be really really long"
string = string.split()

for word_num, word in enumerate(string):
    if word_num and word_num % 5 == 0:
        # access the array since changing only the variable word wont work
        string[word_num] += '\n'

string = ' '.join(string)

print(string)

rawDescription: How to split up a long list using \n

description: Split up a long list using \n


code:
re.findall(r"[^\W\d_]+|\d+", "23Westminister15London")
re.findall(r"[^\W\d_]+|\d+", "Westminister15London England")

rawDescription: Fast way to split alpha and numeric chars in a python string


code: edit.bind("<KeyPress>", lambda e: "break")

rawDescription: hide typed caracters in tkinter.text widget

description: Hide typed caracters in tkinter.text widget


code: gws = conn.get_all_internet_gateways(filters={'attachment.vpc-id': vpc.id})

rawDescription: AWS boto: how to get a list of all Internet gateways attached to a VPC


code:
with open('buildings.csv', 'r') as f:
    for line in f:
        if(line.find("IRELAND")!=-1):
            print(line)

rawDescription: Read only rows with matching data in csv list with python


code:
def is_code_block(node):
    return (node.tagname == 'literal_block'
            and 'code' in node.attributes['classes'])

code_blocks = doctree.traverse(condition=is_code_block)
source_code = [block.astext() for block in code_blocks]

rawDescription: extract code from code directive from restructuredtext using docutils

description: Extract code from code directive from restructuredtext using docutils


code:
js_code = "document.getElementById('foo').style.display = 'None';"
self.webview.execute_script(js_code)

rawDescription: How to display only specific div with python webkit

description: Display only specific div with python webkit


code:
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy.random as rnd
import numpy as np

def arc_patch(xy, width, height, theta1=0., theta2=180., resolution=50, **kwargs):

    # generate the points
    theta = np.linspace(np.radians(theta1), np.radians(theta2), resolution)
    points = np.vstack((width*np.cos(theta)  + xy[0],
                        height*np.sin(theta) + xy[1]))
    # build the polygon and add it to the axes
    poly = mpatches.Polygon(points.T, closed=True, **kwargs)

    return poly

NUM = 10
arcs = []
for i in range(NUM):
    r = rnd.rand()*360.
    arcs.append(arc_patch(xy=rnd.rand(2)*10, width=1.,
                height=1., theta1=r, theta2=r+180.))

# axis settings
fig, ax = plt.subplots(1,1)
for a in arcs:
    ax.add_artist(a)
    a.set_clip_box(ax.bbox)
    a.set_alpha(0.5)
    a.set_facecolor(rnd.rand(3))

ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

plt.show()

rawDescription: How to plot half-ellipses in Python?

description: Plot half-ellipses in Python


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('<thing><id>1234</id><distribution-code>555444333</distribution-code></thing>')
soup.thing
soup.id
soup.distribution-code
soup.find('distribution-code')

rawDescription: In Python, how do I refer to an XML tag that contains a hyphen


code:
import sys

class ParallelMock(object):

    def __init__(self):
        '''Init and blank the "display".'''
        self.display = [' '] * 4
        self._update()

    def setData(self,data):
        '''Bits 0-3 are the "value".
           Bits 4-7 are positions 0-3 (first-to-last).
        '''
        self.display = [' '] * 4
        value = data & 0xF
        if data & 0x10:
            self.display[0] = str(value)
        if data & 0x20:
            self.display[1] = str(value)
        if data & 0x40:
            self.display[2] = str(value)
        if data & 0x80:
            self.display[3] = str(value)
        self._update()

    def _update(self):
        '''Write over the same four terminal positions each time.'''
        sys.stdout.write(''.join(self.display) + '\r')

if __name__ == '__main__':
    p = ParallelMock()

    nums = raw_input("Enter a string of numbers: ")

    # Shift over the steam four-at-a-time.
    stream = 'XXXX' + nums + 'XXXX'
    data = [0] * 4
    for i in range(len(stream)-3):
        # Precompute data
        for pos in range(4):
            value = stream[i+pos]
            data[pos] = 0 if value == 'X' else (1<<(pos+4)) + int(value)
        # "Flicker" the display...
        for delay in xrange(1000):
            # Display each position briefly.
            for d in data:
                p.setData(d)
        # Clear the display when done
        p.setData(0)

rawDescription: Multiplexing string of numbers in python for the parallel port


code:
combinations = [([1, 1], [0], [1, 1], [0]),
            ([1, 1], [0], [0], [1, 1]),
            ([1, 1], [1, 1], [0], [0]),
            ([1, 1], [1, 1], [0], [0]),
            ([1, 1], [0], [0], [1, 1]),
            ([1, 1], [0], [1, 1], [0])]

def filterComb(comb):
    result = list()
    for current in comb:
        isok = True
        for i in range(1, len(current)):
            if current[i] != [0] and current[i-1] != [0]:
                isok = False
                break
        if isok:
            result.append(current)
    return result

combinations = filterComb(combinations)

rawDescription: test for a specific element placement relative to other elements python

description: Test for a specific element placement relative to other elements python


code:
import wx

class TestRun(wx.Frame):
    def __init__(self,parent):
        wx.Frame.__init__(self, parent, title="StackO Test", size=(400,400))
        self.control = wx.TextCtrl(self, id=wx.ID_ANY, style=wx.TE_MULTILINE)
        self.control.Bind(wx.EVT_CHAR, self.OnPress)

        self.Show(True)

    def OnPress(self, event):
        if event.GetKeyCode() == 13:
            self.control.WriteText('\n>>>')
        else:
            event.Skip()

if __name__ == '__main__':
    app = wx.App(False)
    TestRun(None)
    app.MainLoop()

rawDescription: preventing newline after wxpython TextCtrl.WriteText()

description: Preventing newline after wxpython TextCtrl.WriteText()


rawDescription: Make Python Lists Into Two-Dimensional Arrays


code:
from threading import Lock
from flask import Flask
app = Flask(__name__)

a = 1
b = 2
c = 3
lock = Lock()

@app.route("/")
def hello():
    with lock:
        a += 1
        b += a
        c += b
    return "Hello World!"

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

rawDescription: Working with a global singleton in Flask (WSGI), do I have to worry about race conditions?


code:
class Storage(models.Model):
    storage_types = models.ManyToManyField(StorageType)

    def __unicode__(self):
        return str(self.id)

class StorageType(models.Model):
    tripa = 'Tripa'
    portada = 'Portada'
    type_choice = (
        (tripa, 'Tripa'),
        (portada, 'Portada'),
    )
    sto_type = models.CharField(max_length=9, choices=type_choice, default=tripa)
    paper_type = models.ForeignKey(Paper)
    paper_qnty = models.IntegerField(blank=True, default=0)
    web_paper_qnty = models.IntegerField(blank=True, default=0)

    def __unicode__(self):
        return '%s of %s' %(self.sto_type, str(self.storage))

rawDescription: How can I save an empty model (I only need it's pk created)

description: Save an empty model (I only need it's pk created)


code:
#!/usr/bin/env python

# core modules
from itertools import chain

# installed modules
import pyglet
import numpy

# local modules
import config

# constants
CURVE_SEGS = config.curve_segments  # number of line segs in a curve

# bezier curves courtesy of NYU

def fac( k ):
    '''
    Returns k!.
    '''

    if k == 0: return 1
    else: return reduce(lambda i,j : i*j, range(1,k+1))

def binom( n, k ):
    '''
    Returns n choose k.
    '''

    if k < 0 or k > n: return 0

    return fac( n ) / ( fac( k ) * fac( n - k ) )

def B( P, t ):
    '''
    Evaluates the bezier curve of degree len(P) - 1, using control points 'P',
    at parameter value 't' in [0,1].
    '''
    n = len( P ) - 1
    assert n > 0

    from numpy import zeros
    result = zeros( len( P[0] ) )
    for i in xrange( n + 1 ):
        result += binom( n, i ) * P[i] * (1 - t)**(n-i) * t**i

    return result

def B_n( P, n, t ):
    '''
    Evaluates the bezier curve of degree 'n', using control points 'P',
    at parameter value 't' in [0,1].
    '''

    ## clamp t to the range [0,1]
    t = min( 1., max( 0., t ) )

    num_segments = 1 + (len( P ) - (n+1) + n-1) // n
    assert num_segments > 0
    from math import floor
    segment_offset = min( int( floor( t * num_segments ) ), num_segments-1 )

    P_offset = segment_offset * n

    return B( P[ P_offset : P_offset + n+1 ], ( t - segment_offset/float(num_segments) ) * num_segments )

def Bezier_Curve( P ):
    '''
    Returns a function object that can be called with parameters between 0 and 1
    to evaluate the Bezier Curve with control points 'P' and degree len(P)-1.
    '''
    return lambda t: B( P, t )

def Bezier_Curve_n( P, n ):
    '''
    Returns a function object that can be called with parameters between 0 and 1
    to evaluate the Bezier Curve strip with control points 'P' and degree n.
    '''
    return lambda t: B_n( P, n, t )

def cubicSpline(p0, p1, p2, p3, nSteps):
    """Returns a list of line segments and an index to make the full curve.

    Cubics are defined as a start point (p0) and end point (p3) and
    control points (p1 & p2) and a parameter t that goes from 0.0 to 1.0.
    """
    points = numpy.array([p0, p1, p2, p3])
    bez = bezier.Bezier_Curve( points )
    lineSegments = []
    for val in numpy.linspace( 0, 1, nSteps ):
        #print '%s: %s' % (val, bez( val ))
        # the definition of the spline means the parameter t goes
        # from 0.0 to 1.0
        (x,y) = bez(val)
        lineSegments.append((int(x),int(y)))
    #lineSegments.append(p2)
    cubicIndex = [0] + [int(x * 0.5) for x in range(2, (nSteps-1)*2)] + [nSteps-1]
    #print "lineSegments = ",lineSegments
    #print "cubicIndex = ",cubicIndex
    return (lineSegments,cubicIndex)

# graphic primatives

class GraphicObject(object):

    """Basic graphic object primative"""

    def __init__(self, field, points, index, color):
        """Graphic object constructor.

            Args:
                arcpoints - list of points that define the graphic object
                arcindex - list of indicies to arcpoints
                color - list of colors of each arc
        """
        self.m_field = field
        self.m_arcpoints = points
        self.m_arcindex = index
        self.m_color = color
        # each arc is broken down into a list of points and indecies
        # these are gathered into lists of lists
        # TODO: possibly these could be melded into single dim lists
        self.m_points = []
        self.m_index = []

class Circle(GraphicObject):

    """Define circle object."""

    def __init__(self, field, p, r, color,solid=False):
        """Circle constructor.

        Args:
            p - center point
            r - radius of circle
            c - color
        """
        self.m_center = p
        self.m_radius = r
        self.m_solid = solid
        k = 0.5522847498307935  # 4/3 (sqrt(2)-1)
        kr = int(r*k)
        (x,y)=p
        arcpoints=[(x+r,y),(x+r,y+kr), (x+kr,y+r), (x,y+r),
                           (x-kr,y+r), (x-r,y+kr), (x-r,y),
                           (x-r,y-kr), (x-kr,y-r), (x,y-r),
                            (x+kr,y-r), (x+r,y-kr)]
        arcindex=[(0, 1, 2, 3), (3, 4, 5, 6), (6, 7, 8, 9), (9, 10, 11, 0)]
        GraphicObject.__init__(self,field,arcpoints,arcindex,color)

    def render(self):
        # e.g., self.m_arcpoints = [(10,5),(15,5),(15,10),(15,15),(10,15),(5,15),(5,10)]
        # e.g., self.m_arcindex = [(0,1,2,3),(3,4,5,6)]
        for i in range(len(self.m_arcindex)):
            # e.g., self.m_arcindex[i] = (0,1,2)
            p0 = self.m_arcpoints[self.m_arcindex[i][0]]
            p1 = self.m_arcpoints[self.m_arcindex[i][1]]
            p2 = self.m_arcpoints[self.m_arcindex[i][2]]
            p3 = self.m_arcpoints[self.m_arcindex[i][3]]
            (points,index) = cubicSpline(p0,p1,p2,p3,CURVE_SEGS)
            if self.m_solid:
                points.append(self.m_center)
                nxlast_pt = len(points)-2
                last_pt = len(points)-1
                xtra_index = [nxlast_pt,last_pt,last_pt,0]
                index = index + xtra_index
            self.m_points.append(points)
            self.m_index.append(index)

    def draw(self):
        for i in range(len(self.m_index)):
            points = self.m_points[i]
            index = self.m_index[i]
            pyglet.gl.glColor3f(self.m_color[0],self.m_color[1],self.m_color[2])
            if not self.m_solid:
                pyglet.graphics.draw_indexed(len(points), pyglet.gl.GL_LINES,
                    index,
                    ('v2i',self.m_field.scale2out(tuple(chain(*points)))),
                )
            else:
                pyglet.graphics.draw_indexed(len(points), pyglet.gl.GL_POLYGON,
                    index,
                    ('v2i',self.m_field.scale2out(tuple(chain(*points)))),
                )

rawDescription: Python to Plot Graphics and Output Vector XY Pairs


rawDescription: pandas scatterplots: stop automatic scaling of axis

description: Pandas scatterplots: stop automatic scaling of axis


code:
from subprocess import call
call(["pdfdetach", "-saveall", "file.pdf"])

rawDescription: how do i export PDF file attachments via python

description: Export PDF file attachments via python


rawDescription: Python string strip

description: Python string strip


code:
def hook_factory(*factory_args, **factory_kwargs):
    def response_hook(response, *request_args, **request_kwargs):
        # use factory_kwargs
        # etc.
        return None # or the modified response
    return response_hook

grequests.get(u, hooks={'response': [hook_factory(search_item=search_item)]})

rawDescription: How to pass parameters to hooks in python grequests

description: Pass parameters to hooks in python grequests


code:
import csv
writer = csv.writer(open("test_out.csv", 'wt'))
l1 = ['a', 'b', 'c']
l2 = [n for n in xrange(len(l1))]
for row in xrange(len(l1)):
    writer.writerow([l1[row], l2[row]])

rawDescription: Python data to CSVs

description: Python data to CSVs


code:
from pprint import PrettyPrinter
pp = PrettyPrinter(indent = 4)
pp.pprint(map(dict, izip(*chain((product([k], v) for k, v in data.items())))))

rawDescription: itertools.izip() for not predefined count of lists

description: Itertools.izip() for not predefined count of lists


rawDescription: How to delete repeated elements from array keeping the order unchanged in python?

description: Delete repeated elements from array keeping the order unchanged in python


code:
from collections import defaultdict

...

if 'folding' not in request.session:
    request.session['folding'] = defaultdict(bool)

...

def update_folding_view(request, category, is_folded):
    if not request.is_ajax():
         raise Http404
    for item in category:
        request.session['folding'][item] = is_folded

rawDescription: Django: simplifying a view

description: Django: simplifying a view


rawDescription: python pandas: How to simplify the result of groupby('column_name').count()

description: Python pandas: How to simplify the result of groupby('column_name').count()


code:
import sys, os
sys.path.append(os.path.join(os.path.split(os.path.split(os.path.abspath(sys.argv[0]))[0])[0], "lib"))
import my_dependency

rawDescription: Provide a folder out of source where all my external libraries are found


code: soup.find("caption", text="Very long caption").find_parent("table")

rawDescription: Trying to use BeautifulSoup to find a specific table in an HTML doc


code:
from psycopg2.extensions import adapt as sqlescape
import sqlalchemy
from sqlalchemy import select
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import ColumnClause

class MyFunc(ColumnClause):
    def __init__(self, *args, **kwargs):
        self.kwargs = kwargs
        super().__init__(*args)

@compiles(MyFunc)
def compile_myfunc(element, compiler, **kw):
    s = ','.join("%s:=%s" % (k, sqlescape(v)) for k, v in element.kwargs.items())
    return "%s(%s)" % (element.name, s)

def call(engine, func, **kwargs):
    return engine.execute(select([MyFunc(func, **kwargs)]))

engine = sqlalchemy.create_engine('postgresql+psycopg2://lbolla@localhost/mytest')
print(call(engine, 'test_f', a='a').scalar())
print(call(engine, 'test_f', b='b').scalar())

rawDescription: Named parameters in database functions with SQLAlchemy


code:
import  numpy as np

arr = np.array([14 ,21, 13, 56, 12])
np.savetxt("foo.csv", np.dstack((np.arange(1, arr.size+1),arr))[0],"%d,%d",header="Id,Values")

rawDescription: write numpy array to CSV with row indices and header

description: Write numpy array to CSV with row indices and header


code:
from PyPDF2 import PdfFileMerger, PdfFileReader

merger = PdfFileMerger()

filenames = ['c:\\11.pdf', 'c:\\22.pdf', 'c:\\33.pdf']

for filename in filenames:
    merger.append(PdfFileReader(file(filename, 'rb')))
    merger.write('c:\\123.pdf')

rawDescription: Using Python to combine PDFs - Closing PDF files when they are combined


code:
screen.nodelay(1)
while True:
    char = screen.getch()
    if char == 113: break  # q
    elif char == curses.KEY_RIGHT: snake.update(RIGHT)
    elif char == curses.KEY_LEFT: snake.update(LEFT)
    elif char == curses.KEY_UP: snake.update(UP)
    elif char == curses.KEY_DOWN: snake.update(DOWN)
    else: snake.update()
    time.sleep(0.1)

rawDescription: How do you get the last arrow key pressed using curses?

description: Get the last arrow key pressed using curses


code:
import random

Answer1 = random.randint(1,5)

while True:
    Guess1 = int(input("Input a number 1-5 >>"))

    if Guess1 == Answer1:
        print ("You got luck this time")
        break

    elif Guess1 < 6 and Guess1 != Answer1:
        #send back to guess again
        print ("Try again!")
        continue

    elif Guess1 > 5:
        print ("Invalid Number")
        #send back to guess again
        continue

rawDescription: How do I send the prompt backwards in my code in python?

description: Send the prompt backwards in my code in python


code:
l = ['This', 'is', 'a', 'test']
any(['is', 'a'] == l[i:i+2] for i in xrange(len(l) - 1))

rawDescription: In python, how can I find a phrase in a tokenized string?


code:
from collections import Counter
test = 'abc def abc def zzz zzz'
Counter(test.split()).most_common()

rawDescription: Efficiently calculate word frequency in a string


code:
found = defaultdict(int)
def determine(tup):
    if self.message in tup[3]: return True      # matched message

    times = messageTimes[tup[0]]
    idx = found[tup[0]]
    le = bisect.bisect_right(times, tup[1], idx)
    idx = le
    return (le and tup[1]-times[le-1] <= tdiff) or (le != len(times) and times[le]-tup[1] <= tdiff)

rawDescription: How can I make my code more efficient?

description: Make my code more efficient


code:
required_fields = ('account','report_date_iso_year_week','report_date')
owner = db.session.query(Owner).filter(Owner.id == owner_id).first()
if owner is None:
    return None

result = {'data': []}
report_date = datetime.datetime.strptime('2016-05-01', '%Y-%m-%d')

rows = db.session.query(Opportunity)\
                 .filter(Opportunity.status == 'Won',
                         Opportunity.owner == owner,
                         or_(Opportunity.actual_close_date_iso_year_week == '2016/16',\
                             Opportunity.actual_close_date_iso_year_week == '2016/17'),
                         Opportunity.report_date == report_date)\
                 .order_by(Opportunity.account)\
                 .values(*[getattr(Opportunity,f) for f in required_fields])

for row in rows:
    result_row = {'first_name':owner.first_name}
    for field in required_fields:
        result_row[field] = getattr(row, field)
    result['data'].append(result_row)

rawDescription: Am I using the best SQLAlchemy query?

description: Am I using the best SQLAlchemy query


code:
import cgi

DATA = cgi.FieldStorage()

d = {}

for attr in DATA.keys():
    key = str(attr)
    value = DATA['key'].value
    d[key] = value

rawDescription: How do I parse http html post data submitted by a form

description: Parse http html post data submitted by a form


code:
characters = [chr(n) for n in numlist]   # Use unichr instead in Python 2.
# ['z', 'ń', 'o', '̕', 'o']

rawDescription: Convert list of numbers to characters

description: Convert list of numbers to characters


rawDescription: Python regex - split alphanumeric characters but remove and combine hyphenated words


code:
import time
time.asctime(time.strptime('2008 50 1', '%Y %W %w'))

rawDescription: In Python, how do I find the date of the first Monday of a given week?


rawDescription: how to resize images in python 3.2

description: Resize images in python 3.2


code:
from geopy.distance import great_circle
newport_ri = (41.49008, -71.312796)
cleveland_oh = (41.499498, -81.695391)
great_circle(newport_ri, cleveland_oh).kilometers

rawDescription: getting distance between two location using geocoding

description: Getting distance between two location using geocoding


code:
from __future__ import with_statement
import sys
import gevent
from gevent import socket
from gevent.pool import Pool

N = 1000
# limit ourselves to max 10 simultaneous outstanding requests
pool = Pool(10)
finished = 0

def job(url):
    global finished
    try:
        try:
            ip = socket.gethostbyname(url)
            print ('%s = %s' % (url, ip))
        except socket.gaierror:
            ex = sys.exc_info()[1]
            print ('%s failed with %s' % (url, ex))
    finally:
        finished += 1

with gevent.Timeout(2, False):
    for x in xrange(10, 10 + N):
        pool.spawn(job, '%s.com' % x)
    pool.join()

print ('finished within 2 seconds: %s/%s' % (finished, N))

rawDescription: Resolving and saving hostnames in parallel with Python


rawDescription: Optimized Averaging of Large Array?

description: Optimized Averaging of Large Array


code:
import sys
import os

# locate app-engine SDK
AE_PATH = "/path/to/sdk/google_appengine/"

# path to app code
APP_PATH = os.path.abspath(".")

# load the AE paths (as stolen from dev_appserver.py)
EXTRA_PATHS = [
    APP_PATH,
    AE_PATH,
    os.path.join(AE_PATH, 'lib', 'antlr3'),
    os.path.join(AE_PATH, 'lib', 'django'),
    os.path.join(AE_PATH, 'lib', 'ipaddr'),
    os.path.join(AE_PATH, 'lib', 'webob'),
    os.path.join(AE_PATH, 'lib', 'yaml', 'lib'),
    os.path.join(AE_PATH, 'lib', 'fancy_urllib'), # issue[1]
]
sys.path = EXTRA_PATHS + sys.path

rawDescription: Can't access Google AppEngine external libraries


rawDescription: How to create list of string elements

description: Create list of string elements


code:
from sys import getsizeof
a = range(100)
b = set(a)
getsizeof(a)
getsizeof(b)

rawDescription: Python very large set. How to avoid out of memory exception?


code:
def get_object(self, *args, **kwargs):
    obj = super(EditarEvento, self).get_object(*args, **kwargs)
    if obj.user != self.request.user:
        raise PermissionDenied() #or Http404
    return obj

rawDescription: How to restrict access to certain user to an UpdateView?

description: Restrict access to certain user to an UpdateView


code:
def main():
    sss = 0
    oa = 0
    sss, oa = calc (sss ,oa)
    print ("value = ",sss ,oa)

def calc (sss ,oa):
    sss = sss + 1
    oa = oa + 1
    return sss, oa
main()

rawDescription: Python not returning value from function


rawDescription: Push all non-'0' to front

description: Push all non-'0' to front


code:
from django.db.models import Q
products_list = Product.objects.all()
orq = None
for key in keywords:
    thisq = Q(name__icontains=q)
    if orq:
        orq = thisq | orq
    else:
        orq = thisq
products_list = products_list.filter(orq)

rawDescription: Django dynamic number of filter for a objects request


code:
l = [('name1', 'val1'), ('name2', 'val2')]
d = dict(l)
d
d.items()
d.keys()
d.values()

rawDescription: Unknown quantity of items in configuration files using ConfigParser


code: group = pd.concat([temp, group], axis=1)

rawDescription: How to concatenate within 'apply' on a grouped object

description: Concatenate within 'apply' on a grouped object


code:
from dns import resolver

consul_resolver = resolver.Resolver()
consul_resolver.port = 8600
consul_resolver.nameservers = ["127.0.0.1"]

answer = consul_resolver.query("chef.service.consul", 'A')
for answer_ip in answer:
    print(answer_ip)

rawDescription: How can I lookup dns service records in consul in python?

description: Lookup dns service records in consul in python


code:
str = "WooHoo"
str = str[:-len(str)/2]

rawDescription: Need more elegant solution to even string length


code: line = re.sub(pattern, r'\1', line)

rawDescription: How to perform this regex replacement more effectively in python without repeating the search?

description: Perform this regex replacement more effectively in python without repeating the search


code:
import matplotlib.font_manager
matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')

rawDescription: How to get a list of all the fonts currently available for Matplotlib?

description: Get a list of all the fonts currently available for Matplotlib


code:
def get_basic():
    L = []
    while True:
        line = str( input() )
        L.append( line )
        if "END" in line:
            break
    return L

rawDescription: GoTo(basic) program

description: GoTo(basic) program


code:
x = np.loadtxt('data' ,dtype=np.uint8, comments='#', delimiter='\t')
x = x.reshape(-1, 72, 44)
x.shape

rawDescription: Rehaspe a 2D matrix into a 3D ? (x, y) -> (x/72,72,y)


code:
def __new__(self,a,b):
    s=a
    return str.__new__(A,s)

rawDescription: python: overriding access a var

description: Python: overriding access a var


code:
df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
df.ix[:,'b':]

rawDescription: How to take column-slices of dataframe in pandas

description: Take column-slices of dataframe in pandas


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QWidget):
    updateSignal = QtCore.pyqtSignal()
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.table_widget = QtGui.QTableWidget()
        self.button = QtGui.QPushButton('Populate')
        self.button.clicked.connect(self.populate)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.table_widget)
        layout.addWidget(self.button)
        self.setLayout(layout)
        self.updateSignal.connect(self.update_table)
        self.populate()

    def populate(self):
        nrows, ncols = 5, 2
        self.table_widget.setSortingEnabled(False)
        self.table_widget.setRowCount(nrows)
        self.table_widget.setColumnCount(ncols)
        for i in range(nrows):
            for j in range(ncols):
                item = QtGui.QTableWidgetItem('%s%s' % (i, j))
                self.table_widget.setItem(i, j, item)
        self.updateSignal.emit()
        self.table_widget.setSortingEnabled(True)

    def update_table(self):
        self.table_widget.sortItems(0,QtCore.Qt.DescendingOrder)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    wnd = MainWindow()
    wnd.resize(640, 480)
    wnd.show()
    sys.exit(app.exec_())

rawDescription: Python PyQt - QTableWidget, JSON, and emitSignal causing blank cells


code:
with really_really_long_name_function(p) as f1, \
     other_really_really_long_name_function() as f2:
    pass

rawDescription: How to break a long with statement in python

description: Break a long with statement in python


code:
functions_to_call = ["func_1", "func_2", "func_3"]

for f in functions_to_call:
    eval(f+'()')

rawDescription: Calling unknown Python functions

description: Calling unknown Python functions


code:
# Create a temporary list to hold new x values
result = []

for x, y in zip(list_x, list_y):
     # Populate the new list
     result.append(f(x, y))

# Name your new list same as the old one
list_x = result

rawDescription: Python list initialization in for loop

description: Python list initialization in for loop


code:
class TaskForm(forms.ModelForm):
   class Meta:
      model = Task

   def __init__(self, *args, **kwargs):
      super(TaskForm, self).__init__(*args, **kwargs)
      self.fields['prerequisites'].queryset = Task.objects.filter(job=self.instance.job)

rawDescription: Django: apply "same parent" constraint to ManyToManyField mapping to self


code:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((100,100))*2
data[data<0.5]=0.5
plt.imshow(data,cmap='seismic', vmin=0.5, vmax=2)
c = plt.colorbar()
c.set_clim(0, 2)

rawDescription: matplotlib adjusting colorbar

description: Matplotlib adjusting colorbar


code:
import _winreg
import unicodedata
keyQ = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Environment', 0, _winreg.KEY_QUERY_VALUE)
path_old, _ = _winreg.QueryValueEx(keyQ, "PATH")
#the result is unicode, need to be converted
unicodedata.normalize('NFKD', path_old).encode('ascii','ignore')

rawDescription: How to return only user Path in environment variables without access to Registry?

description: Return only user Path in environment variables without access to Registry


code:
if __name__ == '__main__':
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('--junit', action='store_true')
    options, args = parser.parse_known_args()

    testrunner = None
    if (options.junit):
        testrunner = xmlrunner.XMLTestRunner(output='tests', descriptions=True)
    unittest.main(testRunner=testrunner, argv=sys.argv[:1] + args)

rawDescription: Python: run a unittest.TestCase without calling unittest.main()?


code:
import wx
from wx.lib.pubsub import pub

class CtrlPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1, style=wx.SUNKEN_BORDER)

        self.lstCombo = wx.ComboBox(self, -1)
        self.lstCombo.Bind(wx.EVT_COMBOBOX, self.onSelect)
        self.get_data()

    def get_data(self):
        self.lst = range(1, 10)
        self.lst = [str(x) for x in self.lst]
        self.lstCombo.Clear()
        self.lstCombo.AppendItems(self.lst)
        self.lstCombo.SetValue(self.lst[2])
        pub.sendMessage('F.Change', fobj=self.lstCombo.GetValue())

    def onSelect(self, event):
        pub.sendMessage('F.Change', fobj=self.lstCombo.GetValue())

class MainFrame(wx.Frame):
    """ The main frame of the application
    """
    def __init__(self, parent, title):

        wx.Frame.__init__(self, parent, title=title)

        self.statusbar = self.CreateStatusBar()
        pub.subscribe(self.change_StatusBarText, 'F.Change')
        self.ctrl_panel = CtrlPanel(self)

    def change_StatusBarText(self, fobj):
        self.SetStatusText(fobj)

def main():
    app = wx.App(redirect=False)
    frame = MainFrame(None, "Test")
    frame.Centre()
    frame.Show(True)
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: using wxpython and pubsub for changing text in statusbar

description: Using wxpython and pubsub for changing text in statusbar


code:
class LargeThing(object):
    def __init__(self):
        self.x = 6
    def large_func(self):
        self.small_func_that_will_increment_x()
        self.small_func()
        # ...
    def small_func_that_will_increment_x(self):
        self.x += 1

rawDescription: Python Large Functions Many Variables (Refactoring)


code:
number_of_read_lengths = {}

number_of_read_lengths[14,3] = "Your value"

rawDescription: Double-indexed dictionary

description: Double-indexed dictionary


code:
import shutil
shutil.copy('/local/mnt/workspace/user/Automation/swbuild/board/test_new.html',
            '/local/mnt/workspace/user/Automation/sw_admin/reports/board/test.html')

rawDescription: Copying a file with another name

description: Copying a file with another name


code:
pwlist = ([random.choice(special_char),
           random.choice(string.ascii_digits),
           random.choice(string.ascii_lowercase),
           random.choice(string.ascii_uppercase),
          ]
         + [random.choice(string.ascii_lowercase
                          + string.ascii_uppercase
                          + special_char
                          + string.ascii_digits) for i in range(4)])
random.shuffle(pwlist)
pw = ''.join(pwlist)

rawDescription: generating random string with requirements in Python 3

description: Generating random string with requirements in Python 3


code:
for i in [x for x in myList if x.Id > 5]:
    pass #do something

rawDescription: Foreach loop where clause in Python similar to c# LINQ


code:
from copy import deepcopy

#snip
templateclass = deepcopy(ListofClass[position])

rawDescription: Python how to assign a copy of a class to a variable? (Instead of by reference)


code:
from functools import wraps

def require_auth(roles=(Roles.USER,), *args, **kwargs):

    def call(f, *args, **kwargs):
        return f(*args, **kwargs)

    def deco(f):
        @wraps(f)
        def wrapped_f(request, *a, **kw):
            # do your authentication here
            return call(f, request, *a, **kw)

        return wrapped_f

    return deco

rawDescription: Python decorator internally calls wrong function


code:
score = [1,2,3,4,5]

with open("file.txt", "w") as f:
    for s in score:
        f.write(str(s) +"\n")

with open("file.txt", "r") as f:
  for line in f:
    score.append(int(line.strip()))

rawDescription: How to save a list to a file and read it as a list type?

description: Save a list to a file and read it as a list type


code:
first = ["B","C","D","A"]
second = [2,3,4,1]

zip(first, second)
first_new, second_new = zip(*sorted(zip(first, second)))
first_new
second_new

rawDescription: Sorting 2 lists

description: Sorting 2 lists


code:
def remove_abnormalities(values, indices):
    return [val for i, val in enumerate(values) if i not in indices]

rawDescription: Remove multiple elements from a list of index with Python


code:
from subprocess import Popen, stdin

args = ['mysqlimport', my_db_name, '-']
with Popen(args, stdin=PIPE) as import1, Popen(args, stdin=PIPE) as import2:
    with open('giantfile.txt') as f:
        for line in f:
            data = parse(line)
            if belongs_in_import2(data):
                import2.stdin.write(make_sql(data))
            else:
                import1.stdin.write(make_sql(data))

rawDescription: python write output to different fifo pipe file?

description: Python write output to different fifo pipe file


code:
import signal
import sys
import time

def confirm_password(signal, frame, secret="shhh"):
  password = raw_input("Enter password: ")

  if password == secret:
      sys.exit(0)
  else:
      print("Password incorrect.  Refusing to exit.")

while True:
    signal.signal(signal.SIGINT, confirm_password)
    time.sleep(1000)

rawDescription: Catching SIGINT with conditional exit in Python


code:
from random import randint, sample, choice

def create_random_list(length):
    return [randint(0, 100) for i in range(length)]

# This should be your list of four initial csv files
# with the 264 rows in total, read with the csv lib
lists = [create_random_list(264) for i in range(4)]

# Take a randomized sample from the lists
lists = map(lambda x: sample(x, 40), lists)

# Add some variables to the
lists = map(lambda x: {'data': x, 'full_count': 0}, lists)

final = [[] for i in range(4)]
for l in final:
    prev = None
    count = 0
    while len(l) < 40:
        current = choice(lists)

        if current['full_count'] == 10 or (current is prev and count == 3):
            continue
        # Take an item from the chosen list if it hasn't been used 3 times in a
        # row or is already used 10 times. Append that item to the final list

        total_left = 40 - len(l)
        maxx = 0
        for i in lists:
            if i is not current and 10 - i['full_count'] > maxx:
                maxx = 10 - i['full_count']

        current_left = 10 - current['full_count']
        max_left = maxx + maxx/3.0

        if maxx > 3 and total_left <= max_left:
            # Make sure that in te future it can still be split in to sets of
            # max 3
            continue

        l.append(current['data'].pop())
        count += 1
        current['full_count'] += 1

        if current is not prev:
            count = 0
            prev = current

    for li in lists:
        li['full_count'] = 0

rawDescription: How to randomly sample from 4 csv files so that no more than 2/3 rows appear in order from each csv file, in Python

description: Randomly sample from 4 csv files so that no more than 2/3 rows appear in order from each csv file, in Python


code:
data = """[your data]"""
data_new = ""
for line in data.splitlines():
    i = line.rfind("<")
    data_new += line if i == -1 else line[:i] + ". \n<1> " + line[i:] + "\n"
data_new = data_new.strip()

rawDescription: Split string to desired form using Python


code:
from selenium import webdriver

url = "http://fiddle.jshell.net/ebkXh/show/"
driver = webdriver.Firefox()
driver.get(url)

button = driver.find_element_by_xpath('//button[@type="submit"]')

# dismiss
button.click()
driver.switch_to.alert.dismiss()

# accept
button.click()
driver.switch_to.alert.accept()

rawDescription: How to check for webpages' popups?

description: Check for webpages' popups


rawDescription: scrapy selector xpath extract matching regex or slicing string

description: Scrapy selector xpath extract matching regex or slicing string


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

bins = np.linspace(0,120,13)

# my approximation of your example arrays
hist1 = np.arange(1.1,15, 1.1)
hist2 = np.arange(15, 1.1, -1.1)

all_weights = np.vstack([hist1, hist2]).transpose()
all_data = np.vstack([bins, bins]).transpose()
num_bins = len(bins)

plt.hist(x = all_data, bins = num_bins, weights = all_weights, stacked=True, align = 'mid', rwidth = .5)

rawDescription: Stacked histogram with bin heights defined in numpy array


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

plt.ion()

fig, ax = plt.subplots()

plot = ax.scatter([], [])
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)

while True:
    # get two gaussian random numbers, mean=0, std=1, 2 numbers
    point = np.random.normal(0, 1, 2)
    # get the current points as numpy array with shape  (N, 2)
    array = plot.get_offsets()

    # add the points to the plot
    array = np.append(array, point)
    plot.set_offsets(array)

    # update x and ylim to show all points:
    ax.set_xlim(array[:, 0].min() - 0.5, array[:,0].max() + 0.5)
    ax.set_ylim(array[:, 1].min() - 0.5, array[:, 1].max() + 0.5)
    # update the figure
    fig.canvas.draw()

rawDescription: Add points to matlibplot scatter plot live


rawDescription: Python Pandas replicate rows in dataframe


code:
class Adict(dict):
    pass

def myfunc(x):
    print(x, x.my_attr)

def my_builder(v, **kvargs):
    obj = Adict(v)
    obj.__dict__.update(kvargs)  # internal dictionary with attributes
    return obj                   # return the created object

# Your original code.
v = {'a':'cat'}
var = Adict(v)
var.my_attr = 'whatever'
myfunc(var)

print('------------')

v2 = {'d': 'dog'}
myfunc(my_builder(v2, my_attr='whatever_dog'))

print('------------')

myfunc(my_builder({'c': 'crocodile'}, my_attr='whatever_croc'))

rawDescription: Is there a way to set a value and an attribute of an object simultaneously?


code:
#!/usr/bin/env python

# example eventbox.py

import pygtk
pygtk.require('2.0')
import gtk

class EventBoxExample:
    def __init__(self):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_title("Event Box")
        window.connect("destroy", lambda w: gtk.main_quit())
        window.set_border_width(10)

        # Create an EventBox and add it to our toplevel window
        frame = gtk.EventBox() # gtk.Frame()
        window.add(frame)
        frame.show()
        frame.set_border_width(2)
        frame.modify_bg(gtk.STATE_NORMAL,
                            frame.get_colormap().alloc_color("blue"))

        event_box = gtk.EventBox()
        frame.add(event_box)
        event_box.set_border_width(10)
        event_box.show()

        # Create a long label
        label = gtk.Label("Click here to quit, quit, quit, quit, quit")
        event_box.add(label)
        label.show()

        # Clip it short.
        label.set_size_request(110, 20)

        # And bind an action to it
        event_box.set_events(gtk.gdk.BUTTON_PRESS_MASK)
        event_box.connect("button_press_event", lambda w,e: gtk.main_quit())

        # More things you need an X window for ...
        event_box.realize()
        event_box.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.HAND1))

        # Set background color to green
        event_box.modify_bg(gtk.STATE_NORMAL,
                            event_box.get_colormap().alloc_color("green"))

        window.show()

def main():
    gtk.main()
    return 0

if __name__ == "__main__":
    EventBoxExample()
    main()

rawDescription: Pygtk color for drag_highlight

description: Pygtk color for drag_highlight


code:
#!/usr/bin/env python3

c = 1
d = 1

b = 1
while True:
    a = 3 * b + c
    new_b = (a - d) / 5
    if b - new_b <= 0.25:
        break
    b = new_b

print(a, new_b)

rawDescription: How to compute mutually recursive expressions in a loop?

description: Compute mutually recursive expressions in a loop


rawDescription: Monitor Process in Python?

description: Monitor Process in Python


code:
import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

RGBlist = [(random.randint(0,255), random.randint(0,255), random.randint(0,255)) for i in range(100)]
paleta=zip(*RGBlist)
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(paleta[0],paleta[1],paleta[2], c=[(r[0] / 255., r[1] / 255., r[2] / 255.) for r in RGBlist])
ax.grid(False)
ax.set_title('grid on')
plt.savefig('blah.png')

rawDescription: RGB cube of an image

description: RGB cube of an image


code:
date = '30-Nov-2015'
driver.find_element_by_id("reportDate").send_keys(date)

rawDescription: How to give value to a drop down calendar using selenium and python

description: Give value to a drop down calendar using selenium and python


code:
def __unicode__(self):
  return self.name

rawDescription: django site administration (entering fixtures data)

description: Django site administration (entering fixtures data)


rawDescription: Python: Writing to a specific position in a text file


code:
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w, h

rawDescription: How can I get the coordinates of a sprite's position in pygame?

description: Get the coordinates of a sprite's position in pygame


code:
import tokenize
import ast

values = []

with open('input_file') as f:
    for token_type, token_string, _, _, _ in tokenize.generate_tokens(f.readline):
        # Ignore newlines and the file-ending dummy token.
        if token_type in (tokenize.ENDMARKER, tokenize.NEWLINE, tokenize.NL):
            continue
        values.append(ast.literal_eval(token_string))

rawDescription: how to easily read Python built-in types from a file

description: Easily read Python built-in types from a file


code:
zipfile = ZipFile(os.path.join(dest_dir, zip_name), 'w', ZIP_DEFLATED)
sys.path.insert(0, '.')
finder = ModuleFinder()
finder.run_script(source_name)

for name, mod in finder.modules.iteritems():
    filename = mod.__file__
    if filename is None:
        continue
    if "python" in filename.lower():
        continue

    subprocess.call('"%s" -OO -m py_compile "%s"' % (python_exe, filename))

    zipfile.write(filename, dest_path)

rawDescription: How to build a single python file from multiple scripts

description: Build a single python file from multiple scripts


code:
from django.template import Library
register = Library()

@register.filter
def split_timeuntil(duration):
    return duration.split(",")[0]

rawDescription: Finer control over Django timeuntil output possible?


code:
def zipdir(path, zip):
    path = os.path.abspath(path)
    for root, dirs, files in os.walk(path):
        dest_dir = root.replace(os.path.dirname(path), '', 1)
        for file in files:
            zip.write(os.path.join(root, file), arcname=os.path.join(dest_dir, file))

rawDescription: Python zipfile whole path is in file

description: Python zipfile whole path is in file


code:
p = subprocess.Popen("echo 'foo' && sleep 60 && echo 'bar'", shell=True)
p.kill()

rawDescription: Kill a running subprocess call

description: Kill a running subprocess call


code:
from Tkinter import *

root=Tk()

root.geometry('400x600')

root.update()

print (root.winfo_width())
print (root.winfo_height())
print (root.winfo_geometry())

root.mainloop()

rawDescription: Python Tkinter: Attempt to get widget size


code:
import re

m = re.search(r'\S+ highway', sentence)  # non-white-space followed by ' highway'
print(m.group())
# 'uhuru highway'

rawDescription: Using regular expressions in python to extract location mentions in a sentence


code:
import certifi
import ssl
import requests

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager

class Ssl3HttpAdapter(HTTPAdapter):
    def init_poolmanager(self, connections, maxsize, block=False):
        # specify the version of SSL you want to use below
        self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block,
                                       ssl_version=ssl.PROTOCOL_SSLv3)

s = requests.Session()

# May or may not need this. I needed it since I didn't need to route through a proxy to get to local services.
s.trust_env = False

s.verify = certifi.where()
s.auth = (user, password)  # Basic-Auth username/password

s.mount(base_url_of_your_service, Ssl3HttpAdapter())

req = s.get(your_service_url)
print(req.text)

rawDescription: Python 3.5 - Connection reset by peer

description: Python 3.5 - Connection reset by peer


code:
from gi.repository import Gtk, Gdk, GdkPixbuf

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_default_size(200, 200)

        self.liststore = Gtk.ListStore(str, str)
        self.treeview = Gtk.TreeView(model=self.liststore)

        self.liststore.append(["icon.png", "This is a symbol1"])

        px_renderer = Gtk.CellRendererPixbuf()
        px_column = Gtk.TreeViewColumn('')
        px_column.pack_start(px_renderer, False)
        str_renderer = Gtk.CellRendererText()
        px_column.pack_start(str_renderer, False)
        # set data connector function/method
        px_column.set_cell_data_func(px_renderer, self.get_tree_cell_pixbuf)
        px_column.set_cell_data_func(str_renderer, self.get_tree_cell_text)
        self.treeview.append_column(px_column)

        self.add(self.treeview)

    def get_tree_cell_text(self, col, cell, model, iter, user_data):
        cell.set_property('text', model.get_value(iter, 1))

    def get_tree_cell_pixbuf(self, col, cell, model, iter, user_data):
        cell.set_property('pixbuf', GdkPixbuf.Pixbuf.new_from_file(model.get_value(iter, 0)))

if __name__ == '__main__':
    win = MyWindow()
    win.connect("delete-event", Gtk.main_quit)
    win.show_all()
    Gtk.main()

rawDescription: Show icon or color in Gtk TreeView tree

description: Show icon or color in Gtk TreeView tree


code:
if tx_avt >= 100: tx = 1
elif tx_avt >= 50: tx = 2
elif tx_avt >= 25: tx = 3
elif tx_avt >= 12.5: tx = 4
else: tx = 5

rawDescription: Is there a better way to write this "if" boolean evaluation?


code:
from django.contrib.auth.models import User
len(User._meta.fields)
len(User._meta.many_to_many)

rawDescription: Django getting the number of fields of a model


code:
def startdump():
    global DUMPCAP, dumpdirectory, proc1
    global eventfile, dc_capfile

    DUMPCAP = ''
    print("========================[ MAIN DUMPCAP MONITORING ]===========================")
    setDumpcapOptions()
    os.chdir(dumpdirectory)
    if platform == "Linux":
        DUMPCAP = "dumpcap " + DUMPCAP
    elif platform == "Windows":
        DUMPCAP = "dumpcap.exe " + DUMPCAP
    proc1 = subprocess.Popen(DUMPCAP, shell=True, stderr=subprocess.PIPE)
    #procPID = proc1.pid
    if dc_mode == "Dumpcap Only":
        time.sleep(5)
        with open("proc1stderr.txt", 'w+') as proc1stderr:
            proc1stderr.write(str(proc1.stderr))
            for line in proc1.stderr:
                print("%s" % line)
                if "File:" in line:
                    print(line)
                    raweventfile = line.split('File: ')[1]
                    eventfile = raweventfile.strip('\[]').rstrip('\n')
                    mail_man()
            proc1.communicate()

rawDescription: Parse filename from Dumpcap output

description: Parse filename from Dumpcap output


code:
class _MyClass(object):
    pass

def MyClass(*args, **kw):
    if not "my_class_object" in all_objects:
         all_objects["my_class_object"] = _MyClass(*args, **kw)
    return all_objects["my_class_object"]

rawDescription: Should I use __new__ to prevent instantiation?


code:
if str.lower(char) in "aeiou":
    ...

rawDescription: How do I make this long if statement less cumbersome?

description: Make this long if statement less cumbersome


code:
with open('file.txt', 'r') as f:
    for line in f:
        if line.startswith('1113'):
            line = line.split()
            x = int(line[1])
            y = int(line[2])

rawDescription: In python, how can I search a specific column for a specific value in a txt file then return the specific value's row?


code:
myString = 'Johnny picked an APPLE from the tree'
slicedString = myString[:25]
# do regex matching on slicedString

rawDescription: REGEX to check for phrase within first 25 characters


rawDescription: Draw Box-Plot with matplotlib

description: Draw Box-Plot with matplotlib


code:
initial = cache.get("foo_modelchoice_initial")
if initial is None:
    initial = Foo.objects.get(pk=14)
    cache.set("foo_modelchoice_initial", initial)

foo = ModelChoiceField(label="Foo label",
                   queryset=Foo.objects.all(),
                   initial=initial)

rawDescription: Efficient ModelChoiceField initial data

description: Efficient ModelChoiceField initial data


code:
fill = np.zeros(array_length)     #  array_length = 10
fill[indexes] = 1                 #  indexes = [2,5,6]
fill

rawDescription: (Numpy) Index list to boolean array

description: (Numpy) Index list to boolean array


code:
self.response.out.write("""

     <form action="/sign" method="post">

<textarea name="content" rows="3" cols="60"></textarea>

<input type="submit" value="Sign Guestbook">

     </form> """.format( ('Red','Blue','Black','Green') ))
self.response.out.write('
')

rawDescription: Google App Engine Python HTML Table

description: Google App Engine Python HTML Table


code:
foobar = Foo.bar.label("foobar")
session.query(foobar).filter(foobar > 10).all()

rawDescription: python sqlalchemy label usage

description: Python sqlalchemy label usage


code:
def close(self):
    self.session.close()
    self.db.dispose()

rawDescription: sqlalchemy mysql connections not closing on flask api

description: Sqlalchemy mysql connections not closing on flask api


code:
import numpy as np

def add_word_as_ordinal(arr, word):
    arr.extend([ord(ch) for ch in word])
    return arr

def char_array_to_ascii_matrix(char_array):
    result = np.matrix(reduce(add_word_as_ordinal, char_array, []))
    result.shape = len(char_array), len(char_array[0])
    return result

my_array = np.array("JustA Flesh Wound".split())
my_matrix = char_array_to_ascii_matrix(my_array)

rawDescription: convert string numpy array to a ascii numpy matrix

description: Convert string numpy array to a ascii numpy matrix


code:
class Role(DeclarativeBase):
    __tablename__ = 'role'
    id = Column(Integer, primary_key=True)
    role_type = Column(String)
    employee_id = Column(Integer, ForeignKey('employee.id'))
    employee = relationship('Employee', backref='roles')

    __mapper_args__ = {
        'polymorphic_identity': 'employee',
        'polymorphic_on': role_type
    }

class SalesRole(Role):
    __tablename__ = 'sales_role'
    id = Column(Integer, ForeignKey('role.id'), primary_key=True)

    __mapper_args__ = {
        'polymorphic_identity': 'sales_role'
    }
    # Sales-specific attributes, etc.

class CustomerSupportRole(Role):
    __tablename__ = 'support_role'
    id = Column(Integer, ForeignKey('role.id'), primary_key=True)

    __mapper_args__ = {
        'polymorphic_identity': 'support_role'
    }
    # Support-specific attributes, etc.

rawDescription: How to define (or simulate) a collection containing different types in SQLAlchemy?

description: Define (or simulate) a collection containing different types in SQLAlchemy


code: s[1:-1]     # skip the first and last character

rawDescription: python 2.7 remove brackets

description: Python 2.7 remove brackets


code:
from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from django.views.static import serve
from django.conf import settings

from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import HttpResponse

@login_required
def protected_serve(request, path, document_root=None):
    try:
        obj = Photobox.objects.get(user=request.user.id)
        obj_image_url = obj.image.url
        correct_image_url = obj_image_url.replace("/media/", "")
        if correct_image_url == path:
            return serve(request, path, document_root)
    except ObjectDoesNotExist:
        return HttpResponse("Sorry you don't have permission to access this file")

url(r'^{}(?P<path>.*)$'.format(settings.MEDIA_URL[1:]), protected_serve, {'file_root': settings.MEDIA_ROOT}),

rawDescription: How to to make a file private by securing the url that only authenticated users can see

description: To make a file private by securing the url that only authenticated users can see


code:
df
results
df.set_index(['group1', 'group2'], inplace=True)['results'] = results
df
df.reset_index()

rawDescription: Joining a Pandas series with a hierarchical index back to the source DataFrame


rawDescription: quick question: clear an attribute of a model in django

description: Quick question: clear an attribute of a model in django


code:
def do_process(command, text):
    enc = 'cp866'
    p = Popen(command, stdout=PIPE, stdin=PIPE, stderr=PIPE)
    out, err = p.communicate(text.encode())
    return out.decode(enc)

rawDescription: Example to call subprocess with cmd.exe

description: Example to call subprocess with cmd.exe


code:
import os
import glob

dir = os.getcwd()

for (path, subdirs, files) in os.walk(dir):
    os.chdir(path)
    if glob.glob("*.mp3") != []:
        _m3u = open( os.path.split(path)[1] + ".m3u" , "w" )
        for song in glob.glob("*.mp3"):
            _m3u.write(song + "\n")
        _m3u.close()

os.chdir(dir) # Not really needed..

rawDescription: Python module to create music playlist (windows)


code:
def __setattr__(self, name, value):
    if hasattr(super(Clazz, self), name):
        setattr(super(Clazz, self), name, value)
    else:
        # implement *my* __setattr__
        pass

rawDescription: __setattr__ only for names not found in the object's attributes`?


code:
x = queue.Queue()
x.unfinished_tasks
x.put("test")
x.unfinished_tasks

rawDescription: Python Queue Count of Unfinished Tasks

description: Python Queue Count of Unfinished Tasks


code:
result=[{ 'type': 'O', 'count': 54},{ 'type': 'E', 'count': 125},{ 'type': 'C', 'count': 2}]

result_as_dict=dict([(type_and_count['type'], type_and_count['count']) for type_and_count in result])

print(result_as_dict)

rawDescription: Django creating aliased query outputs

description: Django creating aliased query outputs