code:
def sort_events(method_name, events):
  ######
  return sorted_events

def schedule_event(event, scheduled_events):
  if not len(scheduled_events):
    scheduled_events.append(event)
    return
  right_index = bisect.bisect(scheduled_events, event)
  left_index = right_index - 1
  if len(scheduled_events) == right_index:
    if event.conflicts(scheduled_events[left_index]):
      return
  else:
    if event.conflicts(scheduled_events[left_index]) or event.conflicts(scheduled_events[right_index]):
      return
  bisect.insort(scheduled_events, event)

def main():
  scheduled_events = []
  sorted_events = sort_events("FCFS", events)
  for event in sorted_events:
    schedule_event(event, scheduled_events)

rawDescription: Schedule datetime intervals via different skipping methods


code:
def D(Y,x):
    return np.array([Y[1], -(epsilon-x**2)*Y[0]])

rawDescription: Python: odeint to solve ODEs with variable coefficients (QHO)


code: format(math.sqrt(2), ".20f")

rawDescription: Seeing the digits of long floats

description: Seeing the digits of long floats


rawDescription: Pushing all elements of a python list one element earlier


code: bananas = start_bananas + factory_one + factory_two

rawDescription: How to set limits to specific components of an equation when plotting them?

description: Set limits to specific components of an equation when plotting them


code:
class MyInt(int):
    def __iadd__(self, other):
        return MyInt(self - other)
    def __add__(self, other):
        return MyInt(self - other)

i = MyInt(4)
i += 1
type(i)
i
i + 5
type(i + 5)

rawDescription: Is it possible to be a virtual subclass of a built in type?


code:
def get_odds(items):
    new_list = [item for item in items if item % 2 == 1]
    return new_list

rawDescription: Checking odd numbers python

description: Checking odd numbers python


code:
['__class__',
 ...<etc>...,
 'a_static_var',
 'b_static_var']

rawDescription: Get list (key-value dictionary) of static variables, while respecting inheritance


code: lil_wayne_writer.writerow(['TITLE', 'SUMMARY', 'URL', 'KEYWORDS'])

rawDescription: Python3: How to store information from short script in a CSV file?


code:
def layout_widgets(layout):
   return (layout.itemAt(i) for i in range(layout.count()))

for w in layout_widgets(layout):
   doSomething(w)

rawDescription: Loop over widgets in PyQt Layout

description: Loop over widgets in PyQt Layout


rawDescription: Python - extracting particular numbers from each line in a file


rawDescription: append to a key in a dictionary the union of other two keys using python

description: Append to a key in a dictionary the union of other two keys using python


code:
name = "SpecialClass"
classes = {}
classes[name] = ClassFactory(name, params)
instance = classes[name](...)

rawDescription: How can I dynamically create derived classes from a base class

description: Dynamically create derived classes from a base class


rawDescription: What is the best way to create a python dictionary from a string?


code:
re.split('(?<=>)\s+(?=<)', '<a> <b> <c> <This is a string>')
re.split('(?<=>)\s+(?=<)', '''<World Bank> <provides> <loans for> <"a Country's Welfare">''')
re.split('(?<=>)\s+(?=<)', '<Facebook> <is a> <social networking site> <"Happy Facebooking => Enjoy">')

rawDescription: splitting line in python

description: Splitting line in python


code: values = [[self.sentences_intersection(sentences[i], sentences[j]) for i in xrange(n)] for j in xrange(n)]

rawDescription: How is this 2D array being sized by FOR loops?


code:
table = soup.find('table')
data = table.find_all('tr')[-1]
data = data.find_all('td')[1:]

rawDescription: Using BeautifulSoup to find a tag and evaluate whether it fits some criteria


code:
class PersonResource(SQLAlchemyResource):
    address = ForeignKey(AddressResource, 'address', full=True)

rawDescription: How do I load sub-models with a foreign key relationship in Backbone.js?

description: Load sub-models with a foreign key relationship in Backbone.js


code:
import bisect
import random
def random_choice(choices, weights):
    """
    >>> a = ['Hit', 'Out']
    >>> b = [.3, .7]
    >>> random_choice(a,b)
    """
    cumsums = []
    c = 0
    for weight in weights:
        c += weight
        cumsums.append(c)
    rnd = random.uniform(0, c)
    i = bisect.bisect(cumsums, rnd)
    return choices[i]

rawDescription: Weighted random from int list

description: Weighted random from int list


code:
def confirm(expression):
    if not expression:
        raise AssertionError

rawDescription: Terse error-checking in Python

description: Terse error-checking in Python


code:
class MyWords(object):
  def __init__(self):
    self.word_list = ... #code to create word list

  def pick_starting_point(self):
    # do something with self.word_list
    return ...

rawDescription: Accessing List from outside function

description: Accessing List from outside function


code: [print(result) for result in (function_call(params), ) if result]

rawDescription: Alternatives for 3 lines of java-like code?


rawDescription: Python Pandas value from index position

description: Python Pandas value from index position


code:
with some_open_method(filename) as spreadsheet:
    spreadsheet.writelines('%s\n\n\n\n\n' % splitted)

rawDescription: Iterate through a loop to change a conditional statement, python


code:
#!/usr/bin/env python

import socket

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

for thing in things:
    # produce files for consumer
    sock.sendto(b'X', ('127.0.0.1', 12345))

rawDescription: Wait for signal to start generating data from another process in python


code:
from numpy import *
from scipy.sparse import csc_matrix

nvox = 1000000
ntracks = 300000
nmask = 100

# create about 100 entries per track
tcoords = random.uniform(0, ntracks, ntracks * 100).astype(int)
vcoords = random.uniform(0, nvox, ntracks * 100).astype(int)
d = ones(ntracks * 100)
T = csc_matrix((d,  vstack((tcoords, vcoords))), shape=(ntracks, nvox), dtype=bool)

# create around 10000 entries per mask
mcoords = random.uniform(0, nmask, nmask * 10000).astype(int)
vcoords = random.uniform(0, nvox, nmask * 10000).astype(int)
d = ones(nmask * 10000)
M = csc_matrix((d, vstack((mcoords, vcoords))), shape=(nmask, nvox), dtype=bool)

Overlap = (M * T.transpose()).astype(bool) # mask M overlaps track T
Connected = (Overlap * Overlap.transpose()).astype(bool) # mask M1 and M2 are connected
Density = Overlap * T.astype(float) # number of tracks overlapping mask M summed across voxels

rawDescription: More efficient way to count intersections?


rawDescription: Method to uniformly randomly populate a disk with points in python


code: groups = [binary[i:i + 4] for i in range(0, len(binary), 4)]

rawDescription: binary to hex dictionary

description: Binary to hex dictionary


code:
import os
from subprocess import CalledProcessError, Popen, PIPE

cmd = "tsfoil2.exe"
input_data = os.linesep.join(['I:\\', 'test', 'SC20610.inp', os.linesep])
p = Popen(cmd, stdin=PIPE, bufsize=0)
p.communicate(input_data.encode('ascii'))
if p.returncode != 0:
   raise CalledProcessError(p.returncode, cmd)

rawDescription: How to handle an executable requiring interactive responses?

description: Handle an executable requiring interactive responses


code:
np.linspace(0, 1, num=0)
np.linspace(0, 1, num=1)

rawDescription: for floating point x, is x==numpy.linspace(x,y,n)[0] always True?

description: For floating point x, is x==numpy.linspace(x,y,n)[0] always True


rawDescription: regular expression python `r'*(.|:|?|!)*'`

description: Regular expression python `r'*(.|:|?|!)*'`


rawDescription: plotting orbital trajectories in python

description: Plotting orbital trajectories in python


code: df['days_between'] = df.groupby('Team')['Date'].diff() - timedelta(days=1)

rawDescription: count of last n days per group

description: Count of last n days per group


code: lib.f.restype = ctypes.POINTER(_Opaque)

rawDescription: Is it acceptable to subclass c_void_p in ctypes?


code: result = {k: v for k,v in preschool_kids.items() if v[0] == color}

rawDescription: Searching for value in dictionary and return a new dictionary with the corresponding key and value


code:
sorted([3,4,2,5]) # list
sorted({1: 'hello', 2: 'there', 4: 'foo', 3: 'bar'}) # dict
sorted(('Foo', 'Bar', 'Baz')) # tuple

rawDescription: Discuss the "sorted" function in Python

description: Discuss the "sorted" function in Python


code: findPeople( people, lambda x: x['age'] == 42 );

rawDescription: Searching 2 dimensional dictionary

description: Searching 2 dimensional dictionary


code:
import heapq

h = []
infile = open('input_data.txt')
name = infile.readline()

score = float(infile.readline())
heapq.heappush(h, (score, name))

while name != "":
    name = infile.readline()
    if name != "":
        score = float(infile.readline())
        heapq.heappush(h, (score, name))

infile.close()
bestScore, bestCandidate = heapq.heappop(h)
bestScore2, bestCandidate2 = heapq.heappop(h)

print(bestCandidate)
print(bestScore)
print(bestCandidate2)
print(bestScore2)

rawDescription: InputFile Loops Handling Two data

description: InputFile Loops Handling Two data


code: ['<employee ', 'Mark Twain', ' as ', 'Captain>']

rawDescription: how to split a list in to different strings in python

description: Split a list in to different strings in python


code: L.delete_edges(index for index, mut in enumerate(L.is_mutual()) if mut)

rawDescription: Smart way to remove mutual edges with python-igraph 0.7


code:
snap_num = len(snapshots)
for i in xrange(snap_num):
    # if snapshots[i].start_time is not the format of datetime object, you will have to format it first like above
    start_time = datetime.datetime.strptime(snapshots[i].start_time[:-5], '%Y-%m-%dT%H:%M:%S')
    if start_time > real_user_time:
        for n in xrange(i,snap_num):
            snapshots[n].delete()
        break

rawDescription: Python script for EC2 snapshots, use datetime to delete old snapshots


code: AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD

rawDescription: How do I fill in unused ip addresses in a python sublist?

description: Fill in unused ip addresses in a python sublist


code: C = A.mul(B)

rawDescription: Multiply two Pandas dataframes with same shape and same columns names


code:
import numpy as np
from itertools import izip, cycle
import matplotlib.pyplot as plt
from collections import defaultdict

N = 100

fake_data = {}
for j in range(97, 104):
    lab = chr(j)
    fake_data[lab] = np.cumsum(np.random.rand(N) > np.random.rand(1))

colors = cycle(['r', 'g', 'b', 'm', 'c', 'Orange', 'Pink'])

# fig, ax = plt.subplots(1, 1, tight_layout=True) # if your mpl is newenough
fig, ax = plt.subplots(1, 1) # other wise
ax.set_xlabel('time')
ax.set_ylabel('counts')
cum_array = np.zeros(N*2 - 1) # to keep track of the bottoms
x = np.vstack([arange(N), arange(N)]).T.ravel()[1:] # [0, 1, 1, 2, 2, ..., N-2, N-2, N-1, N-1]
hands = []
labs = []
for k, c in izip(sorted(fake_data.keys()), colors):
    d = fake_data[k]
    dd = np.vstack([d, d]).T.ravel()[:-1]  # double up the data to match the x values [x0, x0, x1, x1, ... xN-2, xN-1]
    ax.fill_between(x, dd + cum_array, cum_array,  facecolor=c, label=k, edgecolor='none') # fill the region
    cum_array += dd                       # update the base line
    # make a legend entry
    hands.append(matplotlib.patches.Rectangle([0, 0], 1, 1, color=c)) # dummy artist
    labs.append(k)                        # label

ax.set_xlim([0, N - 1]) # set the limits
ax.legend(hands, labs, loc=2)             #add legend
plt.show()                                #make sure it shows

rawDescription: Efficiently displaying a stacked bar graph


code:
def tokenize_autocomplete(phrase):
    a = []
    for word in phrase.split():
        j = 1
        while True:
            for i in range(len(word) - j + 1):
                a.append(word[i:i + j])
            if j == len(word):
                break
            j += 1
    return a

