code:
from app.models import MyModel

a = MyModel(field=value)
a.save()

rawDescription: python django automated data addition

description: Python django automated data addition


code:
for x in array1 if opt1 else array2 if opt2 else []:
    ...

rawDescription: Different for-"definitions/conditions but same execution code


rawDescription: Numpy: Add rows from one matrix to another by index


code:
('SECTION', '1')
('SOME LINE', 'some line')

rawDescription: How do I tokenize a file with Python as a sequence of regular expressions?

description: Tokenize a file with Python as a sequence of regular expressions


rawDescription: Iterate over vectors in a multidimensional numpy array


code:
def join_lists(*args):
    out = []
    for L in args:
        for i in L:
            out.append(i)
    return out

rawDescription: concatenate splatted lists

description: Concatenate splatted lists


rawDescription: Get the value of a tag which has another tag before its value with BeautifulSoup


code:
plain_body = render('plain_email.mako', opts, request)
html_body = render('html_email.mako', opts, request)
msg = Message(body=plain_body, html=html_body)

rawDescription: Turbomail Integration with Pyramid

description: Turbomail Integration with Pyramid


rawDescription: Pandas, unexpected behavior of .resample('B')


rawDescription: What's wrong with my def function? how to fix it?


rawDescription: Python Pandas: print the csv data in oder with columns


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

class DummyPlot(object):
    def __init__(self):
        self.imsize = (10, 10)
        self.data = np.random.random(self.imsize)

        self.fig, self.ax = plt.subplots()
        self.im = self.ax.imshow(self.data)

        buttonax = self.fig.add_axes([0.45, 0.9, 0.1, 0.075])
        self.button = Button(buttonax, 'Update')
        self.button.on_clicked(self.update)

    def update(self, event):
        self.data += np.random.random(self.imsize) - 0.5
        self.im.set_data(self.data)
        self.im.set_clim([self.data.min(), self.data.max()])
        self.fig.canvas.draw()

    def show(self):
        plt.show()

p = DummyPlot()
p.show()

rawDescription: Preserve zoom settings in interactive navigation of matplotlib figure


code:
f = open('e:\\text.txt','rb')
content = f.read().decode('utf-8')
content

rawDescription: How to print non-ascii characters to file in Python 2.7

description: Print non-ascii characters to file in Python 2.7


code:
checkbox = Wizard['Create Shortcut on Desktop'].Wait('enabled')
if checkbox.GetCheckState() != pywinauto.win32defines.BST_CHECKED:
    checkbox.Click()

rawDescription: Python - Control window with pywinauto while the window is minimized or hidden


code: print("....", file=f)

rawDescription: Redirecting the print output to a .txt file in Python


code:
def song_decoder(song):
    # replace the WUBs and strip spaces
    song = song.replace("WUB", " ").strip()
    ret = ''

    space = False
    # instead of iterating over the length, just iterate over
    # the characters of the string
    for c in song:
        # since we iterate over the string, we don’t need to check
        # where it ends

        # check for spaces
        if c == " ":
            # space is a boolean, so don’t compare it against booleans
            if not space:
                space = True
            else:
                # if we saw a space before and this character is a space
                # we can just skip it
                continue
        else:
            space = False

        # if we got here, we didn’t skip a later space, so we should
        # include the current character
        ret += c

    return ret

rawDescription: Remove repeating spaces manually in a string


code: print([obj.attr for obj in my_list_of_objs])

rawDescription: python - readable list of objects

description: Python - readable list of objects


code: c.IPCompleter.limit_to__all__ = True

rawDescription: Hide imported modules to interpreter

description: Hide imported modules to interpreter


code:
my_dict = dict.fromkeys(keys, [])
my_dict
my_dict['k3'].append(1)
my_dict

rawDescription: Add items to a dictionary of lists

description: Add items to a dictionary of lists


rawDescription: Regular expression for class using Beautifulsoup


rawDescription: PySpark - Combining Session Data without Explicit Session Key / Iterating over All Rows


rawDescription: consensus score and WSP score in python

description: Consensus score and WSP score in python


rawDescription: Python RE: how can I neglect empty space between tags?


code:
# file_data is the text of the file, not the filename
reader = csv.DictReader(file_data, ("title", "value"))
for i in reader:
  list_of_stuff.append(i)

rawDescription: Using Python's csv.dictreader to search for specific key to then print its value


code:
class ParentClass:
    def f(self):
        print("Hi!");

class ChildClass(ParentClass):
    def f(self):
        super(ChildClass, self).f();
        print("Hello!");

rawDescription: Adding extra functionality to parent class method without changing its name


code: np.unique(df[['Col1', 'Col2']].values)

rawDescription: pandas unique values multiple columns

description: Pandas unique values multiple columns


code:
My_List = [['This', 'Is', 'A', 'Sample', 'Text', 'Sentence'],
           ['This', 'too', 'is', 'a', 'sample', 'text'],
           ['finally', 'so', 'is', 'this', 'one']]
GG_List = ['This', 'Sentence']
FF_List = ['Is', 'A', 'Text']
EE_List = ['Sample']

zipped = zip((GG_List, FF_List, EE_List), ('GG', 'FF', 'EE'))
tags = {item: tag for tag_list, tag in zipped for item in tag_list}
res = [[(word, tags[word]) for word in entry if word in tags] for entry in My_List]

rawDescription: PYTHON 2.7 - Modifying List of Lists and Re-Assembling Without Mutating


code:
# lastdup will be a map from line content to the line number the
# last duplicate was found. On first insertion the value is None
# to mark the line is not a duplicate
lastdup = {}
for n, L in enumerate(f):
    if L in lastdup:
        lastdup[L] = n
    else:
        lastdup[L] = None

# Now all values that are not None are the last duplicate of a line
result = sorted(x for x in lastdup.values() if x is not None)

rawDescription: Find double lines; a faster way

description: Find double lines; a faster way


code:
xl = win32com.client.Dispatch("Excel.Application")
xl.ActiveWorkbook.FullName

rawDescription: Get name of active Excel workbook from Python


code:
for gene in genes:
    if gene in text:
        print('True')

rawDescription: python search for a set of words

description: Python search for a set of words


code:
def _show_auto_complete(self, view):
    def _show_auto_complete():
        view.run_command('auto_complete', {
            'disable_auto_insert': True,
            'api_completions_only': True,
            'next_completion_if_showing': False,
            'auto_complete_commit_on_tab': True,
        })
    # Have to set a timeout for some reason
    sublime.set_timeout(_show_auto_complete, 0)

rawDescription: Sublime Text 3 Stop Auto-Complete From Committing on 'Space'


rawDescription: Parsing a table with rowspan and colspan


code:
import regex
char = u'A\u030a'
print(char)
len(char)
regex.findall(r'\X', char)
len(regex.findall(r'\X', char))

rawDescription: Calculate bytes of the unicode character in python


code:
df.index.set_levels([u'Total', u'x2'],level=1,inplace=True)
df.index.set_labels([0, 1],level=1,inplace=True)

rawDescription: Replace a value in MultiIndex (pandas)

description: Replace a value in MultiIndex (pandas)


code:
Names = ['John', 'James', 'Barry', 'Greg', 'Jenny']
Results1 = ['James', 'Barry', 'Jenny', 'Greg', 'John']
Results2 = ['Barry', 'Jenny', 'Greg', 'James', 'John']

Order1 = dict((name,order) for order,name in enumerate(Results1))
Order2 = dict((name,order) for order,name in enumerate(Results2))

score = [[0]*len(Names) for y in range(len(Names))]

for i,name1 in enumerate(Names):
    for j,name2 in enumerate(Names):
        if name1 in Order1 and name2 in Order1 and Order1[name1] > Order1[name2] and name1 in Order2 and name2 in Order2 and Order2[name1] > Order2[name2]:
            score[i][j] = 1

rawDescription: Comparing list values by index in Python


code: lambda v: all(map(v.test, List)) # You should not use List as a variable name!

rawDescription: How to make my code more Pythonic?

description: Make my code more Pythonic


rawDescription: Calculate weighted average using a pandas/dataframe


code:
ax = df1.plot(x='Lat', y='Lon')
df2.plot(ax=ax, x='Lat', y='Lon')

rawDescription: Plotting multiple dataframes using pandas functionality


code:
def run_timed_method():
    return_queue = multiprocessing.Manager().Queue()
    pool = multiprocessing.Pool()
    result = pool.apply_async(_timed_method_wrapper, args=(self, return_queue))

rawDescription: Limit function execution in Python

description: Limit function execution in Python


code: d = dict(map(lambda x: x.strip().replace('<br>', ''), a.split('=', 1)) for a in l)

rawDescription: Remove repeated elements from list and HTML Tag


rawDescription: Remove track from playlist with soundcloud Python


code:
A
np.where(A==7)

rawDescription: Python: list vs. np.array: switching to use certain attributes


code:
st=str(str1)
arr=np.array(list(st))
mask=map(str.isalpha,st)
mask
arr[~mask]

rawDescription: Functional masking of numpy string array in Python


code:
n, bins, patches = plt.hist([setA,setB,setC], bins=mybins,
                            label = ['setA','setB','setC'],
                            normed=True, stacked=True)

rawDescription: Normalising Histograms Matplotlib

description: Normalising Histograms Matplotlib


rawDescription: Django - Where to write code for easy-thumnails custom THUMBNAIL_NAMER?


code:
n = b.shape[1]
mask = (np.arange(n) >= a[:,None,0]) & (np.arange(n) <= a[:,None,1])
d = mask*b

rawDescription: Python - numpy : 'dimension dependent indexing'


code: soup.find_all('td', class_=lambda x: x != 'foo')

rawDescription: BeautifulSoup4: select elements where attributes are not equal to x


code:
A
B
C

rawDescription: Remove rows from numpy array based on presence/absence in other arrays


code:
string = Series(np.random.choice(df.string.values, size=100), name='string')
visits = Series(poisson(1000, size=100), name='date')
date = Series(np.random.choice([df.date[0], now(), Timestamp('1/1/2001'), Timestamp('11/15/2001'), Timestamp('12/1/01'), Timestamp('5/1/01')], size=100), dtype='datetime64[ns]', name='date')
df = DataFrame({'string': string, 'visits': visits, 'date': date})
df.head()
resamp = df.set_index('date').groupby('string').resample('M', how='sum')
resamp.head()

rawDescription: Grouping daily data by month in python/pandas and then normalising


code:
regex = re.compile("file:///c:/[^/]+/([.]+)\.json#/")
replacer = lambda g: '<xmlns="http://blahblah.com/sub1//{0}.md">{0} /xxxx/'.format(g.groups()[0])

with open("output.txt","w") as f:
    for line in open("input.txt"):
         f.write(re.sub(regex,replacer,line))

rawDescription: how to edit a line (overwright and replace) in python

description: Edit a line (overwright and replace) in python


rawDescription: String Mirror Function

description: String Mirror Function


code: server = [getServers(i) for i in grouplist]

rawDescription: My first python program: can you tell me what I'm doing wrong?


code:
from difflib import Differ
difference = []
for d in Differ().compare(text_1, text_2):
    difference.append(d)

rawDescription: Delta words between two TXT files

description: Delta words between two TXT files


rawDescription: Regex to extract characters within json

description: Regex to extract characters within json


code: temp_arr = [value[0]['firstName'] for value in json_obj.itervalues()]

rawDescription: JSON object array parsing in django

description: JSON object array parsing in django


code:
class Meta(type):

    @property
    def __doc__(self):
        return self.attributes_string()

class Foo(object):
    """My doc string
    """

    __metaclass__ = Meta

    @classmethod
    def default_attributes(cls):
        return {'foo':'description of foo attribute',
                'bar':'description of bar attribute'}

    @classmethod
    def attributes_string(cls):
        attributes = cls.default_attributes()
        result = '\nDefault Attributes:\n'
        for key, value in attributes.items():
            result += '%s: %s\n' % (key, value)
        return result

rawDescription: How to modify class docstrings using classmethods

description: Modify class docstrings using classmethods


code:
# Import Django's standard feed view.
from django.contrib.auth.decorators import login_required
from django.django.contrib.syndication.views import feed

# Wrap it in a new feed view that requires authentication!
private_feed = login_required(feed)

rawDescription: Django RSS Feed Authentication

description: Django RSS Feed Authentication


code:
s = Popen('svn log', shell=True, stdout=PIPE).communicate()[0]
m = re.search('\r\nr(?P<rev>\d+)\s+\|\s+(?P<author>\w+)\s+\|\s+(?P<timestamp>.*?)\s|', s)

rawDescription: How do I poll the subversion history/log remotely from python?

description: Poll the subversion history/log remotely from python


rawDescription: Python tuple to json structure

description: Python tuple to json structure


rawDescription: cluster points after KMeans clustering (scikit learn)

description: Cluster points after KMeans clustering (scikit learn)


code:
x = np.sin(t) + np.sin(3*t) + np.sin(5*t)
f = np.fft.rfft(x)
np.round(np.abs(f), 0)

rawDescription: How to Make Sense of Fourier Transform Results in Audio Frequency Analysis


code: np.array([1+0j, 2+0j]).real

rawDescription: Numbers ending with j

description: Numbers ending with j


code:
with open("followers.txt", 'a') as f:     #open file first
    for page in tweepy.Cursor(api.followers, screen_name='handle').pages():
        for user_obj in page:   #iterate through each User object
            json.dump(user_obj._json, f)  #dump each to file, f
            f.write("\n")  #you'll need this for Martjin's answer below to work.

rawDescription: Extracting data in Tweepy in useable form (JSON)


code:
import numpy
from scipy import signal

data_length = 8192

a = numpy.random.randn(data_length)
b = numpy.zeros(data_length * 2)

b[data_length/2:data_length/2+data_length] = a # This works for data_length being even

# Do an array flipped convolution, which is a correlation.
c = signal.fftconvolve(b, a[::-1], mode='valid')

# Use numpy.correlate for comparison
d = numpy.correlate(a, a, mode='same')

# c will be exactly the same as d, except for the last sample (which
# completes the symmetry)
numpy.allclose(c[:-1], d) # Should be True

rawDescription: Fast cross correlation method in Python

description: Fast cross correlation method in Python


code:
class football:
    def __init__(self,qb,num):
        self.qb = qb
        self.num = num

    def __str__(self):
        return self.qb + ", " + self.num
teams = {
"Niners" : football("Gabbert", "02" ),
"Bears" : football("CUTLER, JAY","06"),
"Bengals" : football ("Dalton, Andy","14"),
"Bills" : football (" Taylor, Tyrod", "05")} #etc
#I didn't include the whole dictionary for brevity's sake

def decor(func):
    def wrap():
        print("===============================")
        func()
        print("===============================")
    return wrap

def print_text():
    print("Who\s your NFL Quarterback? ")

decorated = decor(print_text)
decorated()

team = input("Enter your teams name here:").capitalize()
print(teams[team])

rawDescription: calling class with user input

description: Calling class with user input


rawDescription: Generating list of iterations on own output in Python


code: males = df[(df[Gender]=='Male') & (df[Year]==2014)]

rawDescription: how do you filter pandas dataframes by multiple columns

description: Filter pandas dataframes by multiple columns


code: newlist = [ list(filter(bool, x)) for x in oldlist ]

rawDescription: How do I create a new list with specific items from an old list in Python 2?

description: Create a new list with specific items from an old list in Python 2


code: re.findall(r'{([^}]+)}', inputtext)

rawDescription: Python regex parsing string containing braced items


code:
csvList = []
for suffix in ('US-CIR', 'US-PIR', 'DS-PIR'):
    for item in glob.glob(filepath + '\\*{}.csv'.format(suffix))[:1]:
        csvList.append(item)

rawDescription: custom ordering list using glob.glob in python

description: Custom ordering list using glob.glob in python


code:
import re
len(re.findall("X+", s))

rawDescription: Count character repeats in Python

description: Count character repeats in Python


rawDescription: iterate through unicode strings and compare with unicode in python dictionary

description: Iterate through unicode strings and compare with unicode in python dictionary


code: [sum(l, []) for l in zip(*lists)]

rawDescription: How to use *args to combine multiple lists?

description: Use *args to combine multiple lists


code:
def partition2(max_range, max_sum):
    max_range = np.asarray(max_range, dtype = int).ravel()
    if(max_range.size == 1):
        return np.arange(min(max_range[0],max_sum) + 1, dtype = int).reshape(-1,1)
    P = partition2(max_range[1:], max_sum)
    # S[i] is the largest summand we can place in front of P[i]
    S = np.minimum(max_sum - P.sum(axis = 1), max_range[0])
    offset, sz = 0, S.size
    out = np.empty(shape = (sz + S.sum(), P.shape[1]+1), dtype = int)
    out[:sz,0] = 0
    out[:sz,1:] = P
    for i in range(1, max_range[0]+1):
        ind, = np.nonzero(S)
        offset, sz = offset + sz, ind.size
        out[offset:offset+sz, 0] = i
        out[offset:offset+sz, 1:] = P[ind]
        S[ind] -= 1
    return out

rawDescription: Generating a numpy array with all combinations of numbers that sum to less than a given number


code:
umap = {ord(key):unicode(val) for key, val in umlautDictionary.items()}
for filename in filePathsList:
    filename = filename.translate(umap)
    print(filename)

rawDescription: Python - Transliterate German Umlauts to Diacritic


code:
def hueShift(img, amount):
    arr = np.array(img)
    hsv = rgb_to_hsv(arr)
    hsv[..., 0] = (hsv[..., 0]+amount) % 1.0
    rgb = hsv_to_rgb(hsv)
    return Image.fromarray(rgb, 'RGB')

filename = 'without_colorize.jpg'
basename, ext = os.path.splitext(filename)
img = Image.open(filename).convert('RGB')
for amount in (50, 133):
    img2 = hueShift(img, amount/360.)
    out_name = '{}_hue{:+03d}.jpg'.format(basename, int(amount))
    img2.save(out_name)

rawDescription: RGB to HSV Python, change Hue continuously


code:
from collections import defaultdict

A = [6, 6, 3, 2, 5, 2, 3]
B = [1, 2, 3, 3, 4, 6, 7]

purchase_dict = defaultdict(list)
for key, value in zip(A, B):
     purchase_dict[key].append(value)

rawDescription: Is there a more time-wise efficient way to populate a dictionary


code: indices = np.random.randint(0, 512**2, size=(50**4))

rawDescription: How do I use Python multiprocessing to get rid of nested while loops

description: Use Python multiprocessing to get rid of nested while loops


code:
def dictionary_tuples(key, values):
    return [(key, item) for item in values[key]]

dictionary_tuples(a, graph)

rawDescription: Python Build tuples from a dictionary with key and multiple values


code: a, b, c = objectCase()

rawDescription: How to call an object created in a module

description: Call an object created in a module


code:
for beta in [0, np.pi/3, np.pi/2]:
    pylab.plot(*class2(np.linspace(0, np.pi, 100), beta),
               label='$\\beta={:.3f}$'.format(beta))
pylab.legend()

rawDescription: Parametric equation with numpy

description: Parametric equation with numpy


rawDescription: How can I compare corresponding items in a python dictionary?

description: Compare corresponding items in a python dictionary


code:
['<</Producer(AFPL Ghostscript 8.11)', '/CreationDate(D:20040910110429)',
 '/ModDate(D:20040910110429)', '/Creator(PDFCreator Version 0.8.0)']

rawDescription: Without using any additional libraries, how would someone approach the challenge of reading the metadata of .pdf files in Python?


code:
def count():
        if last_ip != ip:
                c.execute("INSERT INTO dl VALUES ('%d', '%s', '%s', '%s')" % (index, dt, ip, client))
                conn.commit()
                conn.close()

rawDescription: Download counter: cgi FieldStorage reset pressed button values


code:
import json
s = " query : {'names' :['abc','xyz'],'location':'India'}"
key, value = s.strip().split(':', 1)
r = value.replace("'", '"')
data = {
    key: json.loads(r)
}

rawDescription: Converting a MongoDB Query String with Datetime field into Dict in Python


rawDescription: Split a list of tuples into sub-lists of the same tuple field


code: final_matrix = tmp1 + 1j * tmp2

rawDescription: How to split a matrix in two in python in a memory effecient way?

description: Split a matrix in two in python in a memory effecient way


code:
newImage.setPixel(4*r, 4*c, pixel)
newImage.setPixel(4*r, 4*c+1, pixel)
newImage.setPixel(4*r, 4*c+2, pixel)
newImage.setPixel(4*r, 4*c+3, pixel)

rawDescription: Rescale an Image using Python3.2

description: Rescale an Image using Python3.2


code:
def check_margin(self, cr, uid, ids, product_id, unit_price, context=None):
  res = {}
  warning = {}
  sale_price = None
  if product_id:
     sale_price = self.pool.get('product.product').browse(cr, uid,product_id).list_price
  if unit_price is None:
     pass
  elif unit_price < sale_price:
     warning = {
       'title': _("Warning"),
       'message': _('Unit price given, is less than the sales price of the selected product. Please change (or contact your sales manager to change) the sales price of the selected product.'),
               }
     res = {'value': {'price_unit':sale_price}}
  elif unit_price >= sale_price:
     res = {'value': {'price_unit':unit_price}}
     pass
  return {'value': res.get('value'), 'warning':warning}

rawDescription: Don't allow to quote below the sales price of a product in openerp


code:
class SSEHandler(sse.Handler):

    #...

    @classmethod
    def broadcast(cls, message):
        for instance, future in cls._instances.items():
            instance.send(message)

class Telnet(asyncio.Protocol):

    #...

    def data_received(self, data):
        #...
        SSEHandler.broadcast(data.decode('ascii'))

rawDescription: Python - Communicate between asyncio protocol/servers


code:
def fftnoise(f):
    f = np.array(f, dtype='complex')
    Np = (len(f) - 1) // 2
    phases = np.random.rand(Np) * 2 * np.pi
    phases = np.cos(phases) + 1j * np.sin(phases)
    f[1:Np+1] *= phases
    f[-1:-1-Np:-1] = np.conj(f[1:Np+1])
    return np.fft.ifft(f).real

rawDescription: How to generate noise in frequency range with numpy?

description: Generate noise in frequency range with numpy


code: for x in funB(): yield x

rawDescription: Python - is there any way to organize a group of yields in sub function to yield outside the main function?


rawDescription: Python regular expression to change date formatting


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

def main():
    textFileName = 'C:\\temp\\001.txt'
    total = 0
    for line in open(textFileName):

        total += len(line.split())
    print(total, "words")
main()

rawDescription: How do I count the words in a string using only loops and string.strip()?

description: Count the words in a string using only loops and string.strip()


code:
if n == 1:
    return fn

rawDescription: Recursive function using lambda expression


code:
#Change MyPaintApp to the following...
class MyPaintApp(App):
    def build(self):
        return MyPaintWidget()

rawDescription: How to fill canvas with an image in kivy?

description: Fill canvas with an image in kivy


rawDescription: Finding the longest (deepest) chain in a Tree and summing the TreeNodes?


code:
import binascii

s1 = '\\xd0\\xb1'
print('s1 =', repr(s1), '=', list(s1))            # list() to emphasize what are the characters

s2 = s1.replace('\\x', '')
print('s2 =', repr(s2))

b = binascii.unhexlify(s2)
print('b =', repr(b), '=', list(b))

s3 = b.decode('utf8')
print('s3 =', ascii(s3))

with open('output.txt', 'w', encoding='utf-8') as f:
    f.write(s3)

rawDescription: Decoding bytes as unicode string

description: Decoding bytes as unicode string


rawDescription: Capture multiple words in group