rawDescription: Partial matching GAE search API

description: Partial matching GAE search API


code:
from itertools import chain

print(*chain(*l))

rawDescription: print list of tuples without brackets python

description: Print list of tuples without brackets python


code:
def closewindow(event=None):
    Messagebox.destroy()

rawDescription: Tkinter Initial Cursor position and Enter to press button


code:
b = np.vstack([a,a])
print(b.shape) # (2, 2, 2, 2)
c = np.vstack([b,a])
print(c.shape) # (3, 2, 2, 2)
c.shape

rawDescription: adding matrices to n dimensional array with numpy

description: Adding matrices to n dimensional array with numpy


code: sum([x * y for x, y in zip([d, e, f], [a, b, c])])

rawDescription: How may I project vectors onto a plane defined by its orthogonal vector in Python?


code: dagger = Weapon('finesse', 'light', 'thrown')

rawDescription: Creating a variable inside of a for loop


rawDescription: removing "()" using python

description: Removing "()" using python


code:
import csv
from pprint import pprint
def undoublequotes(fobject):
    for line in fobject:
        yield line.replace('""', '"')

sample = '''\
""BIN"",""Afg"",""SONIC/SONIC JET/"",1,8.9095,""Due to the dynamic nature of the exemptions granted to many operators, the Contract Price does not reflect V.A.T. / G.S.T., Mineral Oil Taxes, Federal Excise Taxes or other taxes to which an operator may be exempt.  Please contact your salesperson or World Fuel Services if you require assistance in generating a fuel price estimate."",""N/A"",""01-NOV-2013"
'''
reader = csv.reader(undoublequotes(sample.splitlines(True)),
                    quoting=csv.QUOTE_NONNUMERIC)
pprint(next(reader))

rawDescription: csv import with pythons QUOTE_NONNUMERIC not working as expected

description: Csv import with pythons QUOTE_NONNUMERIC not working as expected


code:
class CategoryModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.category

class TimeModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.time

class PreparationModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.preparation

class ContentModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.content

rawDescription: Returning multiple values independently from __str__ for ModelChoiceField


code: np.all(np.diff(a) > 0)

rawDescription: Efficiently check if numpy ndarray values are strictly increasing


code:
def get_dval(dict_, first_idx, *args):
    if not isinstance(dict_, dict):
        return False
    if len(args) == 0:
        return dict_.get(first_idx, False)
    else:
        if first_idx not in dict_:
            return False
        return get_dval(dict_[first_idx], *args)

rawDescription: a python function that returns the value of a dictionary

description: A python function that returns the value of a dictionary


rawDescription: Django, get an attribute from a model

description: Django, get an attribute from a model


code:
b = a.swapaxes(1,2)
b.strides
b = a.swapaxes(1,2).copy()
b.strides

rawDescription: Numpy: Striding a multiple channel image


code:
#!/usr/bin/env python2

from __future__ import print_function
import subprocess

proc = subprocess.Popen(['./out.py'], shell=True,
    stdout=subprocess.PIPE)

# Discard first 4 lines
for i in range(4): proc.stdout.readline()

# First set of output
output = ''.join([ proc.stdout.readline() for i in range(3) ])
print(output.strip())
print('\n\n')

# Only one line is updated now
while True:
    output = proc.stdout.readline()

    print(output.strip().replace('\x1b[1A', ''))

rawDescription: Subprocess– showing X lines of output

description: Subprocess– showing X lines of output


rawDescription: Methods of creating a structured array

description: Methods of creating a structured array


code: df['hb'] - 5 #Where `df` is your dataframe.

rawDescription: How can i substract a single value from a column using pandas and python

description: Substract a single value from a column using pandas and python


code:
def query_in_string(query, string):
    for term in query.split('OR'):
        lst = map(str.strip, term.split('AND'))
        if all(word in string for word in lst):
           return True
    return False

rawDescription: Determining if a query is in a string

description: Determining if a query is in a string


code:
def process_form():
   validated_data = dict()
   for k,v in request.vars.values(): # I think this works...
      if k == 'some_key':
         do_some_processing()
      ...
      validated_data[k] = some_func(v)
      ...
   # now everyhing is validated and ok, send the data on
   redirect('next_page', vars=validated_data)

rawDescription: Preprocessing form data before using it

description: Preprocessing form data before using it


code:
# file_storages.py
from django.conf import settings
from django.core.files.storage import default_storage
from whatever.backends.s3boto import S3BotoStorage

app_storage = None
if settings.DEBUG == True:
    app_storage = default_storage
else:
    app_storage = S3BotoStorage()

rawDescription: Local filesystem as a remote storage in Django


code:
h = hashlib.md5('data')
int(h.hexdigest(), 16)

rawDescription: Operations on Python hashes

description: Operations on Python hashes


code:
arr = np.array([5, 4, 5, 8, 9])
idx = np.where(cond)[0]
idx
label

rawDescription: Replacing minimum element in a numpy array subject to a condition


code: H, xedges, yedges = np.histogram2d(x, y, bins=[nx, ny], weights=z)

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


code:
from operator import attrgetter
ancestor = max(nodes_ancestors, key=attrgetter('level'))

rawDescription: Get the object with the max attribute value in a list of objects


code:
for k,vals in audio.iteritems():
    for val in vals:
        print("{}:{}".format(k,val))

rawDescription: How to add multiple values to the same key in a Python Dictionary

description: Add multiple values to the same key in a Python Dictionary


code:
# settings.py
...
SOCIAL_AUTH_PIPELINE = (
    'my.path.custom_pipeline.clean_pipeline',
    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'social.pipeline.social_auth.social_user',
    'my.path.custom_pipeline.redirect_to_join_form',
    ...
)

rawDescription: Login vs Register in PythonSocialAuth

description: Login vs Register in PythonSocialAuth


code:
from PIL import Image
import tempfile

def image_watermark(request,image_id):
    photo = Photo.objects.get(pk=image_id)
    watermark = Image.open('{0}/{1}'.format(settings.MEDIA_ROOT,'wmark.png'))
    img = Image.open(photo.photo.file)
    img.paste(watermark,(img.size[0]-watermark.size[0],img.size[1]- watermark.size[1]),watermark)

    tmpfile = tempfile.TemporaryFile()
    img.save(tmpfile, img.format, quality=80)

    tmpfile.seek(0)
    wrapper = FileWrapper(tmpfile)
    response = StreamingHttpResponse(wrapper, 'image/jpeg')
    response['Content-Disposition'] = 'attachment; filename=photo.jpg'
    return response

rawDescription: Saving Image in a temporary file in django


code:
number = 0
while number != 4:
    #do stuff
    number = someNewValue

rawDescription: Not quite sure what's happening when using "or" in python


code:
def calc_checksum(packet):
    total = 0

    # Add up 16-bit words
    num_words = len(packet) // 2
    for chunk in struct.unpack("!%sH" % num_words, packet[0:num_words*2]):
        total += chunk

    # Add any left over byte
    if len(packet) % 2:
        total += ord(packet[-1]) << 8

    # Fold 32-bits into 16-bits
    total = (total >> 16) + (total & 0xffff)
    total += total >> 16
    return (~total + 0x10000 & 0xffff)

rawDescription: Computing 16-bit checksum of ICMPv6 header


code:
from dateutil.relativedelta import relativedelta
import datetime

rawDescription: pandas reading dates from csv in yy-mm-dd format

description: Pandas reading dates from csv in yy-mm-dd format


code:
class other_class():
    def __init__(self):
        self.helloWorld = hello_world()
        self.changeToGoodbye = change_to_goodbye() #contains a different hello_world object

        self.helloWorld.define_hello()
        self.changeToGoodbye.hello_to_goodbye() #changes the hello_world object inside of changeToGoodbye
        self.helloWorld.say_hello() #the unaltered helloWorld object

rawDescription: Changing Variables in Class from Other Classes (Python)


code:
class SpamForm(forms.ModelForm):
    class Meta:
        exclude = ('foo_type',)

rawDescription: Django Different form validation when adding and changing instance


code:
for elem in data:
    print(elem)

rawDescription: Printing output from json

description: Printing output from json


rawDescription: Pass dbf data to sentence and save as text file using Python 2.7


rawDescription: Best way to hash ordered permutation of [1,9]

description: Hash ordered permutation of [1,9]


code:
from wtforms.ext.sqlalchemy.fields import QuerySelectField  #import the ext.

def enabled_topics(): # query the topics (a.k.a categories)
    return Topic.query.all()

class PostForm(Form):  # create your form
    title = StringField(u'title', validators=[DataRequired()])
    body = StringField(u'Text', widget=TextArea())
    topic = QuerySelectField(query_factory=enabled_topics, allow_blank=True)

rawDescription: WTForms: setting default value from an SQLAlchemy field with relationship


code: ['a', 'b', 'c' 'd', 'e']  # no comma between 'c' and 'd'

rawDescription: Why is the following string literal allowed?


code:
bits3d = [[bitarray.bitarray(1000) for y in range(1000)] for x in range(1000)]
myvalue = bits3d[x][y][z]

rawDescription: python multidimensional boolean array?

description: Python multidimensional boolean array


rawDescription: How to search for XML elements in python?

description: Search for XML elements in python


rawDescription: How to get the unique part of a ref ID with GitPython?

description: Get the unique part of a ref ID with GitPython


code:
def unzip(source_filename, dest_dir):
    with zipfile.ZipFile(source_filename) as zf:
        zf.extractall(dest_dir)

rawDescription: Python zipfile.extract() doesn't extract all files


code:
text = "One two three. Four five six."
text
sentences = text.split('.')
sentences
reversed_words = [words.split()[::-1] for words in sentences]
reversed_words
rejoined_words= [' '.join(words) for words in reversed_words]
rejoined_words
capitalized_sentences = [sentence.capitalize() for sentence in rejoined_words]
capitalized_sentences
'. '.join(capitalized_sentences)

rawDescription: Faster and more consise way to reverse sentences in a string?


code:
targets = ".,'"
a = "I'll buy paper,pen and beg"
punct = [ (i, c) for i, c in enumerate (a) if c in targets]
nopunct = [c for c in a if c not in targets][::-1]
for i, c in punct: nopunct.insert (i, c)
b = ''.join (nopunct)
print (a)
print (b)

rawDescription: How to reverse position in string?

description: Reverse position in string


code:
ax.annotate('Maximum = {:0.0f}'.format(maxpoint[1]), ha='center',
            size=8, xy=(maxpoint[0], 1), xytext=(0, 5),
            textcoords='offset points',
            xycoords=('data', 'axes fraction'))

rawDescription: Matplotlib axis limits and text positions independent of dataset units


code: df[['name', 'gender', 'grade', 'marks']].to_dict(orient='records')

rawDescription: Merging 2 list of dicts based on common values


code:
r"""
Match number 1
  Time:             08:38:36
  Module name:      TestModule
  Message type:     08:38:36
  Message:          result success
  FTP site URL:     ftp.test.com
  Input file:       \root\level1\level2-ABC\2C.013000000B.dat
  Input file path:  \root\level1\level2-ABC
  Input file name:  2C.013000000B.dat
  Output file:      c:\local\project1\data\2C.013000000B.dat.ext
  Output file path: c:\local\project1\data
  Output file name: 2C.013000000B.dat.ext

Match number 2
  Time:             06:40:37
  Module name:      TestModule
  Message type:     06:40:37
  Message:          result success
  FTP site URL:     ftp.test.com
  Input file:       \root\level1\level2-ABC\20100722B.TXT
  Input file path:  \root\level1\level2-ABC
  Input file name:  20100722B.TXT
  Output file:      c:\local\project1\data\20100722B.TXT.ext
  Output file path: c:\local\project1\data
  Output file name: 20100722B.TXT.ext

Match number 3
  Time:             06:40:39
  Module name:      TestModule
  Message type:     06:40:39
  Message:          result success
  FTP site URL:     ftp.test.com
  Input file:       \root\level1\level2-DEF\20100722D1-XYZ.TXT
  Input file path:  \root\level1\level2-DEF
  Input file name:  20100722D1-XYZ.TXT
  Output file:      c:\local\project1\data\20100722D1-YFP.TXT.ext
  Output file path: c:\local\project1\data
  Output file name: 20100722D1-YFP.TXT.ext

Match number 4
  Time:             06:40:42
  Module name:      TestModule
  Message type:     06:40:42
  Message:          result success
  FTP site URL:     ftp.test.com
  Input file:       \root\level1\level2-DEF\2C.250B
  Input file path:  \root\level1\level2-DEF
  Input file name:  2C.250B
  Output file:      c:\local\project1\data\2C.250B.ext
  Output file path: c:\local\project1\data
  Output file name: 2C.250B.ext

There were 4 matching records
"""