description: Capture multiple words in group


code:
cv.WarpPerspective(cv.fromarray(im), out_2, cv.fromarray(h))
cv.ShowImage("test", out_2)
cv.SaveImage("result.png", out_2)
cv2.waitKey()

rawDescription: How to show the whole image when using OpenCV warpPerspective

description: Show the whole image when using OpenCV warpPerspective


rawDescription: How to split a string at line breaks in python?

description: Split a string at line breaks in python


code:
profdir = '~/.config/mozilla'
profile = 'foo'
mozembed.set_profile_path(profile_directory, profile)

rawDescription: How to set User-Agent in Python MozEmbed?

description: Set User-Agent in Python MozEmbed


code:
s='6800       MAIN ST'
' '.join(s.split())

rawDescription: Python - Getting Rid of Spaces in String


code: onestep = node.next

rawDescription: Tail-Loop Puzzle with a Linked list - My Python solution is Failing when tail is longer than loop


code:
if day == 'Sat':
    print('Sat')

rawDescription: Checking if today is a Wed or Sat with java.util.Calendar


rawDescription: Python - returning something as an object instead of string


code:
with open('file', 'w') as f:
    f.write(format_string.format(list[0], list[1], list[2]))

rawDescription: Writing Python lists into file, items seperated by semicolon


code:
import datetime
datetime.datetime.now()
d1 = datetime.datetime.now()
d2 = datetime.datetime(2014, 2, 2, 13, 0, 0, 0)
d1 - datetime.timedelta(days=4*365./12) > d2
from dateutil.relativedelta import relativedelta
d1 - relativedelta(month=4)
d1 - relativedelta(month=4) > d2

rawDescription: python django converting date values in months or days

description: Python django converting date values in months or days


code:
def count(n):
    sum = 0
    for i in range(1, n+1):
            sum+=1.0/i
    return sum

count(4)
count(1)
count(2)
count(3)
count(4)

rawDescription: Writing a python program takes an int argument and adds 1+1/2+1/3+1/4....1/n


code:
table = pd.crosstab([df.c1,df.c2], [df.c3,df.c4], values=df.val, aggfunc=[len, np.mean])
table
table.reorder_levels([1, 2, 0], axis=1).sort_index(axis=1)

rawDescription: how to use two different functions within crosstab/pivot_table in pandas?

description: Use two different functions within crosstab/pivot_table in pandas


code:
def project_points(x, y, z, a, b, c):
    """
    Projects the points with coordinates x, y, z onto the plane
    defined by a*x + b*y + c*z = 1
    """
    vector_norm = a*a + b*b + c*c
    normal_vector = np.array([a, b, c]) / np.sqrt(vector_norm)
    point_in_plane = np.array([a, b, c]) / vector_norm

    points = np.column_stack((x, y, z))
    points_from_point_in_plane = points - point_in_plane
    proj_onto_normal_vector = np.dot(points_from_point_in_plane,
                                     normal_vector)
    proj_onto_plane = (points_from_point_in_plane -
                       proj_onto_normal_vector[:, None]*normal_vector)

    return point_in_plane + proj_onto_plane

rawDescription: orthogonal projection with numpy

description: Orthogonal projection with numpy


code:
import re

def replacer(match):
    return match.group(1).upper()

rawString = "{{prefix_HelloWorld}}   testing this. {{_thiswillNotMatch}} {{prefix_Okay}}"
result = re.sub(r'\{\{prefix_(.+?)\}\}', replacer, rawString)

rawDescription: Python string.replace equivalent (from Javascript)


code:
#!/usr/bin/env python
import json
import sys
from subprocess import check_output

output = check_output([sys.executable, 'child.py'])
x, y = json.loads(output.decode())

rawDescription: Python subprocess.Popen : sys.stdout vs .txt file vs Cpickle.dump


rawDescription: beautifulsoup table tree: find all tr between two objects?

description: Beautifulsoup table tree: find all tr between two objects


code:
mlen = max([len(x) for x in duplicates])
padded_dups = [np.pad(x,(0,mlen-len(x)),'edge') for x in duplicates]
labels[np.array(padded_dup)]

array([[2, 3, 3],
       [3, 2, 2],
       [0, 0, 0]])

rawDescription: Access 1D array with array of lists or arrays


rawDescription: Get nested arrays out of a dictionary

description: Get nested arrays out of a dictionary


rawDescription: Unescape unicode-escapes, but not carriage returns and line feeds, in Python


code:
if request.method == "POST":
     book_id = request.POST['book_id']

rawDescription: How can I access data sent in a post request in Django?

description: Access data sent in a post request in Django


code: plt.scatter(x, y, z, z, cmap='Blues')

rawDescription: How to generate data for matplotlib filled contour plots given the real coordinates?

description: Generate data for matplotlib filled contour plots given the real coordinates


rawDescription: IndexError: too many indices for array. Numpy array with 42 features not homogeneous


rawDescription: Sorting a 2D numpy array by multiple axes


code:
z = np.zeros((5,5))
z[np.arange(5), np.arange(5)] = 1 # diagonal is 1
z[np.arange(4), np.arange(4) + 1] = 2 # first upper diagonal is 2
z[np.arange(4) + 1, np.arange(4)] = [11, 12, 13, 14] # first lower diagonal values

rawDescription: Numpy: Affect diagonal elements of matrix prior to 1.10


rawDescription: Python- Parser the today's date out of Dateutil


code:
conditions = [
    (np.isnan(x['position'])) & (x['position'].fillna(method='ffill')*x['change']>0),
    (np.isnan(x['position'])) & (x['position'].fillna(method='ffill')*x['change']<=0)]

rawDescription: Write a user defined fillna function in pandas dataframe to fill np.nan different values with conditions


code:
import multiprocessing as mp
import time
import subprocess

def caller(task, wait):
    time.sleep(wait)
    subprocess.call(['python', task], shell=True)

tasks = ["task1.py", "task2.py", ..., "task64.py"]
for t,task in enumerate(tasks):
    p = mp.Process(target=caller, args=(task,t*4))
    p.join()

rawDescription: Staggering tasks using Crontab

description: Staggering tasks using Crontab


rawDescription: Readlines() and calculations in for loop


code:
result = numpy.empty((len(param_1_vals),len(param_2_vals)))
result[i,j] = yourCalculation(param_1_vals[i],param_2_vals[j])

rawDescription: Python datastructure with string for indexing


code:
from myproject.twitter_status import TwitterManager

def __update_twitter(message):
    twit_mgr = TwitterManager()
    twit_mgr.update_twitter_status(message)

rawDescription: Django Tweepy File

description: Django Tweepy File


rawDescription: Bitwise operations on .ix (Pandas)

description: Bitwise operations on .ix (Pandas)


code:
with open("scores.txt", 'r') as infile, open("top_score.txt", 'w') as outfile, open("top_score2.txt", '\
w') as outfile2:
    lineList = sorted(infile.readlines())
    for lines in lineList:
        newLine = lines.replace('\n', '')
        splitLines = newLine.split(',')
        studentNames = splitLines[0]
        studentScores = splitLines[1:]
        studentsList = []
        for i in studentScores:
            if i == '':
                break
            studentsList.append(int(i))
        topScore = max(studentsList)
        result = "%s: %s,max score = %d" % (studentNames.capitalize(),
                                            str(studentsList),
                                            max(studentsList))
        print(result)
        print(result, file = outfile)
        outfile2.write(result + "\n")

rawDescription: Writing Lines to a Different File

description: Writing Lines to a Different File


code:
import pandas as pd
rows = ['1','2','3']
cols = ['X','Y']

df = pd.DataFrame(([col+row for col in cols] for row in rows),
                  index=rows, columns=cols)

rawDescription: create a Data frame as a function of row index value and column name?

description: Create a Data frame as a function of row index value and column name


rawDescription: Surround outputted email addresses in quotation marks in Python3.2


code:
np.arctan2(-np.sin(np.real(x))*np.sinh(np.imag(x)),
            np.cos(np.real(x))*np.cosh(np.imag(x)))

rawDescription: Reason for the difference between arg and atan2


code:
from random import choice

results = {x: choice(directors) for x in movies}

rawDescription: Joining two lists with unequal number of elements into a dictionary


rawDescription: PyGobject Application Icon

description: PyGobject Application Icon


code:
keywords = set()
with open(list_file_path) as list_file:
    for line in list_file:
        if line.strip():
            keywords.add(line.strip())

rawDescription: Use a file to search lines in another file in Python


code: MyList = form.getlist("state_carry")

rawDescription: Python Pass List into Form and Retrieve as List


code: counts, bin_edges = np.histogram(a, bins=num_bins, normed=True)

rawDescription: How to get cumulative distribution function correctly for my data in python?

description: Get cumulative distribution function correctly for my data in python


code:
air = Lifesupport(40, 60)
print(air)

rawDescription: What are the main advantages of using a class over a callable function?


code: received_list = filter(None, p.map(process_data, data_to_process))

rawDescription: Control the value returned by a spawned process


rawDescription: Split a string of Emojis into single Emoji character


code:
import collections

clusterer = collections.defaultdict(list)

for l in ListA:
    for k, v in l:
        clusterer[k].append(v)

output = clusterer.values()

rawDescription: Find duplicate items within a list of list of tuples Python


code:
def networkx_based(a): #@atomh33ls's solution code
    A=nx.Graph()
    for x in a:
        A.add_edge(x[0],x[1])
    return nx.adjacency_matrix(A)

def vectorize_based(data): # @plonser's solution code
    ord_u = np.vectorize(lambda x: ord(x)-65)
    s = ord_u(data)
    res = np.zeros((s.max()+1,s.max()+1),dtype=int)
    res[s[:,0],s[:,1]] = 1
    res_sym = res + res.T
    np.fill_diagonal(res_sym,1)
    return res_sym

def unique_based(graph): #solution from this post
    _,ID = np.unique(graph,return_inverse=True)
    M = ID.reshape(graph.shape)
    n = M.max()+1
    idx1 = M[:,0]*(n) + M[:,1]
    idx2 = M[:,1]*(n) + M[:,0]
    out = np.eye(n,dtype=int)
    np.put(out,[idx1,idx2],1)
    return out

rawDescription: Numpy- get neighbors matrix from 2D array


code: mynewstr = mystr.decode('utf-8')

rawDescription: How to pass a variable to unicode/raw (ur"") conversion function

description: Pass a variable to unicode/raw (ur"") conversion function


code:
class TestOdd1(unittest.TestCase):
    NUMBER=1
    def runTest(self):
        """Assert that the item is odd"""
        self.assertTrue( self.NUMBER % 2 == 1, "Number should be odd")

class TestOdd2(TestOdd1):
    NUMBER=2

if __name__ == '__main__':
    unittest.main()

rawDescription: Instantiate Python unittest.TestCase with arguments


code:
"""
This is the message class that stores all the message
objects.
"""

message = models.TextField()
time_posted = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User)

rawDescription: Twitter API - how to have a user log in via Twitter to submit text to a database


rawDescription: To print the lists for the code?

description: To print the lists for the code


code:
import os
with open(fname, 'rb') as f:
   is_end = f.tell() == os.fstat(f.fileno()).st_size

rawDescription: Python detecting EOF

description: Python detecting EOF


code: [f(x) for x in my_list]

description: Going from (a_1, a_2, ..., a_n) to (f(a_1), f(a_2), ..., f(a_n))


code:
class BaseRecipe(models.Model):
    def get_recent_comments(self, n=5):
        return self.comment_link.all().order_by('-id')[:n]

rawDescription: iterate through certain number of foreign key objects

description: Iterate through certain number of foreign key objects


code:
class EquipmentMapped(wrapper_class(Equipment)):
    # you may well have to define __init__ here
    # you'll have to check yourself, and see what sqlalchemy does...
    pass

mapper(EquipmentMapped,equipment)

rawDescription: Mixin Cython class and SqlAlchemy

description: Mixin Cython class and SqlAlchemy