rawDescription: Python regular expression to get filename in a long path


code:
df
grouped = df.groupby('ID')['Number'].max().to_dict()
df['Total'] = df.apply((lambda row:5 if grouped[row['ID']] else 0), axis=1)
df

rawDescription: Apply a value to all instances of a number based on conditions


code: health = wordfont.render("Your health: {0}".format(self.a), 1, (255, 9, 12))

rawDescription: pygame text variables

description: Pygame text variables


code:
from pyspark.sql.functions import col, sum

def count_not_null(c):
    return sum(col(c).isNotNull().cast("integer")).alias(c)

exprs = [count_not_null(c) for c in df.columns]
df.agg(*exprs).show()

## +---+---+---+
## |  x|  y|  z|
## +---+---+---+
## |  1|  2|  3|
## +---+---+---+

rawDescription: Count number of non-NaN entries in each column of Spark dataframe with Pyspark


code: weights = tf.Variable(10)

rawDescription: How to manually initialize the values for the weights?

description: Manually initialize the values for the weights


code:
df2 = df.copy()
for i in range(1,len(df.columns)):
    df2.iloc[:,i] = ((df.iloc[:,i].notnull()) &
                     (df.iloc[:,i+1:i+4].apply(lambda x: all(x.isnull()),axis=1)))

rawDescription: Excel like formulas with pandas

description: Excel like formulas with pandas


code:
import numpy as np

num = 10
x = np.random.random(num) # Observation locations

# "Green's functions" for a second-order polynomial
# at our observed locations
A = np.column_stack([x**i for i in range(3)])

rawDescription: Building a covariance matrix in Python

description: Building a covariance matrix in Python


code:
from django.http import HttpResponse
from django.utils import simplejson

def simple_view(request):
    response = {'string': "test",
                'number': 42,
                'array': [1, 2, 3],
                'js_object': dict(foo="bar")}
    return HttpResponse(simplejson.dumps(response),
                        mimetype="application/json")

rawDescription: django: control json serialization

description: Django: control json serialization


code:
s = df.apply((lambda x: x.to_json()), axis=1)
s[0]

rawDescription: Pandas DataFrame to Dict Format with new Keys


code: Full_Names_Test_2['MarketCap'].where(Full_Names_Test_2['MarketCap'] == 'n/a', 7)

rawDescription: np.where Not Working in my Pandas

description: Np.where Not Working in my Pandas


code:
# -*- coding: utf-8 -*-
import pickle
from nltk.tokenize import word_tokenize
from textblob.classifiers import NaiveBayesClassifier
with open('file.csv', 'r', encoding='latin-1') as fp:
    cl = NaiveBayesClassifier(fp, format="csv")

object = cl
file = open('classifier.pickle','wb')
pickle.dump(object,file)

rawDescription: python textblob and text classification

description: Python textblob and text classification


rawDescription: Pandas get previous dataframe row by date


code:
for elem in document.iter():
    elem.tail = ''

rawDescription: How to remove text not in tag using lxml?

description: Remove text not in tag using lxml


rawDescription: web scraping dynamic content with python

description: Web scraping dynamic content with python


rawDescription: django logging local javascript events

description: Django logging local javascript events


code:
from setuptools import setup, find_packages
import sys, os

version = '1.0'

setup(name='bob',
      version=version,
      description="Bob's magic code",
      long_description="""\
Bob's super useful code base""",
      classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
      keywords='Python',
      author='Fred Sprocket',
      author_email='fred.sprocket@example.com',
      url='http://example.com',
      license='',
      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
      include_package_data=True,
      zip_safe=False,
      install_requires=[
          # -*- Extra requirements: -*-
      ],
      entry_points="""
      # -*- Entry points: -*-
      """,
      )

rawDescription: Automatically Generate Python Egg from Python PasteScript


code:
from heapq import nsmallest
s = {'abc', 'defg', 'hij', 'kl', 'mno', 'qr', 'stuv', 'wx', 'yz'}
nsmallest(4, s, key=len)

rawDescription: Find all minimal elements in a list or set as weighted by a function


rawDescription: Can't execute Python script from PHP document


rawDescription: Set class attributes from default arguments


rawDescription: convert "1h30min" string to minutes in python

description: Convert "1h30min" string to minutes in python


rawDescription: get encoded content from an div using soup

description: Get encoded content from an div using soup


code:
orig = [ 'a', 'b', 'c', 'd' ]
rep = {'c': ['x', 'y', 'z']}
[i for c in orig for i in rep.get(c, [c])]

rawDescription: Replacing list item with contents of another list


code: Formset = formset_factory(testingForm, max_num=1, min_num=1, extra=1, validate_min=True, validate_max=True)

rawDescription: Django formset - Creating a formset of just ONE form


code:
D = {'a': 1,
     'b': [ {'example': 'first', 'green': 'second'},
            {'apple': 'third', 'green': 'fourth'}]};

rawDescription: multiple iteration through python dictionary

description: Multiple iteration through python dictionary


code: {{ value|striptags }}

rawDescription: Blocking HTML tags in a webpage

description: Blocking HTML tags in a webpage


code:
class Row(dict):
    def __init__(self, table, index, *args, **kw):
        self._table, self._index = table, index
        super(Row, self).__init__(*args, **kw)

    def __setitem__(self, key, value):
        super(Row, self).__setitem__(key, value)
        self._table.columns[key][self._index] = value

rawDescription: __getitem__, __setitem__ multiple keys Python


code:
FAX_REL = 'http://schemas.google.com/g/2005#fax'
HOME_REL = 'http://schemas.google.com/g/2005#home'
HOME_FAX_REL = 'http://schemas.google.com/g/2005#home_fax'
ISDN_REL = 'http://schemas.google.com/g/2005#isdn'
MAIN_REL = 'http://schemas.google.com/g/2005#main'
MOBILE_REL = 'http://schemas.google.com/g/2005#mobile'
OTHER_REL = 'http://schemas.google.com/g/2005#other'
OTHER_FAX_REL = 'http://schemas.google.com/g/2005#other_fax'
PAGER_REL = 'http://schemas.google.com/g/2005#pager'
RADIO_REL = 'http://schemas.google.com/g/2005#radio'
TELEX_REL = 'http://schemas.google.com/g/2005#telex'
TTL_TDD_REL = 'http://schemas.google.com/g/2005#tty_tdd'
WORK_REL = 'http://schemas.google.com/g/2005#work'
WORK_FAX_REL = 'http://schemas.google.com/g/2005#work_fax'
WORK_MOBILE_REL = 'http://schemas.google.com/g/2005#work_mobile'
WORK_PAGER_REL = 'http://schemas.google.com/g/2005#work_pager'
NETMEETING_REL = 'http://schemas.google.com/g/2005#netmeeting'

rawDescription: gdata.data.PhoneNumber: How do I get the type of Phone Number?

description: Gdata.data.PhoneNumber: How do I get the type of Phone Number


code: sprite, timer = sprites[0]  # first pair

rawDescription: Pygame sprites timer

description: Pygame sprites timer


code: " ".join("{}:{}".format(v, x[v]) for v in sorted(vowels, key=x.get, reverse=True))

rawDescription: Print in Value order, or if values are the same, alphabetical order


code:
import string

def complementary_strand(self, strand):
    return strand.translate(string.maketrans('TAGCtagc', 'ATCGATCG'))

rawDescription: More pythonic way to find a complementary DNA strand


rawDescription: Find number in string between spaces and parse it


code:
from cherrypy import wsgiserver
from app import app

d = wsgiserver.WSGIPathInfoDispatcher({'/': app})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 9999), d)

if __name__ == '__main__':
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()

rawDescription: Flask routing issues on CherryPy

description: Flask routing issues on CherryPy


code: any_in = lambda a, b: any(i in b for i in a)

rawDescription: one-liner to check if at least one item in list exists in another list?

description: One-liner to check if at least one item in list exists in another list


font_face: Source Code Pro

color_scheme: Packages/Theme - Flatland/Flatland Monokai.tmTheme

rawDescription: Specific font_face based on syntax in Sublime Text 2


rawDescription: How to remove the tzinfo completely from the time after converting to UTC in Python?

description: Remove the tzinfo completely from the time after converting to UTC in Python


code:
class FancyFloat(float):
    def __repr__(self):
        return format(Decimal(self), "f")

rawDescription: Disable scientific notation in python json.dumps output


code:
import re
p = re.compile(r'[A-Z]*(?=([\u4300-\u9fff]+))\1(?!,)', re.IGNORECASE | re.U)
test_str = "山牆 山墙,shan1 qiang2,gable\nB型超聲 B型超声, B xing2 chao1 sheng1,type-B ultrasound"
result = p.sub(r"\g<0>,", test_str)
print(result)
# => 山牆, 山墙,shan1 qiang2,gable
# => B型超聲, B型超声, B xing2 chao1 sheng1,type-B ultrasound

rawDescription: Python regex unexpectedly replacing Chinese characters


code:
import csv

with open('test.txt','rb') as myfile:
    mylist = list(csv.reader(myfile, delimiter='|'))

rawDescription: Python operation with delimited texts in text file


code: p = pd.pivot_table(table, index=["weekday"], columns=["weekofyear"], values="people", aggfunc=np.sum)

rawDescription: Pivot_table MultiIndex to columns

description: Pivot_table MultiIndex to columns


code: _, unique = np.unique(a.round(decimals=14), return_index=True)

rawDescription: Efficiently Removing Very-Near-Duplicates From Python List


code:
def proc(filename, lineno):
    line = linecache.getline(filename, lineno)
    a, *b, c, d, e, f = line.strip().split('|')
    b = '|'.join(b)
    # do something

rawDescription: Chopping A Line From A Text Document Into Different Strings


rawDescription: Identifying a 'straight' (from Poker) using Python


code:
keys = ['Q_geo_ges_h', 'Q_geo_ges_k']
values = [12.6, 1.943]
zip(keys, values)

rawDescription: working with placeholder in variable names in Python, wx.python

description: Working with placeholder in variable names in Python, wx.python


code: filt_df = df.loc[:, df.columns != 'User_id']

rawDescription: Remove Outliers in Pandas DataFrame using Percentiles


code:
fig = plt.figure()
ax = fig.add_subplot(111, xlabel="time", ylabel="money")

rawDescription: Matplotlib: set x y label in one line

description: Matplotlib: set x y label in one line


rawDescription: What is an elegant way to select all non-None elements from parameters and place them in a python dictionary?


code:
import datetime

def same_week(date1, date2):
    d1 = datetime.datetime.strptime(date1,'%Y%m%d')
    d2 = datetime.datetime.strptime(date2,'%Y%m%d')
    return d1.isocalendar()[1] == d2.isocalendar()[1] \
              and d1.year == d2.year

rawDescription: what would be the pythonic way to find out if a given date belongs to the current week?

description: What would be the pythonic way to find out if a given date belongs to the current week


code:
result = some_task.apply_async(args=myargs)
result_output = result.wait(timeout=None, interval=0.5)

rawDescription: Stop the thread until the celery task finishes


rawDescription: Remove small words using Python

description: Remove small words using Python


code:
class Bar(models.Model):
    foo_order = models.IntegerField()
    foo = models.ForeignKey(Foo, related_name='bars')

    class Meta:
        unique_together = ('foo', 'foo_order')

    def save(self, *args, **kwargs):
        if not self.foo_order:
            self.foo_order = self.bar_set.count() + 1
        super(Bar, self).save(*args, **kwargs)

rawDescription: Multiple database objects with the same ID using unique_together


code:
with open("/home/ubuntu/tmp/deploy/all", 'r') as f2:
    newvars = ruamel.yaml.round_trip_load(f2)

rawDescription: Copy content from one YAML to another YAML after comparison of keys


rawDescription: Execute code when extending a class in Python


code:
from tkinter import Tk, ttk
from urllib.request import urlopen

def download2(url, filename):
    response = urlopen(url)
    totalsize = int(response.headers['Content-Length']) # assume correct header
    outputfile = open(filename, 'wb')

    def download_chunk(readsofar=0, chunksize=1 << 13):
        # report progress
        percent = readsofar * 1e2 / totalsize # assume totalsize > 0
        root.title('%%%.0f %s' % (percent, filename,))
        progressbar['value'] = percent

        # download chunk
        data = response.read(chunksize)
        if not data: # finished downloading
            outputfile.close()
            root.destroy() # close GUI
        else:
            outputfile.write(data) # save to filename
            # schedule to download the next chunk
            root.after(0, download_chunk, readsofar + len(data), chunksize)

    # setup GUI to show progress
    root = Tk()
    root.withdraw() # hide
    progressbar = ttk.Progressbar(root, length=400)
    progressbar.grid()
    # show progress bar if the download takes more than .5 seconds
    root.after(500, root.deiconify)
    root.after(0, download_chunk)
    root.mainloop()

download2(url, 'downloaded_file.py')

rawDescription: Download progressbar for Python 3

description: Download progressbar for Python 3


code:
t2 = []
for x in range(len(t1)/3): t2.append(t1[x*3 : x*3+3])

t2

rawDescription: Regex Help, por favor

description: Regex Help, por favor


code:
import argparse

# Build the parser
p = argparse.ArgumentParser(prog='CODE.PY')
p.add_argument('-i1', type=argparse.FileType('r'),
               metavar='sourcefile1', help='First input file')
p.add_argument('-i2', type=argparse.FileType('r'),
               metavar='sourcefile2', help='Second input file')
p.add_argument('-o', type=argparse.FileType('w'),
               metavar='destfile', help='Destination filename')

# Parse sys.argv
ns = p.parse_args()

# Use the files
data1 = ns.i1.read()
data2 = ns.i2.read()
result = data1[:10] + data2[:10]
ns.o.write(result)

rawDescription: python - is it possible to enter user-chosen input and output files

description: Python - is it possible to enter user-chosen input and output files


code:
class Mylist(Mixin):
    def __init__ (self, lista):
        if not type (lista) == type (""):
            self.value = lista[:]
    def __add__ (self,some):
        return self.value + some
    def __getitem__ (self,item):
        return self.value[item]
    def __getslice__ (self, beg, end):
        return self.value[beg:end]
a=Mylist([1,2])
a.value

rawDescription: Mixin class to trace attribute requests - __attribute__ recursion


code:
def get_default(size_x,size_y):
    # returns a new matrix filled with 'default values'
    tmp = np.empty([size_x,size_y])
    tmp.fill(np.nan)
    return tmp

rawDescription: How to concatenate an empty array with Numpy.concatenate?

description: Concatenate an empty array with Numpy.concatenate


code:
class ReportDeque(deque):
    """
    Container for processing, sorting Report objects
    """

    def sort(self, *args, **kwargs):
        items = [self.pop() for x in xrange(len(self))]
        items.sort(*args, **kwargs)
        self.extend(items)

rawDescription: how to sort class on datetime, sort collections.deque

description: Sort class on datetime, sort collections.deque


code:
import re
line = "hello [delete this] there!"
line = re.sub(
              r"""(?x)  # Verbose regex:
              \[        # Match a [
              [^][]*    # Match zero or more (*) characters except (^) ] or [
              \]        # Match a ]""",
              "", line)

rawDescription: Removing specific strings

description: Removing specific strings


code:
def letter_grade(mark):
    if mark >= 10:
        return "A+"
    elif 9 < mark < 10:
        return "A"
    elif 7 < mark <= 9:
        return "B"
    elif 5 < mark <= 7:
        return "C"
    else:
        return "D"

rawDescription: Passing mark qualification with Python collection


code: graph = sps.csr_matrix((data['weight'], (data['from'], data['to'])))

rawDescription: How to read a sparse directed graph in scipy

description: Read a sparse directed graph in scipy


code:
conditions = (check_size, check_color, check_tone, check_flavor)
for condition in conditions:
    result = condition()
    if result:
        return result

rawDescription: Pythonic way to avoid "if x: return x" statements


rawDescription: different answer in javascript and python with large number- Division or mod operator

description: Different answer in javascript and python with large number- Division or mod operator


code:
def start(self):
    ...
    try:
        _start_new_thread(self._bootstrap, ())
    except Exception:
        with _active_limbo_lock:
            del _limbo[self]
        raise
    self._started.wait()

rawDescription: Can isAlive() be False immediately after calling start() because the thread hasn't yet started?


code:
def contains(a, b):
    for v in b:
        if not any(v == u for u in a):
            return False
    return True

rawDescription: How can I use python code which will iterate into two list and will find out whether they matches or not

description: Use python code which will iterate into two list and will find out whether they matches or not


rawDescription: Sort python dictionaries with 'value' as primary key and 'key' as secondary


code:
for button, line_edit in ...:
    button.clicked.connect(lambda : self.show_dialog(line_edit))

rawDescription: pyside / pyqt: simple way to bind multiple buttons that shares the same functionality

description: Pyside / pyqt: simple way to bind multiple buttons that shares the same functionality


code:
parser = argparse.ArgumentParser(parents=[general_group])
subparsers=parser.add_subparsers(dest='action')
subparsers.add_parser('Restart',parents=[second_group])
subparsers.add_parser('Start')

rawDescription: How to show help for all subparsers in argparse?

description: Show help for all subparsers in argparse


code:
VK_MENU = 0x12
VK_F = 0x46

def show_menu(handle):
    for key in (VK_MENU, VK_F):
        send_message(window_handle, WM_KEYDOWN, key, 0)
        send_message(window_handle, WM_KEYUP, key, 0)

rawDescription: Display menu bar items of IE using Python


code:
if x > 0:
    return math.pow(x, float(1)/3)
elif x < 0:
    return -math.pow(abs(x), float(1)/3)
else:
    return 0

rawDescription: Cubic root of the negative number on python


code:
def make_video(audio, key):
    audio_destination_file, audio_name, audio_artist, audio_album, audio_title = audio
    # Do something with audio_destination_file, audio_name, audio_artist,
    # audio_album, audio_title and key ...

rawDescription: How to assign values returned from a function to another function

description: Assign values returned from a function to another function


code:
with open(output) as outf:
    print_results(..., outf=outf)

rawDescription: Printing to stdout or file without repeating code


code: from conf import general

rawDescription: Importing modules to a package

description: Importing modules to a package


code: del x

rawDescription: Is there a way to delete created variables, functions, etc from the memory of the interpreter?


code:
import re, collections

mylist = ['Probes', 'Gene.symbol', 'Gene.Title', 'GO1', 'GO2', 'GO3', 'ADX_KD_06.ip', 'ADX_KD_24.ip', 'ADX_LG_06.ip', 'ADX_LG_24.ip', 'ADX_LV_06.ip', 'ADX_LV_24.ip', 'ADX_SP_06.ip', 'ADX_SP_24.ip', 'ADX_LN_06.id', 'ALM_LN_06.id', 'ALM_LV_06.ip', 'ALM_SP_06.ip', 'K3SPG_LV_06.ip', 'K3SPG_SP_06.ip', 'KKK_LN_06.id', 'KKK_LV_06.ip', 'KKK_SP_06.ip', 'ENDCN_LV_06.in', 'ENDCN_SP_06.in', 'bCD_LV_06.ip', 'bCD_SP_06.ip', 'ADX_LV_06.id', 'ADX_SP_06.id', 'ALM_LV_06.id', 'ALM_SP_06.id', 'D35_LN_06.id', 'K3SPG_LN_06.id', 'K3_LV_06.id', 'K3_SP_06.id', 'bCD_LN_06.id', 'D35_LV_06.id', 'D35_SP_06.id', 'K3SPG_LV_06.id', 'K3SPG_SP_06.id', 'bCD_LV_06.id', 'bCD_SP_06.id', 'ENDCN_KD_06.in', 'ENDCN_LG_06.in', 'Probes', 'Gene.symbol', 'ADX_KD_06.ip', 'ADX_KD_24.ip', 'ADX_LG_06.ip', 'ADX_LG_24.ip', 'ADX_LV_06.ip', 'ADX_LV_24.ip', 'ADX_SP_06.ip', 'ADX_SP_24.ip', 'ADX_LN_06.id', 'ALM_LN_06.id', 'ALM_LV_06.ip', 'ALM_SP_06.ip', 'K3SPG_LV_06.ip', 'K3SPG_SP_06.ip', 'KKK_LN_06.id', 'KKK_LV_06.ip', 'KKK_SP_06.ip', 'ENDCN_LV_06.in', 'ENDCN_SP_06.in', 'bCD_LV_06.ip', 'bCD_SP_06.ip', 'ADX_LV_06.id', 'ADX_SP_06.id', 'ALM_LV_06.id', 'ALM_SP_06.id', 'D35_LN_06.id', 'K3SPG_LN_06.id', 'K3_LV_06.id', 'K3_SP_06.id', 'bCD_LN_06.id', 'D35_LV_06.id', 'D35_SP_06.id', 'K3SPG_LV_06.id', 'K3SPG_SP_06.id', 'bCD_LV_06.id', 'bCD_SP_06.id', 'ENDCN_KD_06.in', 'ENDCN_LG_06.in']

regex = re.compile(r'([\w\d]+)_(\w\w)_(\d\d)\.(\w\w)')
first_part_dict = collections.defaultdict(list)
second_part_dict = collections.defaultdict(list)
# second instance of 'Probes', to separate the first and second parts
cutoff_index = mylist.index('Probes', 1)

for i, string in enumerate(mylist):
    matched = regex.match(string)
    if not matched:
        continue
    rg1, rg2, rg3, rg4 = matched.groups()
    key = rg1 + rg3
    if i < cutoff_index:
        first_part_dict[key].append(i)
    else:
        second_part_dict[key].append(i)

rawDescription: Getting index of structured elements of a list into dictionaries based on regex


code:
captcha = CaptchaStore.objects.all()[0]
registration_data = { # other registration data here
                     'captcha_0': captcha.hashkey,
                     'captcha_1': captcha.response }

rawDescription: How to unit test a form with a captcha field in django?

description: Unit test a form with a captcha field in django


code:
import sys
import Tkinter as tk
import tkFont

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        header = "SequenSack and PaFull Name****************************]JOB TITLE****************]HOSP NAME******************************]Delivery Address***********************]Alternate 1 Address********************]Calculated Text**********************************]POSTNET Bar"
        sample = "000001T1  P1     Sample A Sample                                                                                123 Any Street                                                                  Anytown 12345-6789                                12345678900"
        widget = DelimiterWidget(self, header, sample)
        hsb = tk.Scrollbar(orient="horizontal", command=widget.xview)
        widget.configure(xscrollcommand=hsb.set)
        hsb.pack(side="bottom", fill="x")
        widget.pack(side="top", fill="x")