rawDescription: Python character count beside each line of a file


code:
import csv

a = open('a.csv', 'r')
b = open('b.csv', 'w')
ra = csv.DictReader(a)
wb = csv.DictWriter(b, None)

for d in ra:

  if wb.fieldnames is None:
    # initialize and write b's headers
    dh = dict((h, h) for h in ra.fieldnames)
    wb.fieldnames = ra.fieldnames
    wb.writerow(dh)

  wb.writerow(d)

b.close()
a.close()

rawDescription: Is it possible to keep the column order using the Python csv DictReader


rawDescription: Python 2.7 - Conditional passing empty k,v pairs to dict instead of moving to next iterator


code:
from subprocess import Popen, PIPE

p = Popen(['git', '-C', path_to_my_repository, 'show',
        'master@{' + date_string + '}:' + path_to_file],
    stdin=PIPE, stdout=PIPE, stderr=PIPE)

# Content will be in `output`
output, err = p.communicate()

rawDescription: Retrieving versions of a file

description: Retrieving versions of a file


code:
import itertools
AB = map(sum, itertools.izip(A, B))

rawDescription: Finding the sum of matching components in two lists


code:
import ConfigParser
import sys
from StringIO import StringIO

config = ConfigParser.ConfigParser()
config.readfp(StringIO('[default]'))  # <----
config.set('default', 'name', 'value')
config.write(sys.stdout)

rawDescription: Write to lowercase 'default' section ConfigParser


code:
whitelist = ["olive leaf plucked", "during mating searson"]
finder3.apply_ngram_filter(lambda w1, w2, w3: " ".join([w1,w2,w3]) not in whitelist)

rawDescription: finder.apply_ngram_filter in nltk.collocations to classify some ngrams

description: Finder.apply_ngram_filter in nltk.collocations to classify some ngrams


code:
t = ((4,), (3, 5), (2, 4, 6), (1, 3, 5, 7))

from itertools import tee
a, b = tee(t)
next(b)
for ind, (t1, t2) in enumerate(zip(a, b)):
    print([[(ind, i), (ind + 1, j)] for i in t1 for j in t2])

rawDescription: Convert tree nodes to coordinates of endpoints of edges


code:
import subprocess as sp

processes=[sp.Popen('your-command-here', shell=True,
                    stdout=sp.PIPE, stderr=sp.PIPE) for i in range(12)]

rawDescription: Multithreaded thumbnail generation in Python


code:
class Foo(object):
    def __eq__(self, other):
        return type(self) == type(other)
    def __hash__(self):
        return 1

rawDescription: Python set intersection and __eq__

description: Python set intersection and __eq__


code: " ".join("text text                  blabla bla ".split())

rawDescription: python - remove whitespaces that are not needed

description: Python - remove whitespaces that are not needed


code:
entries = [{'remote': '1', 'quantity': 1.0, 'timestamp': 1},
           {'remote': '2', 'quantity': 1.0, 'timestamp': 2},
           {'remote': '2', 'quantity': 1.0, 'timestamp': 3}]

rawDescription: How to delete duplicate entries in a nested container

description: Delete duplicate entries in a nested container


code:
def partition_new(n):
    try:
        return partitions_new[n]
    except IndexError:
        total, sign, i = 0, 1, 1
        k = gen_pent_new(i)
        while n - k >= 0:
            total += sign*partition_new(n - k)

            i += 1
            if i%2: sign *= -1
            k = gen_pent_new(i)

        partitions_new.insert(n, total)
        return total

rawDescription: Optimizing a Partition Function

description: Optimizing a Partition Function


code:
def simple(my_list):
    return [third_transformation(second_transformation(first_transformation(e)))
            for e in my_list]

rawDescription: Performance of multiple iterations

description: Performance of multiple iterations


code:
dt_now = datetime.datetime.now()
t_now = dt_now.time()

rawDescription: Time comparison in python

description: Time comparison in python


code: import operator

rawDescription: Python list comprehensions: Is it possible to specify the inclusion of two elements at a time?


rawDescription: numpy: slicing and vectorized looping with 1d and 2d arrays

description: Numpy: slicing and vectorized looping with 1d and 2d arrays


code: json_text = json.dumps(json_data)

rawDescription: Trying to loop through all entries in a datastore object and adding post numbers in dictionary


code:
import test1
var_new=test1.var1
print(var_new)

rawDescription: How to get value from global variable in another module python

description: Get value from global variable in another module python


code:
import os
os.walk('C:\\')

rawDescription: python construct to know the list of all the directories and recursive sub-directories

description: Python construct to know the list of all the directories and recursive sub-directories


code: result = means.groupby(level='State').filter(lambda x: len(x)>=len(years))

rawDescription: Pandas Groupby with multiple columns selecting rows with full range of values


code: (np.arange(10) == 4).view(np.uint8)

rawDescription: How to create in one line a null vector of size 10 but the fifth value being 1 using numpy

description: Create in one line a null vector of size 10 but the fifth value being 1 using numpy


rawDescription: Python: Having difficulty obtaining current path of script


code:
import numpy as np
from datetime import datetime
wind = np.loadtxt("ws425.log.test", delimiter=",", usecols=(0,4), dtype=object,
                  converters={0: lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S.%f"),
                              4: np.float})

wind

rawDescription: reading a comma-delimited file with a date object and a float with Python

description: Reading a comma-delimited file with a date object and a float with Python


code:
import numpy as np
x = np.arange(10, dtype='int32')
y = x.view('float32')
y[:] = x

print(y)

rawDescription: In-place type conversion of a NumPy array


code:
s= "Name1=Value1;Name2=Value2;Name3=Value3"
dict(item.split("=") for item in s.split(";"))

rawDescription: Splitting a semicolon-separated string to a dictionary, in Python


code:
s = 'foo bar foo bar foo bar'
re.sub(r'\b(.+)(\s+\1\b)+', r'\1', s)

rawDescription: Is there a way to remove duplicate and continuous words/phrases in a string?


rawDescription: Updating a 2D database (CSV) with other databases in Python?


code:
import numpy as np
probs = [0.1, 0.2, 0.5, 0.2]

rawDescription: draw random element in numpy

description: Draw random element in numpy


code:
try:
    __file__
except:
    sys.argv = [sys.argv[0], 'argument1', 'argument2', 'argument2']

rawDescription: When running a python script in IDLE, is there a way to pass in command line arguments (args)?


code:
width, _ = self.GetSize()
self.SetMinSize((width, -1))

rawDescription: wxPython align widgets and fitting

description: WxPython align widgets and fitting


rawDescription: add items to dictionary of list

description: Add items to dictionary of list


code:
selection = treeView.get_selection()
selections, model = selection.get_selected_rows()

for row in selections:
    # Make sure the row we are given is actually selected
    if selection.iter_is_selected(row.iter) and row.previous != None:
        self.listData.move_before(row.iter, row.previous.iter)

rawDescription: How to move multiple ListStore elements up or down

description: Move multiple ListStore elements up or down


code:
from flask import request, Flask

app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
def home():
    key = request.args.get('key', '')
    return 'key is `%s`, type(key) is %s\n' % (key, type(key))

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

rawDescription: Data type of GET attributes

description: Data type of GET attributes


code:
newlist = []
print ("Highest col",readex.get_highest_column())
getnewhighcolumn = readex.get_highest_column()
for i in range(0, lengthofdict):
    prevsymbol = readex.cell(row = i+1,column=getnewhighcolumn).value
    if prevsymbol is not None:
        newlist.append(prevsymbol)
print(newlist)

rawDescription: how to check if a cell is empty in openpyxl python

description: Check if a cell is empty in openpyxl python


code:
from scipy import linspace
from scipy import pi,sqrt,exp
from scipy.special import erf

from pylab import plot,show

def pdf(x):
    return 1/sqrt(2*pi) * exp(-x**2/2)

def cdf(x):
    return (1 + erf(x/sqrt(2))) / 2

def skew(x,e=0,w=1,a=0):
    t = (x-e) / w
    return 2 / w * pdf(t) * cdf(a*t)
    # You can of course use the scipy.stats.norm versions
    # return 2 * norm.pdf(t) * norm.cdf(a*t)

n = 2**10

e = 1.0 # location
w = 2.0 # scale

x = linspace(-10,10,n)

for a in range(-3,4):
    p = skew(x,e,w,a)
    plot(x,p)

show()

rawDescription: skew normal distribution in scipy

description: Skew normal distribution in scipy


code:
a = np.linalg.norm(C - B)
b = np.linalg.norm(C - A)
c = np.linalg.norm(B - A)

rawDescription: Find Arc/Circle equation given three points in space (3D)


code:
df["Date"] = df["Date"].values[::-1]
df

rawDescription: Reversing the order of values in a single column of a Dataframe


code:
import time
import multiprocessing
import gc

def foo(x):
    init()
    for x in range(2**28):pass
    print(x**2)

def init():
    global completely_unrelated_array
    completely_unrelated_array = None
    del completely_unrelated_array
    gc.collect()

if __name__ == "__main__":
    completely_unrelated_array = list(range(2**23))
    P = multiprocessing.Pool(initializer=init)

    for x in range(8):
        multiprocessing.Process(target=foo, args=(x,)).start()
    time.sleep(100)

rawDescription: How can I restrict the scope of a multiprocessing process?

description: Restrict the scope of a multiprocessing process


code:
import re
reg=re.compile('\s*(.+\S)\s+(\S+)')
reg.findall(line)

rawDescription: Regular expression to parse sfv-format files


code:
def capitalize_list(t):
    N = []
    for i in range(len(t)):
        if type(t[i]) == str:
            N.append(t[i].capitalize())
        if type(t[i]) == list:
            N.append(capitalize_list(t[i]))
    return N

rawDescription: A program to mutate Nested Lists

description: A program to mutate Nested Lists


code:
for i in range(18):
    stats[i] = {}
    stats[i]['Population'] = population1.text

rawDescription: Creating numbered dictionaries with a For loop [python]


code:
def process_with_original_measuring(self):
    self._start = time.time()
    next = self._start
    self._k = 0
    while self._k < 100000000:
        self._k = self._k+1
        if time.time() - next > 1:
            print (round((self._k / 1000000), 5))
            next = time.time()

    print("duration:")
    print (time.time() - self._start)

rawDescription: Python, calculating the status of computation slows down the computation itself


code:
n = 2
[[[i>>k&1 for k in range(j, j-8, -1)] for j in range(8*n-1, 0, -8)]
 for i in range(2**(8*n))]

rawDescription: Python : efficient bytearray incrementation


code:
def generate(self):
    while any(self.values):
        r, index = min(v for v in self.values if v)
        try:
            self.values[index] = (self.generators[index].next(), index)
        except StopIteration:
            self.values[index] = None
        yield r

rawDescription: Sort generated numbers using another python generator


code:
def genericInit(self):
    Parent.__init__(self, 'A')

type('Child1', (Rank,), {'__init__': genericInit})

rawDescription: How to pass parameters to parent class with type() in python?

description: Pass parameters to parent class with type() in python


code:
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
coding_dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG", generic_dna)
coding_dna.translate()

rawDescription: How can I do the following comparison without having to write 20 if-statements or making 20 lists/dictionaries?

description: Do the following comparison without having to write 20 if-statements or making 20 lists/dictionaries


rawDescription: Python regular expressions not recognizing \number


code: df.sort_values(['group_min', 'i', 'b'], ascending=[False, False, True]).drop('group_min', axis=1).set_index('i')

rawDescription: Sort pandas DataFrame by multiple columns and duplicated index


code:
from multiprocessing import Pool
from socket import gethostbyaddr

def gethost(addr):
    try:
        return gethostbyaddr(addr)
    except:
        pass

if __name__ == '__main__':

    p = Pool(3)
    print (p.map(gethost,['74.125.228.137',
                          '11.222.333.444',
                          '17.149.160.49',
                          '98.139.183.24']))