class DelimiterWidget(tk.Text):
    def __init__(self, parent, header, samplerow):
        fixedFont = tkFont.nametofont("TkFixedFont")
        tk.Text.__init__(self, parent, wrap="none", height=3, font=fixedFont)
        self.configure(cursor="left_ptr")
        self.tag_configure("header", background="gray")
        self.tag_configure("even", background="#ffffff")
        self.tag_configure("header_even", background="bisque")
        self.tag_configure("header_odd", background="lightblue")
        self.tag_configure("odd", background="#eeeeee")
        markers = " "*len(header)
        for i in range(len(header)):
            tag = "even" if i%2==0 else "odd"
            self.insert("end", " ", (tag,))
        self.insert("end", "\n")
        self.insert("end", header+"\n", "header")
        self.insert("end", samplerow, "sample")
        self.configure(state="disabled")
        self.bind("<1>", self.on_click)
        self.bind("<Double-1>", self.on_click)
        self.bind("<Triple-1>", self.on_click)

    def on_click(self, event):
        '''Handle a click on a marker'''
        index = self.index("@%s,%s" % (event.x, event.y))
        current = self.get(index)
        self.configure(state="normal")
        self.delete(index)
        (line, column) = index.split(".")
        tag = "even" if int(column)%2 == 0 else "odd"
        char = " " if current == "x" else "x"
        self.insert(index, char, tag)
        self.configure(state="disabled")
        self.highlight_header()
        return "break"

    def highlight_header(self):
        '''Highlight the header based on marker positions'''
        self.tag_remove("header_even", 1.0, "end")
        self.tag_remove("header_odd", 1.0, "end")
        markers = self.get(1.0, "1.0 lineend")

        i = 0
        start = "2.0"
        tag = "header_even"
        while True:
            try:
                i = markers.index("x", i+1)
                end = "2.%s" % i
                self.tag_add(tag, start, end)
                start = self.index(end)
                tag = "header_even" if tag == "header_odd" else "header_odd"
            except ValueError:
                break

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

rawDescription: Tkinter GUI to Convert Fixed Width File to Delimited File


rawDescription: Newick tree representation to scipy.cluster.hierarchy linkage matrix format


code:
from django.template import Context, Template