rawDescription: Python script to collect all hostnames of ip addresses with only prime entities


code:
def get_department(dept_num):
    departments = {'1': 'I.T.',
                   '2': 'Administration',
                   '3': 'Human Resources',
                   '4': 'Maintenance'}
    if hasattr(dept_num, 'group'): # then it's a match, not a number
        dept_num = dept_num.group(0)
    return departments.get(dept_num, "Unknown Dept")

file = r"""Name,Performance Review,Department
Adam,3,1
Joe,5,2
Alice,1,3
Eve,12,4""" # this looks like a csv file

dept_names = re.sub(r'''\d+$''', get_department, file, flags=re.M)
print(dept_names)
# Name,Performance Review,Department
# Adam,3,I.T.
# Joe,5,Administration
# Alice,1,Human Resources
# Eve,12,Maintenance

rawDescription: What Regex to use in this example

description: What Regex to use in this example


code:
import sympy as sym

x, y = sym.symbols('xy')
f = x + 2*y
g = 3*x - y
h = f + g

rawDescription: Mathematical function, unassigned variables?


rawDescription: matplotlib close does not close the window

description: Matplotlib close does not close the window


code:
def foo(listOfInputs):
    try:
        return all(map(float,listOfInputs))
    except ValueError:
        return False

rawDescription: Is there a function in python that returns true if all members of an iterable are true?


code:
class BuildingSerializer(serializers.HyperlinkedModelSerializer):

    # additional methods for fields that will be
    # inherited in the DetailBuildingSerializer

    class Meta:
        model = Building
        fields = ('pk',
                  'title',
                  'image_url',
                  'location',
                  'campus_name',
                  'avg_temperature',
                  'avg_humidity',
                  'occupancy_level',
                  )

class DetailBuildingSerializer(BuildingSerializer):

    class Meta:
        model = Building
        fields = ('pk',
                  'title',
                  'image_url',
                  'location',
                  'campus_name',
                  'avg_temperature',
                  'avg_humidity',
                  'occupancy_level',
                  'floors'
                  )

rawDescription: only show a certain serializer field in a sub-level (newbie)

description: Only show a certain serializer field in a sub-level (newbie)


code:
class C(A,B):
    def test(self):
        B.test(self)

rawDescription: How do I call a method on a specific base class in Python?

description: Call a method on a specific base class in Python


code:
def func_(lis):
    ind = 0
    lst = [] # Don't use 'list' as a name; it overshadows the built-in
    for h in lis:
        lst.append((h, ind))
        ind += 1 # Increment the index counter
    return lst

rawDescription: creating a list of tuples using for loop

description: Creating a list of tuples using for loop


code:
class X:
    @classmethod
    def id(cls):
        return cls.__name__

rawDescription: Same name for classmethod and instancemethod?


rawDescription: Add only the first value in my list of arrays


code:
class Error(dexml.Model):
    code = dexml.fields.String()
    value = dexml.fields.String(tagname=".")

rawDescription: Python framework for object-XML mapping through decorators?


code: neighbors2("ACG", 1)

rawDescription: Implement Neighbors to find the d-neighborhood of a string in Python


code:
import csv
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ', quoting=csv.QUOTE_MINIMAL)
    for key, values in d.items():
        spamwriter.writerow([key] + values)

rawDescription: Printing dictionary with lists into file


code: {{ INDEX_DATE }}

rawDescription: Print the last modification of a jinja2 template in pelican


rawDescription: Pandas boolean indexing vs comparision of two lists: Same (?) methods, different results


code:
num = 332000000
colorarray = np.empty((2 * num, 4), dtype=float)
colorarray[:num, :3] = np.random.random_sample((num, 3))
colorarray[:num, -1] = 0.6
colorarray[num:] = colorarray[:num]

rawDescription: Python - Fastest way to generate list of random colours with fixed alpha


code: dataf.apply(foo, axis=1)

rawDescription: Apply function over relative rows in Pandas


code: s.configure(section, key="%s"%val)

rawDescription: Reading python ttk Styles from configuration file


code:
def blocked(xdim, ydim, xblocksize, yblocksize):
  for xblock in range(0, xdim, xblocksize):
     for yblock in range(0, ydim, yblocksize):
        for x in range(xblock, xblock+xblocksize):
           for y in range(yblock, yblock+yblocksize):
              yield (x, y)

rawDescription: How to write this in a simpler way

description: Write this in a simpler way


rawDescription: Merging multiple pandas datasets with non-unique index


code:
for x in output:
    print(x)

rawDescription: Python concatenate recursively strings in files


code:
import sys
from cx_Freeze import setup, Executable
EXE1 = Executable(
    # what to build
    script = "foo.py",
    initScript = None,
    base = 'Win32GUI',
    targetDir = "dist",
    targetName = "foo.exe",
    compress = True,
    copyDependentFiles = True,
    appendScriptToExe = True,
    appendScriptToLibrary = False,
    icon = 'foo.ico'
    )

setup(
    version = "9999",
    description = "...",
    author = "...",
    name = "...",

    options = {"build_exe": {"includes": includes,
                             "excludes": excludes,
                             "packages": packages,
                             "path": sys.path,
                             "append_script_to_exe":False,
                             "build_exe":"dist/bin",
                             "compressed":True,
                             "copy_dependent_files":True,
                             "create_shared_zip":True,
                             "include_in_shared_zip":True,
                             "optimize":2,
                             }
               },

    executables = [EXE1]
    )

rawDescription: cx_freeze & bundling files

description: Cx_freeze & bundling files


code:
a = np.arange(4)
obj = [Super1(a[j:j+1]) for j in xrange(len(a))]
obj[0].value1
obj[0].value1 = 5
a
obj[2].value1
a[2] = 8
obj[2].value1

rawDescription: How to link instance attributes to a numpy array?

description: Link instance attributes to a numpy array


code:
#file: cyclone-ssl.py
import cyclone.web

class IndexHandler(cyclone.web.RequestHandler):
    def get(self):
        self.write("hello world")

factory = cyclone.web.Application([(r"/", IndexHandler)])
portstr = "ssl:4443:privateKey=server_key.pem:certKey=server_cert.pem"

# make twisted app
from twisted.application import service, strports

application = service.Application("cyclone-ssl")
strports.service(portstr, factory).setServiceParent(application)

rawDescription: Does cyclone (python) support HTTPS connections and SSL?


code:
special = dict.fromkeys(string.punctuation + string.whitespace, True)
s = "One two  three    tab\ttabandspace\t end"
[''.join(g) for k,g in groupby(s, special.get)]

rawDescription: Efficiently split a string using multiple separators and retaining each separator?


code:
mask = np.triu_indices(x.shape[0], 1)
para = np.sqrt((x[:, None] - x)**2 + (y[:, None] - y)**2)
perp = np.abs(z[:, None] - z)
hist, _, _ = np.histogram2d(para[mask], perp[mask], bins=[rpbins, pibins])

rawDescription: How to vectorize this loop difference in numpy?

description: Vectorize this loop difference in numpy


rawDescription: Reverse a 3d array in python

description: Reverse a 3d array in python


code: MyList = [inst1,inst2]

rawDescription: Python : How to create a dynamic list of class values


code: words_in_paragraph = [word for word in wordlist if word in paragraph]

rawDescription: Python return which list items string contains


rawDescription: Sort dict in jinja2 loop

description: Sort dict in jinja2 loop


code:
from django.contrib import admin
from myapp.models import Reseller

class ResellerAdmin(admin.ModelAdmin):
    ...

    actions = ['reset_password']

    def reset_password(self, request, queryset):
        for obj in queryset:
            obj.password = genereate_new_passwd()
            sender.send(obj.email, obj.password)
            obj.save()
        self.message_user(request, "Passwords were resets for selected resellers successfully.")

    reset_password.short_description = "Resend Passwords for selected resellers"

admin.site.register(Reseller, ResellerAdmin)

rawDescription: Change admin template in Django

description: Change admin template in Django


code:
values = vd.values()
values

rawDescription: How to add elements from a dictonary of lists in python

description: Add elements from a dictonary of lists in python


code:
def build_db(path):
    db = {}
    with open(path) as f:
        for line in f:
            category, value = map(str.strip, line.split(":"))
            if category == "CONTACT":
                cur_contact = value
                db[value] = {}
            else:
                db.get(cur_contact, {})[category] = value
    # builds a dictionary of dictionaries that looks like:
    # # {"YOU": {"First Name": "FELIX", "Last Name": "MARTIN", ...}, ...}
    return db

rawDescription: Python Not finding phrase on any line other than first (new)


rawDescription: Python string to list 2D

description: Python string to list 2D


rawDescription: Appropriate Data structure

description: Appropriate Data structure


rawDescription: How do I repeatedly shift and pad elements in a list to get a list of lists?

description: Repeatedly shift and pad elements in a list to get a list of lists


code:
import heapq
x = [5, 53, 531, 5131, 1]
heapq.heapify(x)
x

rawDescription: Python Heap Priority Queue sift_up()

description: Python Heap Priority Queue sift_up()


code:
# remove tbr from pointing_to lists of all neighbours pointing to tbr
# (connections from other nodes to tbr
for n in pointed_by[tbr]:
    pointing_to[n].remove(tbr)
# after this tar is pointed by no neighbour
pointed_by[tbr] = set()

# repeat for opposite direction (connections from tbr to other nodes)
for n in pointing_to[tbr]:
    pointed_by[n].remove(tbr)
pointing_to[tbr] = set()

rawDescription: How to delete all occurances of an item from a dictionary of dictionary?

description: Delete all occurances of an item from a dictionary of dictionary


code:
data = [1, 'a', (2, 4, 6)]
any(isinstance(x, (str, list, tuple, int)) for x in data)

rawDescription: Elegant way to check if a list contains int, str, tuple and sub-list


code:
ids_not_wanted = [x.id for x in SeqIO.parse(r"c:\Users\Sergio\Desktop\wsp.fasta", "fasta")]
records_to_save_2 = [x for x in SeqIO.parse(r"c:\Users\Sergio\Desktop\wsp.fasta", "fasta") if (x.id not in ids_not_wanted)]

records_to_save.append(records_to_save_2)
# If duplicate records are a problem, eliminate them using "set"
records_to_save = list(set(records_to_save))
SeqIO.write(records_to_save, r"c:\Users\Sergio\Desktop\nuevsp.fasta", "fasta")

rawDescription: Replace sequences between files using Biopython


code: {k:v for k,v in (e.split(':') for e in lis)}

rawDescription: Efficient way to convert a list to dictionary


code:
'''Very simple enforcer of type annotations.

This toy super-decorator can decorate all functions in a given module that have
annotations so that the type of input and output is enforced; an AssertionError is
raised on mismatch.

This module also has a test function func() which should fail and logging facility
log which defaults to print.

Since this is a test module, I cut corners by only checking *keyword* arguments.

'''

import sys

log = print

def func(x:'int' = 0) -> 'str':
    '''An example function that fails type checking.'''
    return x

# For simplicity, I only do keyword args.
def check_type(*args):
    param, value, assert_type = args
    log('Checking {0} = {1} of {2}.'.format(*args))
    if not isinstance(value, assert_type):
        raise AssertionError(
            'Check failed - parameter {0} = {1} not {2}.'
            .format(*args))
    return value

def decorate_func(func):
    def newf(*args, **kwargs):
        for k, v in kwargs.items():
            check_type(k, v, ann[k])
        return check_type('<return_value>', func(*args, **kwargs), ann['return'])

    ann = {k: eval(v) for k, v in func.__annotations__.items()}
    newf.__doc__ = func.__doc__
    newf.__type_checked = True
    return newf

def decorate_module(module = '__main__'):
    '''Enforces type from annotation for all functions in module.'''
    d = sys.modules[module].__dict__
    for k, f in d.items():
        if getattr(f, '__annotations__', {}) and not getattr(f, '__type_checked', False):
            log('Decorated {0!r}.'.format(f.__name__))
            d[k] = decorate_func(f)

if __name__ == '__main__':
    decorate_module()

    # This will raise AssertionError.
    func(x = 5)

rawDescription: Python 3 and static typing

description: Python 3 and static typing


code:
#pythran export laplacian(float [], float)
import numpy
def laplacian(var, dh2):
    """ (1D array, dx^2) -> laplacian(1D array)
    periodic_laplacian_1D_4th_order
    Implementing the 4th order 1D laplacian with periodic condition
    """
    lap = numpy.zeros_like(var)
    lap[1:]    = (4.0/3.0)*var[:-1]
    lap[0]     = (4.0/3.0)*var[1]
    lap[:-1]  += (4.0/3.0)*var[1:]
    lap[-1]   += (4.0/3.0)*var[0]
    lap       += (-5.0/2.0)*var

    lap[2:]   += (-1.0/12.0)*var[:-2]
    lap[:2]   += (-1.0/12.0)*var[-2:]
    lap[:-2]  += (-1.0/12.0)*var[2:]
    lap[-2:]  += (-1.0/12.0)*var[:2]

    return lap / dh2

rawDescription: Cythonize a partial differential equation integrator


code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.graphics import *

class MyWidget(Widget):

    def __init__(self, **kwargs):
        # I'd make sure to pass of kwargs through to the super
        # as there are widgets's that process their initial
        # arguments through.
        super(MyWidget, self).__init__(**kwargs)

        grid_layout = GridLayout(cols=3)
        grid_layout.add_widget(Button(text='A'))
        grid_layout.add_widget(Button(text='B'))
        grid_layout.add_widget(Label(text='text'))
        grid_layout.add_widget(Label(text='other'))
        grid_layout.add_widget(Button(text='text'))
        self.add_widget(grid_layout)
        with self.canvas.before:
            Color(1,0,0,1)
            Rectangle(pos=self.pos, size=self.size)

class MyApp(App):
    def build(self):
        return MyWidget()

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

rawDescription: Why does the root widget not have the same size of the window?


code:
with open ('~/abc.csv', 'w') as f, open ('~/def.csv', 'w') as g:
    writer1 = csv.writer(f)
    writer2 = csv.writer(g)

    writer1.writerow(['header1', 'header2', 'header3', 'header4'])
    writer2.writerow(['header1', 'header2', 'header3', 'header4', 'header5', 'header6'])

    for iteration in a_list:
        # perform calculations
        for pa in result1:
            writer1.writerow(pa)
        for pb in result2:
            writer2.writerow(pb)

rawDescription: how to write results in a for loop to multiple CSV files

description: Write results in a for loop to multiple CSV files


code:
shift('Hello', 1)
shift('Hello', 2)

rawDescription: Get the indices of capital letters in a string


code: list(map(sum, (masslog/(i+1) for i in range(10000))))

rawDescription: Python3, map-function

description: Python3, map-function


code:
# --- classes ---

class Answers(object):

    def __init__(self):

        # TODO: read it from file CSV or JSON
        #
        # import json
        #
        # with open("data.json") as f:
        #     self.data = json.load(f)

        self.data = {
            'knight': 'Neee!',
            'bunny': 'Rawwww!',
            'pesant': 'Witch!',
            'dingo': 'Bad, wicked, naughty Zoot!',
        }

    def response(self, text):
        try:
            return self.data[text]
        except KeyError:
            return "I don't know"

# --- functions ---

  # empty

# --- main ---

foo = Answers()

while True:

    egg = input('sounds: ').lower()

    if egg == 'exit':
        break

    print(foo.response(egg))

# ---

print("Good Bye!")

rawDescription: Long elif chains vs dictionary with exec()


code:
import subprocess
with open('.tmp', 'w+') as tempf,  open('.tmp2', 'w+') as tempf2:
    proc  = subprocess.Popen(["git", "remote", "show", "origin"], stdout=tempf, stderr=tempf2)
    proc.wait()
    tempf.seek(0)
    gitoutput = tempf.read()
print(gitoutput)

rawDescription: Python Parsing subprocess Output

description: Python Parsing subprocess Output


code: list(permutations(set("Thisss")))

rawDescription: removing duplicates in a string using set and get it back without order

description: Removing duplicates in a string using set and get it back without order


rawDescription: Need help parsing XML with ElementTree

description: Need help parsing XML with ElementTree


code:
async for line in r.content:
    ...
async for chunk in r.content.iter_chunked(1024):
    ...
async for slice in r.content.iter_any(): # as much as possible before blocking
    ...

rawDescription: What is the equivalent method of request.iter_content() in aiohttp?


code:
def nextdigits(s, start):
  return ''.join(itertools.takewhile(str.isdigit,
                                     itertools.islice(s, start, None)))

def findpaths(fname):
  with open(fname, 'rb') as f:
    m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    i = 0
    while True:
      n = m.find(':path', i)
      if n == -1: return
      countstr = nextdigits(m, n+6)
      count = int(countstr)
      n += 6 + len(countstr)
      yield m[n:n+count]
      i = n + 6 + count

rawDescription: seek to regex in a large file using python

description: Seek to regex in a large file using python


code:
for i in otp:
    important_list = [base_dict[i]]

rawDescription: Trying to place values of dictionary into a list, but it prints values individually


code: np.array([[x.strip('()') for x in i] for i in l])

rawDescription: Replacing specific values in numpy 2D Array


rawDescription: Disable/Remove argument in argparse

description: Disable/Remove argument in argparse


rawDescription: Python: Locate 3 adjacent list items and determine list index of first of them


code:
def ack(m, n, _memo={}):
  key = m, n
  if key not in _memo:
    if m==0: v = n + 1
    elif n==0: v = ack(m-1, 1)
    else: v = ack(m-1, ack(m, n-1))
    _memo[key] = v
  return _memo[key]

rawDescription: Why are default arguments evaluated at definition time in Python?


code:
menu = wx.Menu()
item = wx.MenuItem(menu, self.popupID1, "One\tO")
acc = wx.AcceleratorEntry()
acc.Set(wx.ACCEL_NORMAL, ord('O'), self.popupID1)
item.SetAccel(acc)
menu.AppendItem(item)

rawDescription: PopupMenu in wxPython with key press activated context menu items


rawDescription: Select one cell when pandas DataFrame has hierarchical index


code:
import lxml.etree as et

def skip_to(fle, line):
    with open(fle) as f:
        pos = 0
        cur_line = f.readline().strip()
        while not cur_line.startswith(line):
            pos = f.tell()
            cur_line = f.readline()
        f.seek(pos)
        return et.parse(f)

xml = skip_to("/home/padraic/Downloads/sample_html_file.html","<?xml")
tree = xml.getroot()
# one mapping is None ->  None: 'http://www.w3.org/1999/xhtml'
nsmap = {k: v for k, v in tree.nsmap.items() if k}

print(xml.xpath("//ix:nonFraction[contains(@name, 'AuditFeesExpenses')]", namespaces=nsmap))

rawDescription: Code transformation from BS4 to lxml parser


code:
from itertools import groupby
groupby(sorted(myList, key=len), key=len)

rawDescription: Checking to see if a list of lists has equal sized lists


code:
import matplotlib.pyplot as plt

# now plot it
for i in range(0, num_files * N, N):
    # plot column-0 vs column-1 in one subplot
    plt.subplot(2, 1, 1)
    plt.semilogx(my_array[i:i + N, 0], my_array[i:i + N, 1])
    plt.hold(True)
    # plot column-0 vs column-2 in another subplot
    plt.subplot(2, 1, 2)
    plt.semilogx(my_array[i:i + N, 0], my_array[i:i + N, 2])
    plt.hold(True)
plt.show()

rawDescription: save and plot multiple datasets using python

description: Save and plot multiple datasets using python


code:
compact_topo = verbose_to_compact([topo]) # function expects list; make one-item list
verbose_topo = compact_to_verbose(compact_topo)[0] # function returns list; extract the single item

rawDescription: Python: tree like implementation of dict datastructure


code:
import sys
sys.argv  #sys.argv[1] is the file to upload

rawDescription: Run Python Script on Selected File

description: Run Python Script on Selected File


rawDescription: Getting values live from a logfile into a string for caculations using Python


code:
import numpy as np

sample_rate = 400
Nyquist = sample_rate/2.0
fneeg = 'data.eeg'
t = 10
ch = 32
le = t*sample_rate
EEG = np.fromfile(fneeg, 'int16').reshape(ch, le, order='F')

rawDescription: Converting matlab code to python

description: Converting matlab code to python


code: {fn: int(fn[3:7]) for fn in filenames}

rawDescription: Python csv processing

description: Python csv processing


code:
@timeout(2, raise_exc=False)
def outer():
    return inner()

@timeout(2)
def inner():
    time.sleep(1)
    return "Should be printed"

print(outer())  # Should be printed

rawDescription: Nestable timeout decorator? (i.e. timeout decorated func calling timeout decorated func)


code:
import smtplib
import socket
import ssl
import sys

class SMTP_SSL(smtplib.SMTP_SSL):
    """Add support for additional ssl options."""
    def __init__(self, host, port=0, **kwargs):
        self.ssl_kwargs = kwargs.pop('ssl_kwargs', {})
        self.ssl_kwargs['keyfile'] = kwargs.pop('keyfile', None)
        self.ssl_kwargs['certfile'] = kwargs.pop('certfile', None)
        smtplib.SMTP_SSL.__init__(self, host, port, **kwargs)

    def _get_socket(self, host, port, timeout):
        if self.debuglevel > 0:
            print>>sys.stderr, 'connect:', (host, port)
        new_socket = socket.create_connection((host, port), timeout)
        new_socket = ssl.wrap_socket(new_socket, **self.ssl_kwargs)
        self.file = getattr(smtplib, 'SSLFakeFile', lambda x: None)(new_socket)
        return new_socket

rawDescription: Send e-mail to Gmail with inline image using Python


code:
temp_tuple = (a + b, a)
b, a = temp_tuple

rawDescription: Python - fibonacci numbers

description: Python - fibonacci numbers


rawDescription: Converting text file to list

description: Converting text file to list


code:
logdata = np.log(data)
plt.hist(logdata, bins=40, normed=True, color='c', alpha=0.75)
xmin = logdata.min()
xmax = logdata.max()
x = np.linspace(xmin, xmax, 100)
pdf = stats.norm.pdf(x, loc=estimated_mu, scale=estimated_sigma)
plt.plot(x, pdf, 'k')

rawDescription: A lognormal distribution in python

description: A lognormal distribution in python


code:
def relpath(filename, root):
    return filename[len(root):].lstrip(os.path.sep).lstrip(os.path.altsep)

rawDescription: Python zip a sub folder and not the entire folder path


rawDescription: Pandas python Initializing groupby object with empty groups


code:
img.save("temp.png")

img_loaded = Image.open("temp.png")

rawDescription: Image created via Pillow's Image.frombytes differs from expected


code: (lambda a: a * (a + 1))(a=b * c)

rawDescription: temporary variables in a python expression

description: Temporary variables in a python expression


code: subprocess.Popen("start /WAIT " + self.file, shell=True)

rawDescription: How do I launch a file in its default program, and then close it when the script finishes?

description: Launch a file in its default program, and then close it when the script finishes


rawDescription: Datetime conversions to timestamp

description: Datetime conversions to timestamp


rawDescription: Python create datetime object from list of values


code:
trd = str.maketrans('()', '{}')
string1 = string1.translate(trd).format(**word_dict)
string2 = string2.translate(trd).format(**word_dict)

rawDescription: How to replace parenthesis and text within it in Python string

description: Replace parenthesis and text within it in Python string


code:
@app.route("/books/")
def add_book():
    form = BookForm()
    # ... snip ...
    return render_template("data.html", action="Add", data_type="a book", form=form)

@app.route("/books/<int:book_id>")
def edit_book(book_id):
    book = lookup_book_by_id(book_id)
    form = BookForm(obj=book)
    # ... snip ...
    return render_template("data.html", data_type=book.title, action="Edit", form=form)