def wrap_plugin(instance, placeholder, rendered_content, original_context):
    t = Template('
{{ content|safe }}
')
    c = Context({
        'content': rendered_content
    })
    return t.render(c)

rawDescription: Wrap every plugin separately in Django CMS


code:
class Polynomial(list):
    def __repr__(self):
        # joiner[first, negative] = str
        joiner = {
            (True, True): '-',
            (True, False): '',
            (False, True): ' - ',
            (False, False): ' + '
        }

        result = []
        for power, coeff in reversed(list(enumerate(self))):
            j = joiner[not result, coeff < 0]
            coeff = abs(coeff)
            if coeff == 1 and power != 0:
                coeff = ''

            f = {0: '{}{}', 1: '{}{}x'}.get(power, '{}{}x^{}')

            result.append(f.format(j, coeff, power))

        return ''.join(result) or '0'

rawDescription: Pretty polynomial printing in python

description: Pretty polynomial printing in python


code:
import numpy as np
import scipy.stats as ss

a = ss.norm.rvs(4, 2, 40)
hist(a, normed=True)

xs = np.linspace(0, 10, 30)
plot(xs, ss.norm.pdf(xs, 4, 2), label='pdf')
plot(xs, ss.norm.cdf(xs, 4, 2), label='cdf')

rawDescription: Generating a probability from a pdf?

description: Generating a probability from a pdf


code:
class LabelEntry(object):
    def __init__(self, parent, text, command):
        self.command = command
        self.label = Label(parent, text=text)
        self.entry = Entry(parent)
        self.button = Button(parent, text="Cal", command=self.call_command)

    def call_command(self):
        value = self.entry.get()
        self.command(value)

rawDescription: Creating entry and buttons linked in tkinter


rawDescription: Is there a wx.EVT_CHAR or event.GetKeyCode() equivalent for wxPython( Phoenix )?


code:
def cartesian(a, b, c):
    yield from product(get_chunks(a, 2), get_chunks(b), get_chunks(c))

rawDescription: Cartesian product that returns outputs of varied lengths


code: np.loadtxt(fname, skiprows=N)

rawDescription: numpy.loadtxt Skipping multiple rows

description: Numpy.loadtxt Skipping multiple rows


code:
from itertools import imap

def power_at_each_point(x_coord, y_coord):
    f = lambda x: cal_pow_rec_plandwall(x, [x_coord, y_coord])
    return max(imap(f, xrange(1, len(Node_Positions_Ascending) + 1)))

rawDescription: I want to sort a list in a method with respect to the method's argument


code:
s = '/apps/platform/app/app_name/etc'
re.sub(r'(?<=/apps/)(?P<p1>.*)(/app/)(?P<p2>.*)/', r'windows\2facebook/', s)

rawDescription: python how to replace string by regex group?

description: Python how to replace string by regex group


code:
import sys
sys.maxsize
random.randint(0,sys.maxsize)

rawDescription: How to Generate N random numbers in Python 3 between 0 to infinity


code:
@register.inclusion_tag('includes/gravatar_links.html')
def gravatar_links(email, first_name):
    url = "http://www.gravatar.com/" + hashlib.md5(email.lower()).hexdigest()
    url += '.json'

    response = urllib2.urlopen(url)
    interm = simplejson.load(response)
    accounts_list = interm["entry"][0]["accounts"]
    data = simplejson.dumps(interm)

    return {'gravatar_links': {'accounts': accounts_list, 'name': first_name, 'data': data}}

rawDescription: Accessing JSON data with Django

description: Accessing JSON data with Django


code:
import os
import stat
import pwd
import collections
import operator

os.chdir('/proc')
dirnames=(dirname for dirname in os.listdir('.') if dirname.isdigit())
statinfos=(os.stat(dirname) for dirname in dirnames)
uids=(statinfo[stat.ST_UID] for statinfo in statinfos)
names=(pwd.getpwuid(uid).pw_name for uid in uids)
counter=collections.defaultdict(int)
for name in names:
    counter[name]+=1
count=counter.items()
count.sort(key=operator.itemgetter(1),reverse=True)
print('\n'.join(map(str,count[:10])))

rawDescription: How to print the top 10 users by the number of processes?

description: Print the top 10 users by the number of processes


code:
with open('youtube-dl', 'rb') as f:
    header = f.readline()
    zipfile = f.read()

with open('youtube-dl-new', 'wb') as f:
    print('#!/your/new/hashbang/line', file=f)
    f.write(zipfile)

rawDescription: Python youtube-dl recompile

description: Python youtube-dl recompile


rawDescription: Use built-in setattr simultaneously with index slicing


code:
if 'CRONRUN' in os.environ:
   ...

rawDescription: Is there a way to determine if a python script was started by Cron?


code:
if value in replacement_map:
    output.extend(replacement_map[value])
else:
    output.append(value)

rawDescription: Python CSV: write rows according to dict mapping


rawDescription: argument order in numpy.apply_along_axis

description: Argument order in numpy.apply_along_axis


code:
class TagWidget(SelectMultiple):
    """
    Widget for Tag input fields.
    """
    queryset = []

    def render(self, name, value, attrs=None):
        final_attrs = self.build_attrs(attrs, name=name)
        final_attrs['class'] = 'tag-input'

        selectedTags = []
        if value:
            for tag_id in value:
                if isinstance(tag_id, (int, long)) or tag_id.isdigit():
                    tag_name = Tag.objects.get(pk=tag_id).name
                    selectedTags.append({ 'value': str(tag_id) + '___' + tag_name, 'label': tag_name })
                else:
                    autocompletedTag = tag_id.find('___')
                    if autocompletedTag > 0:
                        parts = tag_id.split('___')
                        selectedTags.append({ 'value': parts[0] + '___' + parts[1], 'label': parts[1] })
                    else:
                        selectedTags.append({ 'value': tag_id, 'label': tag_id })

        allTags = []
        for tag in self.queryset:
            allTags.append({ 'value': str(tag.id) + '___' + str(tag.name), 'label': str(tag.name) });

        allTagsJson = simplejson.dumps(allTags)

        return render_to_string('form/tagwidget.html',
                                {'attrs': flatatt(final_attrs), 'selectedTags': selectedTags, 'allTags': allTagsJson})

rawDescription: Django model pre save for custom ManyToManyField


rawDescription: average of a number of arrays with numpy without considering zero values

description: Average of a number of arrays with numpy without considering zero values


code: df['C'] = np.where(df['A'] == 1, df.index, '')

rawDescription: Pandas lookup values from different columns


code:
if __name__ == '__main__':

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

rawDescription: How to import mainwindow (.ui file) using PySide

description: Import mainwindow (.ui file) using PySide


code:
from mpl_toolkits.basemap import Basemap
map = Basemap(projection='merc', lat_0=50, lon_0=4,
    resolution = 'l', area_thresh = 0.1,
    llcrnrlon=4, llcrnrlat=50,
    urcrnrlon=40, urcrnrlat=60)

map.readshapefile('luthuania', 'any_name_you_like', drawbounds=True, linewidth=2, color='b')

map.drawcoastlines(linewidth=0.15)
map.drawcountries(linewidth=0.15)
map.fillcontinents(color='brown',lake_color='white')
map.drawmapboundary(fill_color='white')

rawDescription: Adding one polygon to a plot using matplotlib-basemap


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-u", action='store_true')
parser.add_argument("-d")
args = parser.parse_args(['-u'])
args.u
args.d
args.u and not args.d
args = parser.parse_args(['-u', '-d', 'foo'])
args.d
args.u and not args.d

rawDescription: Python handling options and args

description: Python handling options and args


code:
[['id2', 'string3', 'string4'],
 ['id3', 'string4', 'string5', 'string6'],
 ['id1', 'string1', 'string2', 'string3']]

rawDescription: Match lists and write result to new list


rawDescription: Create datetime.time() object in yaml?

description: Create datetime.time() object in yaml


code:
df1 = pd.DataFrame(np.random.choice([0, 0.75], size=(4,5)), columns=list('ABCDE'), index=list('WXYZ'))
heatmap_binary(df1)

rawDescription: Annotate heatmap with value from Pandas dataframe


code:
def func1():
    import tkinter as tk

    root1 = tk.Tk()

    def kill1():
        root1.destroy()
        from py2 import func2
        func2()

    button1 = tk.Button(root1, bg = 'green', text = 'hit to kill py1 and start py2', command = kill1)
    button1.pack()

    root1.mainloop()

if __name__ == '__main__':
    func1()

rawDescription: Python3 Tkinter - Open .py file with button


rawDescription: importing an array from a .dat file in python

description: Importing an array from a .dat file in python


code:
def regroup(values):
    groups = dict()
    for d in values:
        key = (d["prod_name"], d["prod_hola"])
        if key in groups:
            group = groups[key]
            group["rashod"] += d["rashod"]
            group["prihod"] += d["prihod"]
        else:
            groups[key] = d.copy()
    return list(groups.values())

rawDescription: Python sum dict values based on keys

description: Python sum dict values based on keys


code:
def change_lines(fileC):

    with open(fileC , 'r') as f:
        while True:
            lines = []
            for i in range(4):
                try:
                    lines.append(f.next()) # f.next() returns next line in file
                except StopIteration: # this will happen if you reach end of file before finding 4 more lines.
                    #decide what you want to do here
                    return
            # otherwise this will happen
            lines[2] = lines[4] # or whatever you want to do here
            # maybe write them to a new file
            # remember you're still within the for loop here

rawDescription: Ways to read/edit multiple lines in python


code: edge = Edge.all().filter('better =', vertex1).filter('worse =', vertex2).get()

rawDescription: Storing a directed, weighted, complete graph in the GAE datastore


rawDescription: PyGame: Economic way of handling game loops


code:
hextext = "H:\myfilepath.myfileending"
encodedhex = "".join(c.encode("hex")+"00" for c in hextext)
encodedhex
encodedhex.upper()

rawDescription: python encode hex pad every character with 00

description: Python encode hex pad every character with 00


code:
class OrExpression:
    def __init__(self, left, right):
        self.left = left
        self.right = right
    def eval(self, variables):
        return self.left.eval(variables) or self.right.eval(variables)

class EqualsExpression:
    def __init__(self, left, right):
        self.left = left
        self.right = right
    def eval(self, variables):
        return self.left.eval(variables) == self.right.eval(variables)

class Literal:
    def __init__(self, value):
        self.value = value
    def eval(self, variables):
        return self.value

class Variable:
    def __init__(self, name):
        self.name = name
    def eval(self, variables):
        return variables[self.name]

rawDescription: Create python functions from expression trees


rawDescription: Python regex: find and replace commas between quotation marks


rawDescription: Regex matching newline before word in python


rawDescription: pandas group filter issue

description: Pandas group filter issue


rawDescription: zero fill empty spaces at specific locations

description: Zero fill empty spaces at specific locations


rawDescription: Changing a form html name in a template

description: Changing a form html name in a template


code:
def everythird(l):
    return [l[i] for i in range(0, len(l), 3)]

rawDescription: Python: How to return a list without modifying the original list using a while loop only?


code:
d = {'data': [{'L': 'Leinster'}, {'RN': 'Roscommon'}, {'G': 'Galway'}, {'LS': 'Laois'}, {'LD': 'Longford'}, {'OY': 'Offaly'}, {'KK': 'Kilkenny'}, {'SO': 'Sligo'}, {'C': 'Connaught'}, {'CO': 'Cork'}, {'M': 'Munster'}, {'WD': 'Waterford'}, {'CE': 'Clare'}]}
dict((k,sorted(v,key=dict.values)) for k,v in d.iteritems())

rawDescription: sort sub-dicts in a dict by value of the sub-dict

description: Sort sub-dicts in a dict by value of the sub-dict


code:
#steps around circle from 0 to 2*pi(360degrees)
#reshape at the end is to be able to use np.dot properly
revolve_steps = np.linspace(0, np.pi*2, 600).reshape(1,600)

rawDescription: Python: How to revolve a surface around z axis and make a 3d plot?


code:
csv.register_dialect('mydialect', delimiter=' ', quoting=csv.QUOTE_MINIMAL)
csv.writer(open("try.csv", "w"), dialect="mydialect").writerows(a_ps)

rawDescription: Writing a results to a .txt file using csv


code:
def get_first_common_element(x,y):
    ''' Fetches first element from x that is common for both lists
        or return None if no such an element is found.
    '''
    for i in x:
        if i in y:
            return i

    # In case no common element found, you could trigger Exception
    # Or if no common element is _valid_ and common state of your application
    # you could simply return None and test return value
    # raise Exception('No common element found')
    return None

rawDescription: First common element from two lists

description: First common element from two lists


code:
from django import forms
class RelationForm(forms.ModelForm):
    parent = forms.ChoiceField(required=False,
                              choices=Relation.objects.values_list('id', 'name'))
    particle = forms.ChoiceField(required=False,
                              choices=Particle.objects.values_list('id', 'content'))
    media = forms.ChoiceField(required=False,
                              choices=Media.objects.values_list('id', 'name'))

    class Meta:
        model = Relation

rawDescription: Django admin change form load quite slow


code: E3 = [min(E2, key=lambda x: abs(x-i)) for i in E1]

rawDescription: comparing two different lists

description: Comparing two different lists


code:
def load_words(file1):
    answer = {}
    for line in file1:
        line = line.strip()
        if line[0] in answer: # or in answer.keys() or in answer.iterkeys()
            if line not in answer[line[0]]:
                answer[line[0]].append(line)
        else:
            answer[line[0]] = [line] # or answer[line[0]] = []; answer[line[0]].append(line)
    return answer

rawDescription: dictionary help for python using a file

description: Dictionary help for python using a file


rawDescription: Python: sort dictionary with tuples as key by the value


code:
square_letter = {c: e for e in ['ABC','DEF','GHI'] for c in e}
square_number = {n: e for e in ['123','456','789'] for n in e}
r, c = square_letter[square[0]], square_number[square[1]]

rawDescription: Pythonic way of returning an element of a list if a certain char is found in that element


rawDescription: What Arguments to use while doing a KS test in python with student's t distribution?


code:
@hookable
def square(x):
  return x**2

rawDescription: allow users to "extend" API functions

description: Allow users to "extend" API functions


code:
import datetime
import re

def valid_date(datestring):
        try:
                mat=re.match('(\d{2})[/.-](\d{2})[/.-](\d{4})$', datestring)
                if mat is not None:
                        datetime.datetime(*(map(int, mat.groups()[-1::-1])))
                        return True
        except ValueError:
                pass
        return False

rawDescription: match dates using python regular expressions

description: Match dates using python regular expressions


code: self.seats[('screen1', 'day4')]['show4'] = 90

rawDescription: how to access values of nested dictionary keys in python?

description: Access values of nested dictionary keys in python


rawDescription: Splitting a 16 bit int into two 8 bit ints in python


code:
b = b'\x174R\x03\xd7\x1e\xb5e!-\xcd(D\\oL\x01'
struct.unpack('%dB' % len(b), b)

rawDescription: How does struct.unpack and struct.pack works?


code:
import numpy as np

n_examples = 100
A = np.random.randn(n_examples, 20,30)
B = np.random.randn(n_examples, 30,5)

def sol1():
    sum = np.zeros([20,5])
    for i in range(len(A)):
      sum += np.dot(A[i],B[i])
    return sum

def sol2():
    return np.array(map(np.dot, A,B)).sum(0)

def sol3():
    return np.einsum('nmk,nkj->mj',A,B)

def sol4():
    return np.tensordot(A, B, [[2,0],[1,0]])

def sol5():
    return np.tensordot(A, B, [[0,2],[0,1]])

rawDescription: Python Numpy matrix multiplication in high dimension


code: list(unpack_until(lllt, tuple))

rawDescription: Is there a way of avoiding so many list(chain(*list_of_list))?


code:
number = 1
elements = 1000

thelist = [number] * elements

rawDescription: Efficient way to create list of same numbers?


code:
a_csr = scipy.sparse.csr_matrix(a)
a_csr.indices
np.unique(a_csr.indices).shape[0]

rawDescription: numpy matrix multiplication to triangular/sparse storage?

description: Numpy matrix multiplication to triangular/sparse storage


code:
def setup(app):
    app.add_autodocumenter(SimpleDocumenter)

rawDescription: Including docstring in Sphinx Documentation


rawDescription: multiprocessing Pool.imap broken?

description: Multiprocessing Pool.imap broken


code:
import os
import subprocess
PIPE = subprocess.PIPE

def content_generator(command):
    subprocess.Popen(command, stdout=PIPE, stderr=PIPE)
    content = None
    while content != '':
        content = os.read(process.stdout.fileno(), 1024)
        yield content

rawDescription: send live console data back from server to client using django

description: Send live console data back from server to client using django


code: temp2 = np.copy(temp, order='C')

rawDescription: Force numpy array to physically match striding in memory


code: ['znc-devel', 'znc-devel2']

rawDescription: Removing suffix from list Python

description: Removing suffix from list Python


rawDescription: "Less/greater than" comparison of N-dimensional and (N-k)-dimensional numpy arrays


code:
from scipy.sparse import csr_matrix
A = csr_matrix((5, 5))
A.nnz
A[0, 0] = 0
A.nnz
A[1,1] = 0
A.nnz

rawDescription: Sparse Matrix Addition

description: Sparse Matrix Addition


rawDescription: Python xml Trying to show a if statement on a tag


code:
def get_items(db_connection):
    cursor = db_connection.cursor()
    cursor.execute("SELECT a, b FROM some_table")
    items = cursor.fetchall()
    return items

rawDescription: Printing data from MySql in HTML using Python


code: jvm = sc._jvm

rawDescription: How to use a Scala class inside Pyspark

description: Use a Scala class inside Pyspark


code:
for item in iterable:
    stuff(item)

rawDescription: How do I return a set of n consecutive integers given n and an iterable?

description: Return a set of n consecutive integers given n and an iterable


code:
xx.sort()
plt.plot(xx, ecdf(xx))
plt.show()

rawDescription: ECDF in python without step function?

description: ECDF in python without step function


code:
s = set()
s.add(4)
s.add(5)
s
t = set([2, 4, 9])
s.intersection(t)

rawDescription: Take the intersection of an arbitrary number of lists in python


code:
from copy_reg import dispatch_table
from types import TypeType, StringType, TupleType
from pickle import Pickler, PicklingError

def pickler_save(self, obj):
    # Check for persistent id (defined by a subclass)
    pid = self.persistent_id(obj)
    if pid:
        self.save_pers(pid)
        return

    # Check the memo
    x = self.memo.get(id(obj))
    if x:
        self.write(self.get(x[0]))
        return

    # Check the type dispatch table
    t = type(obj)
    f = self.dispatch.get(t)
    if f:
        f(self, obj) # Call unbound method with explicit self
        return

    # Check copy_reg.dispatch_table
    reduce = dispatch_table.get(t)
    if reduce:
        rv = reduce(obj)
    else:
        # Check for a class with a custom metaclass; treat as regular class
        try:
            issc = issubclass(t, TypeType)
        except TypeError: # t is not a class (old Boost; see SF #502085)
            issc = 0
        if issc:
            self.save_global(obj)
            return

        # Check for a __reduce_ex__ method, fall back to __reduce__
        reduce = getattr(obj, "__reduce_ex__", None)
        if reduce:
            rv = reduce(self.proto)
        else:
            reduce = getattr(obj, "__reduce__", None)
            if reduce:
                rv = reduce()
            else:
                raise PicklingError("Can't pickle %r object: %r" %
                                    (t.__name__, obj))

    # Check for string returned by reduce(), meaning "save as global"
    if type(rv) is StringType:
        self.save_global(obj, rv)
        return

    # Assert that reduce() returned a tuple
    if type(rv) is not TupleType:
        raise PicklingError("%s must return string or tuple" % reduce)

    # Assert that it returned an appropriately sized tuple
    l = len(rv)
    if not (2 <= l <= 5):
        raise PicklingError("Tuple returned by %s must have "
                            "two to five elements" % reduce)

    # Save the reduce() output and finally memoize the object
    self.save_reduce(obj=obj, *rv)

Pickler.save = pickler_save

rawDescription: Pickle doesn't take my registered custom type reduce function into account on python 2.6


rawDescription: Trying to write my own Neural Network in Python


code:
from locale import atof
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
mylist = ['23 text', '23.130', '12 text', '1.482 text', '3,250']
sorted(mylist,key=lambda x: atof(x.split()[0]))

rawDescription: Sort numeric lines with thousand separators


code:
self.setStyleSheet("""
        QPushButton{
        opacity: 50;
        background-color: rgba(204,204,204,10);
        }
        """)

rawDescription: round edges corner on a QWidget in PyQt

description: Round edges corner on a QWidget in PyQt


code:
from django.contrib.contenttypes import generic

class Note(models.Model):
    tags = generic.GenericRelation(TaggedItem)
    [...]

rawDescription: Django tastypie including generic foreign key field results


code:
def run(self):
        while True:
            try:
                data = self.source.recv(1024)
                if not data:
                    break
                self.sink.send(data)
            except Exception as e:
                logging.error(e)
                break
        logging.info('%s terminating' % self)

        self.sink.shutdown(socket.SHUT_WR) #close the socket on the write side

        PipeThread.pipes.remove(self)
        logging.info('%s pipes active' % len(PipeThread.pipes))

rawDescription: Why do I need `Ctrl-c` when `curl` to the this tcp proxy


code: dct[item][key]

rawDescription: In Python, how do I write the contents of nested dictionaries to a file in a certain format?


code:
pd.Timestamp(datetime.date(2013, 12, 25))
ts = pd.DatetimeIndex([t])
ts == pd.Timestamp(datetime.date(2013, 12, 25))

rawDescription: Pandas: Convert Timestamp to datetime.date


rawDescription: Appending a column in a pandas DataFrame based on a different DataFrame


rawDescription: Python permutations including substrings


rawDescription: How can I convert an absolutely massive number to a string in a reasonable amount of time?

description: Convert an absolutely massive number to a string in a reasonable amount of time


code: dic3 = { k : (dic1[k], dic2[k]) for k in dic1.keys() & dic2.keys() }

rawDescription: Match keys from two dictionaries, and make new dictionary with matched key and two associated values


rawDescription: Python Pandas, Resampling only specific hours


rawDescription: Python dict.update() with C++ std::map?

description: Python dict.update() with C++ std::map


code:
# python
import h5py
with h5py.File('test.h5', 'r') as f:
    points = f['/Points'].value

rawDescription: export matlab variable to text for python usage

description: Export matlab variable to text for python usage


code:
hexadecimal_id = repr(p).rpartition(' ')[-1][:-1]
present = int(hexadecimal_id, 16) == id(p)

rawDescription: Object's unique identifier (translate from hexadecimal into decimal)


code:
class MyModel(models.Model):
    pct = models.StringField(validators=[valid_pct])

rawDescription: Django percentage form field

description: Django percentage form field


code:
from collections import defaultdict

arr = ['a', 1, 2, 3, 'b', 4, 5, 6]

d = defaultdict(list)

cur_key = arr[0]

for value in arr[1:]:
    if type(value) != type(cur_key):
        d[cur_key].append(value)
    else:
        cur_key = value

print(d)

rawDescription: Elegant way to split list on particular values


rawDescription: How to capture both lookahead lookbehind regex python

description: Capture both lookahead lookbehind regex python


rawDescription: Creating a dynamically drawn line in Kivy


code:
london = geodetic2ecef(51, 0)
tree.query_ball_point([london], r=euclidean_distance(100))

rawDescription: Python - how to speed up calculation of distances between cities


code:
f = lambda x: x**2
def g(x):
    return x**2
import dis
dis.dis(f)
dis.dis(g)

rawDescription: Handling NoneType in len() while in a Python lambda expression?


code:
x = MyObj(2)
MyObj.__add__(x, 3)  # we pass in a reference to x explicitly
x.__add__(3)  # method call implicitly passes reference to x
x + 3  # overloaded operator implicitly passes reference to x

rawDescription: Are python object functions singletons?

description: Are python object functions singletons


code:
if sys.version_info.major == 3 and sys.version_info.minor == 4:
    print("I like Python 3.4")

rawDescription: Python Version Specific Code

description: Python Version Specific Code


code:
from docx.api import Document

# Load the first table from your document. In your example file,
# there is only one table, so I just grab the first one.
document = Document('Books.docx')
table = document.tables[0]

# Data will be a list of rows represented as dictionaries
# containing each row's data.
data = []

keys = None
for i, row in enumerate(table.rows):
    text = (cell.text for cell in row.cells)

    # Establish the mapping based on the first row
    # headers; these will become the keys of our dictionary
    if i == 0:
        keys = tuple(text)
        continue

    # Construct a dictionary for this row, mapping
    # keys to values for this row
    row_data = dict(zip(keys, text))
    data.append(row_data)

rawDescription: Parsing of table from .docx file

description: Parsing of table from .docx file


code:
def read_in_chunks(infile, chunk_size=1024):
    while True:
        chunk = infile.read(chunk_size)
        if chunk:
            yield chunk
        else:
            # The chunk was empty, which means we're at the end
            # of the file
            return

rawDescription: Does "for line in file" work with binary files in Python?


code: dt = datetime.datetime.strptime(date + ' ' + time, '%Y-%m-%d %H:%M:%S.%f')

rawDescription: Calculate elapsed time

description: Calculate elapsed time


code: cleaned = [i for i in map(str.strip, words) if i]

rawDescription: Python - are there other ways to apply a function and filter in a list comprehension?


code:
def MatrixToMultiChannel(f,x,*args,**kwargs):
    nchannels=x.shape[-1]
    y=np.reshape(x,(x.size/nchannels,nchannels))
    for i in range(0,nchannels):
        yi=np.reshape(y[:,i],x.shape[:x.ndim-1])
        m1=genericF(f,yi,*args, **kwargs)
        m1=np.reshape(m1,m1.shape+(1,))
        if(i==0):
            fout=m1
        else:
            fout=np.concatenate((fout,m1),axis=m1.ndim-1)
    return fout

rawDescription: Stacking images as numpy array

description: Stacking images as numpy array


code:
if is_iterable(test):
    return [do_stuff(x) for x in test]
else:
    return [do_stuff(test)]

rawDescription: Pythonic way of looping over variable that is either an element or a list


rawDescription: Make a copy of a set and exclude one item


code:
def OpenPage(self, stime, etime):
    #[...]
    student=PresentStudent.Student() # assuming to name the class "Student"
    student.presentStudentCall(file)

rawDescription: Python timetable pass start and finish time that pressed button relevant to position


code:
so = ctypes.PyDLL("./mini.so")
so.PyInit_mini.argtypes = []
so.PyInit_mini.restype = ctypes.py_object
mini = so.PyInit_mini()
mini.version

rawDescription: How to Reload a Python3 C extension module?

description: Reload a Python3 C extension module


code:
np.matrix(B).T
np.matrix(A).T

rawDescription: Is it possible to use einsum to transpose everything?


code:
from itertools import compress

''.join(compress(A, choice))

rawDescription: Python multiplication of two list

description: Python multiplication of two list


code:
names['f'] = open('foo', 'w+')
safe_eval.safe_eval("baz = type(f)('baz', 'w+')", names)
names['baz']

rawDescription: Is "safe_eval" really safe?

description: Is "safe_eval" really safe


code:
from collections import defaultdict
nums = defaultdict(list)
for arr in a:
    key = tuple(arr[:2]) # make the first two floats the key
    nums[key].append( arr[2] ) # append the third float for the given key

a_processed = [[k[0], k[1], sum(vals)/len(vals)] for k, vals in nums.items()]

rawDescription: Get information out of sub-lists in main list elegantly


code:
file_name = input("\nEnter name of data file: ")
text_file = open(file_name,'r')
latitude = None
longitude = None

for line in text_file:
   line = line.strip()
   rows = line.split(" ")
   latitude_two = float(rows[0])
   longitude_two = float(rows[1])
   if latitude != None:
       distance = float(calculate_distance(latitude,longitude,latitude_two,longitude_two))
       print(distance)

   longitude = longitude_two
   latitude = latitude_two

rawDescription: How to update a counter variable when reading a file in Python?

description: Update a counter variable when reading a file in Python


code:
def project(key, d):
    return {k: d[k]}

map(partial(project, "name"), mine)

rawDescription: Python list of dictionaries projection, filter, or subset?


code:
import itertools
[key for key,seq in itertools.groupby([1,1,1,2,2,3,4,4])]

rawDescription: A cleaner/shorter way to solve this problem?


code:
class Front(handler.Handler):
    def get(self):
        data = []
        now = datetime.now()
        for item in b1data.b2data.all():
            airingdate = datetime.strptime(item.date_airingdate,
                                           '%Y-%m-%d %H:%M:%S')
            data.append({'allweeks': (now - airingdate).days / 7 + 1,
                         'somename': item.somename})

        self.render("front.html", data=data)

rawDescription: Python: How to correctly loop this edit in jinja2


rawDescription: python - how to convert a nested list to a list of all individual sub-lists

description: Python - how to convert a nested list to a list of all individual sub-lists


code:
Z = f(z)
Z = np.roll(Z, 1) + z
Z = np.roll(Z, -2) + z
z = np.roll(Z, 1)

rawDescription: Combining different elements of array in Numpy while doing vector operations


code:
dists >= r
dists <= r + dr
(dists >= r) & (dists <= r + dr)

rawDescription: Numpy where function multiple conditions


code:
import struct
integer, short = struct.unpack('>ih', my_string)
custom = customType.Unpack(my_string[6:9])

rawDescription: Read bytes from string in Python

description: Read bytes from string in Python


code: float_array = np.apply_along_axis(old_func, 0, (X_flattened, Y_flattened))

rawDescription: Vectorize python function

description: Vectorize python function


rawDescription: Plus and minus sequence in Python

description: Plus and minus sequence in Python


code:
data['percentage'] = data.score/data.outof
data.groupby('date').mean()

rawDescription: Add a new column after groupby in pandas


rawDescription: How can I split a string with no delimiters but with fixed number of decimal places - python

description: Split a string with no delimiters but with fixed number of decimal places - python


code:
s = set()
for line in targets:
    s.add(line.split()[0])

rawDescription: How do I efficiently crossmatch two ASCII catalogs?

description: Efficiently crossmatch two ASCII catalogs


code:
import sys
from PyQt5 import QtCore, QtWidgets

def text_change():
    print("change ok")
def text_click(event):
    print("clicked ok ")

app = QtWidgets.QApplication(sys.argv)
textEdit = QtWidgets.QTextEdit()
textEdit.setGeometry(QtCore.QRect(30, 20, 351, 51))
textEdit.setObjectName("textEdit")
textEdit.mousePressEvent = text_click
textEdit.textChanged.connect(text_change)
textEdit.show()
sys.exit(app.exec_())

rawDescription: clicked event not working in textedit of pyside

description: Clicked event not working in textedit of pyside


rawDescription: Different intervals for Gauss-Legendre quadrature in numpy


code:
conn.execute(MyTable.insert(), [{'color': 'blue'},
                                {'color': 'red'},
                                {'color': 'green'}])

rawDescription: bulk insert list values with SQLAlchemy Core

description: Bulk insert list values with SQLAlchemy Core


code:
'test.test1.test2'.rsplit('.', 1)[0]
'test.test1.test2'.rpartition('.')[0]
'test.test3.test4'.rsplit('.', 1)[0]
'test.test3.test4'.rpartition('.')[0]

rawDescription: Remove the last part of string separated with dot in Python


code:
def answer():
    number_input = int(input("Enter number: "))
    return dat[number_input]

letts = [answer() for _ in range(5)] #collect five answers of the user

rawDescription: Python 2D array with same values

description: Python 2D array with same values


code:
from copy import deepcopy
def result(matrix):
    matrix2=deepcopy(matrix)
    for a in possible_moves(matrix2):
        matrix2=deepcopy(matrix)
        print()
        liste=swap_blank_tile(matrix2,a)
        print(liste)
        print(matrix)

rawDescription: Last function code of 8puzzle in Python

description: Last function code of 8puzzle in Python


rawDescription: Finding groups of increasing numbers in a list


code:
for i in xrange(limit1):
    if 2*i >= limit2:
        break
    l.append('First index: %d, Second index: %d' % (i, 2*i))
    l.append('First index: %d, Second index: %d' % (i, 2*i+1))

rawDescription: Iterate with 2 Indexes Variable in Python


rawDescription: Creating a non-right Pascal's triangle (centered) in python


code:
def main():
    views_path = os.path.join(os.path.dirname(__file__), 'templates')
    settings.TEMPLATE_LOADERS = (('web.rich.templates.alternative_path.Loader', views_path),
                             'django.template.loaders.filesystem.Loader',
                             'django.template.loaders.app_directories.Loader')

rawDescription: How could I enable template caching in appengine after incorporating calls to parent directories?


code:
def prepare_data(line_to_fix):
    return line_to_fix.split('"')[1]
# latter on...
data[a]['state'] = prepare_data(lines[i + 1])

rawDescription: Splitting or stripping a variable number of characters from a line of text in Python?


rawDescription: Python regular expression to get URL

description: Python regular expression to get URL


code: strprime = str(prime)

rawDescription: How can I convert an absolutely massive number to a string in a reasonable amount of time?


code:
import pprint
import random

categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times

matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
newMatrix = []
for row in matrix:
    row = restrictedNumbers + [random.choice(unrestrictedNumbers) for _ in range(len(row)-len(restrictedNumbers))]
    random.shuffle(row)
    newMatrix.append(row)
pprint.pprint(newMatrix)

rawDescription: randomly fill 2d matrix with conditions

description: Randomly fill 2d matrix with conditions


rawDescription: Adding column In table with Python

description: Adding column In table with Python


code:
def die(x):
    return np.bincount(np.random.random_integers(0, 5, size=x))

rawDescription: python random number

description: Python random number


rawDescription: numpy array that is (n,1) and (n,)

description: Numpy array that is (n,1) and (n,)


code:
import re
fileText = '<text top="52" left="20" width="383" height="15" font="0">test</text>'
fileText = re.sub("(.*?)", r"\1", fileText, flags=re.DOTALL)
fileText

rawDescription: Python re.sub back reference not back referencing


code:
(0, 0) # top left
(0, 2) # third element in the first row
(0, 3) # fourth element in the first row
(1, 3) # fourth element in the second row
...    # and so on

rawDescription: Basics of numpy where function, what does it do to the array?


code:
from datetime import datetime
from dateutil.tz import gettz, tzutc

LA = gettz('America/Los_Angeles')
dt = datetime(2011, 11, 5, 12, 30, tzinfo=LA)
dt7 = next_7am(dt)

print(dt7.astimezone(tzutc()) - dt.astimezone(tzutc()))  # 19:30:00

rawDescription: How do I find the next 7am in a timezone

description: Find the next 7am in a timezone


rawDescription: Flip x and y axes for Matplotlib imshow()


code: r = client.post("http://api.imgur.com/2/account/albums.json", json=payload)

rawDescription: requests post to imgur

description: Requests post to imgur


code:
def get_nth_yaml_doc(stream, doc_nr):
    doc_idx = 0
    data = []
    for line in stream:
        if line == u'---\n' or line.startswith('--- '):
            doc_idx += 1
            continue
        if line == '...\n':
            break
        if doc_nr < doc_idx:
            break
        if line.startswith(u'%'):
            continue
        if doc_idx == 0:  # no initial '---' YAML files don't start with
            if line.lstrip().startswith('#'):
                continue
            doc_idx = 1
        if doc_idx == doc_nr:
            data.append(line)
    return yaml.load(''.join(data), Loader=yaml.RoundTripLoader)

with open("input.yaml") as fp:
    data = get_nth_yaml_doc(fp, 8)
print(yaml.dump(data, Dumper=yaml.RoundTripDumper, allow_unicode=True))

rawDescription: Load specific PyYAML documents from file


code:
@yourdecorator
def a_function():
    pass

def b_function():
    pass
b_function = yourdecorator(b_function)

rawDescription: I want to decorate a method in a class but without editing class.py -- details inside


code: new_bad_list=[item for item in bad_list if item[0] not in zip(*good_list)[0]]

rawDescription: List comprehension on lists within lists


code:
child_count=pickle.load( open("child_count.p", "rb"))
child_count-=counter
pickle.dump( child_count, open("child_count.p", "wb"))

rawDescription: Controlling multiple subprocesses in Python?


code:
import numpy as np
import pandas as pd

columns = pd.MultiIndex.from_arrays([['a1','a1','a2','a2'], ['b1','b2','b3','b4']])
index = pd.MultiIndex.from_tuples([(0,'c1','d1'), (0, 'c2', 'd3')])
df = pd.DataFrame(np.arange(1,9).reshape(2,-1), columns=columns, index=index)
#         a1    a2
#         b1 b2 b3 b4
# 0 c1 d1  1  2  3  4
#   c2 d3  5  6  7  8

rawDescription: Pandas, move one of multi-index on top of multi-column indexes


code:
ground = 720

self.y = ground.y # error !!!

rawDescription: Pygame - AttributeError: 'int' object has no attribute 'y'


rawDescription: Inserting query results into new table using loop instead of fetchall (Python, SQLite)


rawDescription: How to get Windows user's full name in python?

description: Get Windows user's full name in python


code:
import script as gh

def get_hostname(request):
        gh.main()
        return HttpResponseRedirect('/')

rawDescription: I want a button on my website that will execute a python script


code:
from collections import defaultdict

def mergeData(file1name, file2name, outfilename, a_filter_func):
    """ Merge the data of two files. """
    mergedData = defaultdict(list)
    with open(file1name, 'r') as file1, open(file2name, 'r') as file2, open(outfilename, 'w') as outfile:
        for line in file1:
            mergedData[line.split()[0].lstrip('0')].append(line)
        for line in file2:
            mergedData[line.split()[0]].append(" ".join(line.split()[:4]))
        filteredMergedData = filter(a_filter_func, mergedData.iteritems())
        for d in filteredMergedData:
            outfile.write("\n".join(d[1]) + "\n")

# finally, call the function.
filter_func = lambda x: (len(x[1]) == 2) and (int(x[1][0].split()[1]) > 15 and int(x[1][1].split()[1]) > 15)
mergeData('file1.txt', 'file2.txt', 'mergedData.txt', filter_func)

rawDescription: Python: Search a text file and then output specific data


code:
for key in list_of_possibly_new_keys:
      dict_list.setdefault(key,[]).extend([list0, list1])

rawDescription: Set or update dictionary entries code pattern in Python


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

url = 'https://caterpillar.taleo.net/careersection/cat+external+cs/jobsearch.ftl?lang=en&portal=4140124208&src=CWS-10005'
driver = webdriver.PhantomJS()
driver.get(url)

wait = WebDriverWait(driver, 10)
table = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "table.contentlist")))