rawDescription: Python Flask-WTF - use same form template for add and edit operations


code:
savefilename = ""
with open(filename, 'r') as f:
    for line in f:
        line = line.strip() # get rid of the unnecessary white chars
        lastchar = line[-1:] # get the last char
        if lastchar == ":": # if the last char is ":"
            savefilename = line[0:-1] # get file name from line (except the ":")
            sf = open(savefilename + ".txt", 'w') # create a new file
        else:
            sf.write(line + "\n") # write the data to the opened file

rawDescription: how to read the content of .txt file using python?

description: Read the content of .txt file using python


code: years = data["year"].apply(lambda date: datetime.strptime(date, '%m/%d/%Y %H:%M:%S %p').year)

rawDescription: how to get year from a file, column contaning datetime

description: Get year from a file, column contaning datetime


code: t = Thread(target=my_function)

rawDescription: Multi threading script favors .start() which is first and doesn't run the others at all python


code:
import matplotlib.pyplot as plt
from scipy.sparse import coo_matrix

def plot_coo_matrix(m):
    if not isinstance(m, coo_matrix):
        m = coo_matrix(m)
    fig = plt.figure()
    ax = fig.add_subplot(111, axisbg='black')
    ax.plot(m.col, m.row, 's', color='white', ms=1)
    ax.set_xlim(0, m.shape[1])
    ax.set_ylim(0, m.shape[0])
    ax.set_aspect('equal')
    for spine in ax.spines.values():
        spine.set_visible(False)
    ax.invert_yaxis()
    ax.set_aspect('equal')
    ax.set_xticks([])
    ax.set_yticks([])
    return ax

rawDescription: python matplotlib plot sparse matrix pattern

description: Python matplotlib plot sparse matrix pattern


code:
import numpy as np
import pandas as pd
import scipy.stats as stats
import itertools as IT

A = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]],
                 columns=['A', 'B', 'C'], index = [1, 2, 3, 4, 5])

for col1, col2 in IT.combinations(A.columns, 2):
    def tau(idx):
        B = A[[col1, col2]].iloc[idx]
        return stats.kendalltau(B[col1], B[col2])[0]
    A[col1+col2] = pd.rolling_apply(np.arange(len(A)), 3, tau)

print(A)

rawDescription: Using rolling_apply with a function that requires 2 arguments in Pandas


code:
def make_happiness_table(filename):
   with open(filename) as f:
      d = dict()
      for line in f:
         word,score,std = line.split() #splits on any consecutive runs of whitspace
         d[word]=score,std # May want to make floats:  `d[word] = float(score),float(std)`
   return d

rawDescription: TAB break for line split in a dictionary in Python


rawDescription: Apply function to one element of a list in Python


code:
data2 = np.array([tupleli[0]], dtype=dt)
data2.shape
data2[0]

rawDescription: Equivalent of named tuple in NumPy?

description: Equivalent of named tuple in NumPy


code: result

rawDescription: Convert content of Object datatype to Date datatype in Python


code:
from nltk.corpus import brown
from collections import Counter
x = defaultdict(list)
for word,pos in brown.tagged_words()[1:100]:
    x[pos].append(word)

x
len(x)

rawDescription: NLTK - Get and Simplify List of Tags

description: NLTK - Get and Simplify List of Tags


code:
conn = MySQLdb.connect(..., cursorclass=MySQLdb.cursors.DictCursor)
curs = conn.cursor()

rawDescription: Python, MySQL and cursors that fetch maps


code: blog_entry = get_cached(BlogEntry, pk = 4)

rawDescription: Patterns for dealing with memcache Caching in Django


code:
a.data
# returns 10485760

rawDescription: Mixin to override inherited method

description: Mixin to override inherited method


code:
df = df.reset_index()
upper_limit = 20
lower_limit = 16
above_upper_line = df.Data > upper_limit
upper_line_crossed = above_upper_line != above_upper_line.shift()
clusters = upper_line_crossed.cumsum()
below_lower_line = df.Data < lower_limit

times = df[below_lower_line].groupby(clusters)["DateTime"].first().tolist()

rawDescription: How to find times when a variable is below a certain value in pandas

description: Find times when a variable is below a certain value in pandas


rawDescription: Change starting index of list in python?

description: Change starting index of list in python


code:
import shelve
s = shelve.open('filehere.db', flag='n', protocol=-1, writeback=False)
for key, val in csv.reader(open('filehere.txt')):
    s[key] = eval(val)
s.close()

rawDescription: Joining large dictionaries by identical keys


code:
import pygame

class car(sprite.Sprite):
    def __init__(self):
        sprite.Sprite.__init__() # necessary to initialize Sprite class
        self.image = image # insert image
        self.rect = self.image.get_rect() #define rect
        self.rect.x = 0 # set up sprite location
        self.rect.y = 0 # set up sprite location
    def update(self):
        pass # put code in here

cars = pygame.sprite.Group()# define a group

pygame.sprite.Group.add(car())# add an instance of car to group

rawDescription: What are PyGame sprites, and what do they do?


code:
def foo(arg1, arg2, arg3, *args, kwarg1="FOO", kwarg2="BAR", kwarg3="BAZ"):
    pass

print(foo.__kwdefaults__)

rawDescription: What is the use of __kwdefaults__ which is a function object attribute?


rawDescription: Generate array of number pairs from 2 numpy vectors


code:
import re
strs = "foo\tbar\t\tspam"
re.split(r'\t+', strs)

rawDescription: splitting a string based on tab in the file

description: Splitting a string based on tab in the file


rawDescription: Easiest way to serialize a simple class object with simplejson?


rawDescription: Challenge: create a list by sorting a bunch of nested dict


code:
df.date = df.date.apply(pd.Timestamp)
df

rawDescription: Reshaping tables in pandas

description: Reshaping tables in pandas


code: list(allnext(comment))

rawDescription: Split html document in pieces parsing html comments with BeautifulSoup


code:
def maketrans(inchars, outchars, deletechars):
    if isinstance(inchars, str) or isinstance(deletechars, str):
        return maketrans_s(inchars, outchars, deletechars)
    elif isinstance(inchars, unicode) or isinstance(deletechars, unicode):
        return maketrans_u(inchars, outchars, deletechars)
    raise Exception('Not supported type %s' % (t))

def maketrans_s(inchars, outchars, deletechars):
    if inchars: transtab = maketrans(inchars, outchars)
    else: transtab = None
    return transtab, deletechars

def maketrans_u(inchars, outchars, deletechars):
    # The if was unnecessary here; if inchars is empty, the zip
    # will be too, so you'll get {} as the result. Also notice
    # no ord(outchar); this means you _can_ use Unicode strings
    # when you know the string is Unicode.
    transtab = dict((ord(inchar), outchar) for inchar, outchar in zip(inchars, outchars))
    for char in deletechars:
        transtab[ord(char)] = None
    return transtab,

rawDescription: Transparently doing .translate with str and unicode objects


code:
import package.subpackage.module
from package.subpackage import module
from module import attribute1

rawDescription: Python: importing a sub‑package or sub‑module


code:
import sys

class File(object):

    def __init__(self, file, func, *args, **kwargs):
        self.close_file = kwargs.pop('close', True)
        # accept either filename or file-like object
        self.file = file if hasattr(file, 'read') else open(file)

        try:
            # func is responsible for self.file if it doesn't return it
            self.file = func(self.file, *args, **kwargs)
        except:  # clean up on any error
            self.__exit__(*sys.exc_info())
            raise

    # context manager support
    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        if not self.close_file:
            return  # do nothing
        # clean up
        exit = getattr(self.file, '__exit__', None)
        if exit is not None:
            return exit(*args, **kwargs)
        else:
            exit = getattr(self.file, 'close', None)
            if exit is not None:
                exit()

    # iterator support
    def __iter__(self):
        return self

    def __next__(self):
        return next(self.file)

    next = __next__  # Python 2 support

    # delegate everything else to file object
    def __getattr__(self, attr):
        return getattr(self.file, attr)

rawDescription: functools.wraps won't let me wrap a function with a class in Python 3

description: Functools.wraps won't let me wrap a function with a class in Python 3


rawDescription: Printing in a class python

description: Printing in a class python


code:
import math
def f(x):
    return 10*math.e**(math.log(0.5)/5.27 * x)

def radiationExposure_while(start, stop, step):
    result = 0
    while start < stop:
        result += f(start) * step
        start += step
    return result

def radiationExposure_range(start, stop, step):
    result = 0
    length = int(1 + (stop - 1 - start) / step)
    for counter in range(length):
        i = start + counter * step
        result += f(i) * step
    return result

radiationExposure_range(0, 11, 1) == radiationExposure_while(0, 11, 1)
radiationExposure_range(40, 100, 1.5) == radiationExposure_while(40, 100, 1.5)

rawDescription: different answers when using different loop constructs

description: Different answers when using different loop constructs


code:
for prev_index, cur_item in enumerate(somelist[1:]):
    if somelist[prev_index] > cur_item:
        do_something()

rawDescription: how to iterate/loop over a list and reference previous (n-1) element

description: Iterate/loop over a list and reference previous (n-1) element


code:
import string, win32ui, win32con
from Tkinter import *
w = Tk()
frame = win32ui.CreateWindowFromHandle(string.atoi(w.wm_frame(), 0))
frame.ModifyStyle(win32con.WS_CAPTION, 0, win32con.SWP_FRAMECHANGED)

rawDescription: Using TCL extensions to set native window style in Tkinter


rawDescription: apply command to list of files in python

description: Apply command to list of files in python


rawDescription: Using a variable as part of a variable name


code: subprocess.check_call(['ls', 'some directory with spaces in'])

rawDescription: How do I used 2 quotes in os.system? PYTHON

description: Used 2 quotes in os.system? PYTHON


rawDescription: Remove empty 'rows' and 'columns' from 3D numpy pixel array


code:
from itertools import cycle

x_values = cycle((0, 1))

for i in range (start, end):
    x = next(x_values)

rawDescription: if statement vs. expression

description: If statement vs. expression


code:
class A:
    # ...
    dependencies = GenericRelation(
        Dependency,
        content_type_field='dependent_contenttype',
        object_id_field='dependent_id')

rawDescription: Data models dependencies, can I simplify these objects?


code:
Field1,Field2,Field3
1,2,3
4,5,6

rawDescription: How can I dynamically generate class instances with single attributes read from flat file in Python?

description: Dynamically generate class instances with single attributes read from flat file in Python


code:
class SneakyDecorator:
    def __init__(self, f):
        self.f = f

    def __call__(self, *args, **kwargs):
        # [...]
        try:
            self.f(*args, **kwargs)
        except:
            t, v, tb = sys.exc_info()
            exec("raise v, None, tb.tb_next")

rawDescription: Python 2 and 3 compatible way of hiding a decorator from stacktrace


code:
from itertools import product
[int(''.join(d)) for l in range(1, 4) for d in product('89', repeat=l)]

rawDescription: How do I create a lambda function to print numbers containing x and y in Python?

description: Create a lambda function to print numbers containing x and y in Python


code:
class Language(models.Model):
    name = models.CharField()

class Word(models.Model):
    value = models.CharField()
    translations = models.ManyToMany(Language, through='Translation')

class Translation(models.Model):
    language = models.ForeignKey(Language)
    word = models.ForeignKey(Word)
    value = models.CharField()

rawDescription: How can I use all objects in a table as a label - input in a model in Django's Admin?

description: Use all objects in a table as a label - input in a model in Django's Admin


code: getattr(table.c, pkey_col_name) == S

rawDescription: Generic function that accept a table and column name and returns all the primary key values that matches a filter value given


code:
import numpy as np
from numpy.lib.stride_tricks import as_strided
N=10
L=4*N
H=3*N
step=5
a=(np.arange(3*H*L)%256).reshape(3,H,L)
(k,j,i)=a.strides
b=as_strided (a,shape=(H/step,L/step,3,step,step),strides=(j*step,i*step,k,j,i))