for row in table.find_elements_by_css_selector("tr.ftlrow"):
    title = row.find_element_by_css_selector(".titlelink a").text
    print(title)

driver.close()

rawDescription: Submitting form to scrap data from a jobs board


code: BYTES = 'abera\xc8\x9bie'

rawDescription: UnicodeDecodeError: 'ascii' codec can't decode


code:
lol = [[1, 3], [3, 4]]
from operator import setitem
map(lambda x: setitem(x, 1, -2), lol)
lol

rawDescription: How to perform a 'one-liner' assignment on all elements of a list of lists in python

description: Perform a 'one-liner' assignment on all elements of a list of lists in python


code:
all_words1 = get_file(filename_1)
all_words2 = get_file(filename_2)
intersection_list = all_words1.intersection(all_words2)
union_list = []
for word in intersection_list:
    union_list += [word]
    union_list.sort()
for i in union_list:
    print(i)

rawDescription: How to avoid repetion with my code

description: Avoid repetion with my code


code:
class Wrapper(object):
  def __init__(self, it):
    self.it = it
    self.pushedback = []
  def __iter__(self):
    return self
  def next(self):
    if self.pushedback:
      return self.pushedback.pop()
    else:
      return self.it.next()
  def pushback(self, val):
    self.pushedback.append(val)

rawDescription: Need to add an element at the start of an iterator in python


code:
my_dict = {}

for row in reader:
    if not row[0] in my_dict.keys():
        my_dict[row[0]] = [set(), set()]

    my_dict[row[0]][0].add(row[1])
    my_dict[row[0]][1].add(row[2])

rawDescription: shorten csv file based on rules python

description: Shorten csv file based on rules python


code:
last_year = today.year - 1
Order.objects.filter(created_at__year=last_year)

rawDescription: How can i query for objects in current year , current month in django

description: Query for objects in current year , current month in django


code:
ainb = np.array([x in b for x in a[:,2]])
a[ainb]

rawDescription: Fastest way to filter a numpy array by a set of values


code:
def handle_request(req):
    for h in handlers:
        if h[1].handles(req):
            h[0] += 1
            handlers.sort(reverse=True)
            break
    else:
        return None
    return h[1]

rawDescription: Efficient way to maintain a sorted list of access counts in Python


code: sorted(myDict.items(), key=lambda e: e[1][2])

rawDescription: Python: sorting a dictionary of lists

description: Python: sorting a dictionary of lists


rawDescription: Class attribute overriding: keep parent class changes


code:
if x > y: x, y = y, x   # swap x and y if x > y
for x in range(x, y+1):
    diff = y-x

rawDescription: Comparing and reducing difference between two numbers regardless of which is larger


code: url(r'^polls/', include('polls.urls')),

rawDescription: How do I setup django with apache so that my appliction is at the root url?

description: Setup django with apache so that my appliction is at the root url


code: map(list, counter.items())

rawDescription: Histogram which do not use bin intervals but concrete values


code: new_ar = {0 if x == 'empty' else x for x in ar}

rawDescription: Normalize Array in Python

description: Normalize Array in Python


code:
from cProfile import Profile
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    ...

    def _handle(self, *args, **options):
        # Actual code I want to profile
        pass

    def handle(self, *args, **options):
        if options['profile']:
            profiler = Profile()
            profiler.runcall(self._handle, *args, **options)
            profiler.print_stats()
        else:
            self._handle(*args, **options)

rawDescription: How to profile a Django custom management command exclusively

description: Profile a Django custom management command exclusively


rawDescription: Form a big 2d array from multiple smaller 2d arrays


code:
X1 = X1 = bar_handles[startBlock].get_x()
wi = bar_handles[startBlock].get_width()
Y2 = ax.transLimits.transform((0,bar_handles[startBlock].get_height()))[1]

rawDescription: python + matplotlib: how can I change the bar's line width for a single bar?

description: Python + matplotlib: how can I change the bar's line width for a single bar


rawDescription: transpose/rotate a block of a matrix in python

description: Transpose/rotate a block of a matrix in python


code:
def calculate_vlan_id(id,ip_vlan):
  return ip_vlan.generate(id=id)

rawDescription: How to calculate value for a expression in a string, then return a new string?

description: Calculate value for a expression in a string, then return a new string


code:
def ss(li):
    l=li[:]
    sl=[]
    while len(l):
        sl.append(l.pop(l.index(min(l))))
    return sl

rawDescription: Sorting 5 elements with minimum element comparison


rawDescription: Ascending Sort of Float Dictionary Values


code: B[zip(*enumerate(ind))]=A

rawDescription: Functional assignment in numpy

description: Functional assignment in numpy


code:
from re import sub
mystr = "Hello (John)"
sub("(?s)\(.*?John.*?\)", "", mystr)
mystr = "Hello (Sally)"
sub("(?s)\(.*?John.*?\)", "", mystr)
mystr = "Hello (John) My John (Sally)"
sub("(?s)\(.*?John.*?\)", "", mystr)

rawDescription: Regex conditionally remove text within parens


code:
stream_pull = zmqstream.ZMQStream(socket_pull)
stream_pull.on_recv(getcommand)

stream_sub = zmqstream.ZMQStream(socket_sub)
stream_sub.on_recv(process_message)

rawDescription: ZeroMQ Poller vs Tornados EventLoop

description: ZeroMQ Poller vs Tornados EventLoop


code:
foo = SomeClass()
foo.funcname()

rawDescription: Python use dictionary keys as function names


rawDescription: python group/user management packages

description: Python group/user management packages


code:
@app.route('/start' ,methods=['POST'])
def stop():
    "process done here"
    return Something

rawDescription: Multiple buttons on a flask webapp?

description: Multiple buttons on a flask webapp


code:
self.Angles = range(-90, 100, 15)
self.Texts = [wx.StaticText(panel, -1, '%d' % a) for a in Angles]
self.CCount = [NumCtrl(panel,-1,style=wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB) for a in Angles]
self.UCount = [NumCtrl(panel,-1,style=wx.TE_PROCESS_ENTER|wx.TE_PROCESS_TAB) for a in Angles]

rawDescription: wxpython Multiple wx.NumCtrl into data structure for plotting in matplotlib

description: Wxpython Multiple wx.NumCtrl into data structure for plotting in matplotlib


rawDescription: Python, A string split into many pieces. How many pieces are in there?


rawDescription: Removing word and replacing character in a column of strings


code:
ZERO = datetime.timedelta(0) # same as 00:00

class tzutc(datetime.tzinfo):

    def utcoffset(self, dt):
        return ZERO

    def dst(self, dt):
        return ZERO

rawDescription: Is tzinfo=tzutc() same as +00:00 in python?


code:
actions = [obj() for obj in Action.__subclasses__()]
actions

rawDescription: Python Instantiate All Classes Within a Module


code:
xx = [2, 1]
sorted_xx = sorted(my_list)
print(sorted_xx)
print(xx)

rawDescription: how to sort the date list in python

description: Sort the date list in python


code:
query_yes_no("Is cabbage yummier than cauliflower?")
True
query_yes_no("Is cabbage yummier than cauliflower?", None)
True

rawDescription: python command line yes/no input

description: Python command line yes/no input


rawDescription: Django slice template tag not working with negative indices