rawDescription: How can I create numpy array of views?

description: Create numpy array of views


code:
def rgb2int(arr):
    """
    Convert (N,...M,3)-array of dtype uint8 to a (N,...,M)-array of dtype int32
    """
    return arr[...,0]*(256**2)+arr[...,1]*256+arr[...,2]

def rgb2vals(color, color2ind):
    int_colors = rgb2int(color)
    int_keys = rgb2int(np.array(color2ind.keys(), dtype='uint8'))
    int_array = np.r_[int_colors.ravel(), int_keys]
    uniq, index = np.unique(int_array, return_inverse=True)
    color_labels = index[:int_colors.size]
    key_labels = index[-len(color2ind):]

    colormap = np.empty_like(int_keys, dtype='uint32')
    colormap[key_labels] = color2ind.values()
    out = colormap[color_labels].reshape(color.shape[:2])
    return out

print(rgb2vals(color, color2ind))

rawDescription: Convert a 3D array to 2D array based on dictionary


code:
bool_array
np.where(bool_array)[0]
np.where(bool_array)[1]
bool_array.argmax(1)

rawDescription: How to obtain the same result as numpy.where over a 2D array without getting 2 indices from the same row

description: Obtain the same result as numpy.where over a 2D array without getting 2 indices from the same row


rawDescription: Intersection of two numpy arrays of different dimensions by column


code: [[x or y or 0 for x, y in zip(a, b)] for a, b in zip(L1, L2)]

rawDescription: merging two lists, removing empty strings

description: Merging two lists, removing empty strings


code:
import matplotlib.pyplot as plt

list_of_lists_of_lengths = [range(1000),range(500,2000)]
plt.subplot(1,1,1)
plt.boxplot(list_of_lists_of_lengths)
plt.xlabel('max gap')
plt.ylabel('cluster lengths')
max_distance = (0, 100)
locs, labels = plt.xticks()
plt.xticks(locs, max_distance, size='small')
plt.show()

rawDescription: Using xticks, ticks not aligned properly with figure


code:
class Account(object):

    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

    def credit(self, amount):
        self.balance += amount

    def debit(self, amount):
        self.balance -= amount

    def get_balance():
        return self.balance

rawDescription: Class Level Variables python

description: Class Level Variables python


code:
import numpy as np

def calc_hour( str ):
    hour, min, sec = [float(i) for i in str.split(':')]
    min += sec/60.
    hour += min/60.
    return hour

calc_hour = np.vectorize( calc_hour )

def calc_deg( str ):
    deg, min, sec = [float(i) for i in str.split(':')]
    min += sec/60.
    deg += min/60.
    return deg

calc_deg = np.vectorize( calc_deg )

rawDescription: Python: Read text file with time in hour, minutes and seconds; and angle in degree, arc minutes and arc seconds


code: resultdict = df.to_dict(orient='index')

rawDescription: Fastest way to store data from Pandas DataFrame


code:
from fabric.operations import sudo

sudo('yum -y install expect')

rawDescription: Run SCP From Command Line With Password

description: Run SCP From Command Line With Password


rawDescription: Python: How to find the a unique element pattern from 2 arrays?


code:
dx, dy = np.hsplit(diff, 2)
slope = dy/dx
slope

rawDescription: Maximal Growth Period in time series

description: Maximal Growth Period in time series


code:
def emit(self, record):
    """
    Overwrite the logging.handlers.SMTPHandler.emit function with SMTP_SSL.
    Emit a record.
    Format the record and send it to the specified addressees.
    """
    try:
        import smtplib
        from email.utils import formatdate
        port = self.mailport
        if not port:
            port = smtplib.SMTP_PORT
        smtp = smtplib.SMTP_SSL(self.mailhost, port, timeout=self._timeout)
        msg = self.format(record)
        msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (self.fromaddr, ", ".join(self.toaddrs), self.getSubject(record), formatdate(), msg)
        if self.username:
            smtp.ehlo()
            smtp.login(self.username, self.password)
        smtp.sendmail(self.fromaddr, self.toaddrs, msg)
        smtp.quit()
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        self.handleError(record)

description: Logging.handlers.SMTPHandler raises smtplib.SMTPAuthenticationError


code:
for word in keywords:
    # keyword_handlers[word] is a function
    keyword_handlers[word](line)

rawDescription: Is there a better way to create dynamic functions on the fly, without using string formatting and exec?


code:
from setuptools import setup

setup(name='motion_control',
      version='0.1',
      description="Python library to operate stuff that move on my rasppi",
      long_description='explain how to use the tools installed by this package',
      classifiers=[],
      keywords='raspberrypi motion control',
      author='YOU',
      author_email='YOUR@EMAIL',
      url='ANY URL YOU THINK IS RELEVANT',
      license='MIT', # or any license you think is relevant
      packages=['motion_control'],
      zip_safe=False,
      install_requires=[
          # add here any tool that you need to install via pip
          # to have this package working
          'setuptools',
      ],
      entry_points="""
      # -*- Entry points: -*-
      [console_scripts]
      runstepper = motion_control.mystepper6:main
      moveit = motion_control.moveit:main
      """,
)

rawDescription: Alias to Launch Python .py Script

description: Alias to Launch Python .py Script


code:
{'href': 'by_city_001.html'}
{'href': 'by_city_244.html'}
{'href': 'by_city_002.html'}
...

rawDescription: Python scraper (Scraperwiki) only getting half of the table


code:
df = df.stack('ticker')
df = df.sortlevel(level=1)
df = df.reset_index()

rawDescription: Converting PANDAS dataframe from monthly to daily


code:
import pandas as pd
import statsmodels.formula.api as smf

d = {'a': [1,2,3,4,3,3,3], 'b': [5,6,7,8,4,4,4], 'c': [9,10,11,12,3,3,3],
     'd': ['red', 'blue', 'green', 'red', 'orange', 'blue', 'red']}
df = pd.DataFrame(d)

model = smf.ols('a ~ b + c + C(d, Treatment(reference="green"))', df).fit()
print(model.summary())

rawDescription: R's relevel() and factor variables in linear regression in pandas


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

a = -1
x = np.linspace(-19, 19, 10000)
y1 = (x/2.) + np.sqrt(np.power(x/2., 2) + a)
y2 = (x/2.) - np.sqrt(np.power(x/2., 2) + a)
plt.plot(x, y1, x, y2, c='k')

# customization
plt.ylim(-12,12)
ax = plt.gca()
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.grid(True)

plt.show()

rawDescription: Matplotlib challenge - smart way to plot only in the existence range


code:
import os
getattr(getattr(os, 'path'), 'join').__call__('.', 'directory')

rawDescription: Does using python files in Jython require python classes?


code:
['13 Whence springs the woodbind, and the bramble-rose,\n', '14 And where the sleepy cowslip sheltered grows;\n', '15 Whilst now a paler hue the foxglove takes,\n']
['23 When darkened groves their softest shadows wear,\n', '24 And falling waters we distinctly hear;']

rawDescription: Using python to process a chunk of a file every x lines


code:
subprocess.check_output(["make", "run_pci"],
                        cwd="/home/ecorbett/hello_world_pthread")

rawDescription: Python subprocess module use

description: Python subprocess module use


code:
script, div = components(fig)
return render_template('simpleline.html',div=div, script=script)

rawDescription: Embedding a bokeh plot in Flask

description: Embedding a bokeh plot in Flask


code:
def searchCourses(courses, query):
    terms = query.lower().strip().split()
    return tuple(course for course in courses
                 if all(course.matches_term(term)
                        for term in terms)
                )

rawDescription: Are python list comprehensions always a good programming practice?


code:
class Display(ctypes.Structure):
    """ opaque struct """

class XKeyEvent(ctypes.Structure):
    _fields_ = [
            ('type', ctypes.c_int),
            ('serial', ctypes.c_ulong),
            ('send_event', ctypes.c_int),
            ('display', ctypes.POINTER(Display)),
            ('window', ctypes.c_ulong),
            ('root', ctypes.c_ulong),
            ('subwindow', ctypes.c_ulong),
            ('time', ctypes.c_ulong),
            ('x', ctypes.c_int),
            ('y', ctypes.c_int),
            ('x_root', ctypes.c_int),
            ('y_root', ctypes.c_int),
            ('state', ctypes.c_uint),
            ('keycode', ctypes.c_uint),
            ('same_screen', ctypes.c_int),
        ]

class XEvent(ctypes.Union):
    _fields_ = [
            ('type', ctypes.c_int),
            ('xkey', XKeyEvent),
            ('pad', ctypes.c_long*24),
        ]

X11.XOpenDisplay.restype = ctypes.POINTER(Display)

rawDescription: How can I use python xlib to generate a single keypress?

description: Use python xlib to generate a single keypress


code:
d={'money':100, 'health':100}
def buyBread():
  d[money]=d[money]-10
  d[health]=d[health]+20

rawDescription: Python Random number generator and currency system for text-based RPG


code:
case_list = {}
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list[entryname] = case  #you will need to come up with the logic to get the entryname.

rawDescription: Adding item to Dictionary within loop

description: Adding item to Dictionary within loop


code:
if string.islower():
    string = string.title()

rawDescription: Python Title Case, but leave pre-existing uppercase


code:
def xToFloat(x):
    for i, row in enumerate(x):
        day, month, year = row.split('/')
        row = date(int(year), int(month), int(day)).toordinal()
        x[i] = row

rawDescription: Python - Altering a list that is being iterated. Out of Scope


code: sum([(xi - m)**2 for xi in results]) / (len(results) - 1)

rawDescription: How can I calculate the variance of a list in python?

description: Calculate the variance of a list in python


code: total_unique = len(counter)

rawDescription: Counting every word in a text file only once using python


code:
codes = {'Generation':{1:'First', 2: second},
         'Location':{1:'New York', 2:'Pennsylvania', 3: 'New Jersey'}
         }

rawDescription: How can I organize my data into a grid using Python Pandas?

description: Organize my data into a grid using Python Pandas


rawDescription: Flattening a complex list of tuples

description: Flattening a complex list of tuples


rawDescription: django redirect to parent of iframe from view

description: Django redirect to parent of iframe from view


rawDescription: Find previous occurrence of an element

description: Find previous occurrence of an element


code:
def handle(request):

    # Post request containing the key.
    if request.method == 'POST' and 'my_data' in request.POST.keys():

        # Retrieving the value.
        my_data = request.POST['my_data']

    # ...

rawDescription: How do I structure data for POST from form in ReactJS?

description: Structure data for POST from form in ReactJS


rawDescription: Improving Python/django view code

description: Improving Python/django view code


code:
from Bio import AlignIO
alignment = AlignIO.read(open('protein1.fasta'), 'fasta')
sequences = [record.seq for record in alignment]

rawDescription: Trying to find efficient ways to remove headers in fasta files


code:
new_current_combo = current_combo[:]
new_current_combo.append({'word': word['word']})
flatten_combinations(word['next'], new_current_combo, all_combos)

rawDescription: Find all paths through a tree (nested dicts) from top to bottom


code: h = ( bin(int(h, 16))[2:] ).zfill(h_size)

rawDescription: Converting from hex to binary without losing leading 0's python


code:
def pyramid(h,symbol):
    if symbol == "" or symbol == "#":
        for i in range(h):
            print(" " * (h-i - 1) + "#" * (2 * i + 1))
    else:
        for i in range(h):
            print(" " * (h-i - 1) + symbol * (2 * i + 1))
    print()

pyramid(5, "#")

rawDescription: Writing a function that prints a pyramid - two parameters


code:
import datetime
do = datetime.datetime.strptime("Dec 17 2014 00:00:06", "%b %d %Y %H:%M:%S")
do.strftime("%Y-%m-%d %H:%M:%S")

rawDescription: Change Date Format In Python

description: Change Date Format In Python