code:
def isempty(self):
    return self.root is None

rawDescription: Method isEmpty for binary tree

description: Method isEmpty for binary tree


code:
email.utils.parseaddr("jsmith@example.com")
email.utils.parseaddr("(John Smith) jsmith@example.com")
email.utils.parseaddr("John Smith <jsmith@example.com>")

rawDescription: Parsing "From:" field of an e-mail message in Python


code:
df = using_pandas(filename)
print(df)
#     Stno       DateHourNMT  CD  CD147  CD15  CD18  CD30  CD40  CD69  CD75  \
# 0  76920  1995-12-31-00:00 NaN    NaN   NaN   NaN   NaN   NaN   NaN   NaN
# 1  76920  2005-01-01-00:00  52    NaN   NaN   NaN   NaN   NaN   NaN   NaN

#    ...    X2SDP1  X2TM24  X2TW  X2WHM0  X2WHMAX  X2WL  X2WTHMAX  X2WTP  \
# 0  ...       NaN     NaN   NaN     NaN      3.7   NaN       NaN    NaN
# 1  ...       NaN     NaN   NaN     1.5      2.4  17.4       NaN   12.6

#    X2WTP2  X2WTZ
# 0     NaN    NaN
# 1     5.8    4.9

print(df.dtypes)
# Stno             int64
# DateHourNMT     object
# CD             float64
# ...
# X2WTP2      float64
# X2WTZ       float64
# Length: 122, dtype: object

rawDescription: Set one specific date type for reading in genfromtxt


[A] a x b

k: k f

rawDescription: How to cluster list-of-list by distance condition in Python

description: Cluster list-of-list by distance condition in Python


code:
from datetime import datetime,timedelta
from calendar import monthrange

today = datetime.today()
dt = "04/08/2015"

fut = datetime.strptime(dt, "%d/%m/%Y")
diff = 0
while today <= fut:
    today += timedelta(days=monthrange(today.day,today.month)[1])
    diff += 1
print(diff)
6

rawDescription: How to calculate months left to particular date?

description: Calculate months left to particular date


rawDescription: Accessing list values in a defaultdict(list) type


code:
# Calculate second derivative
ddx_img = np.diff(np.diff(img,1),1)

# Get sliced version of img excluding the first and last columns
# and use mask with ddx elements as "-2" to zeros
img[:,1:-1][ddx_img==-2] = 0

rawDescription: Flipping continuous chunks of 1's up to a certain size in a binary numpy matrix


rawDescription: Euler's pentagonal number function in python


code:
class A:
    @staticmethod
    def abc(cls, *args, **kwargs):
        pass

rawDescription: How to surely refer to global objects in a class during definition?

description: Surely refer to global objects in a class during definition


code:
import psutil
import subprocess
doc = subprocess.Popen(["start", "/WAIT", "file.pdf"], shell=True)   #Stores the open file as doc
doc.poll()                                                           #Shows that the process still exists (will return 0 if the /WAIT argument is excluded from previous line)
psutil.Process(doc.pid).get_children()[0].kill()                     #Kills the process
doc.poll()                                                           #Shows that the process has been killed

rawDescription: How to open an Excel file with Python to display its content?

description: Open an Excel file with Python to display its content


code:
import os
def oldest_file_in_tree(rootfolder, extension=".avi"):
    return min(
        (os.path.join(dirname, filename)
        for dirname, dirnames, filenames in os.walk(rootfolder)
        for filename in filenames
        if filename.endswith(extension)),
        key=lambda fn: os.stat(fn).st_mtime)

rawDescription: Find the oldest file (recursively) in a directory


code: d = dict((k, (repr(v) if isinstance(v, float) else str(v))) for k, v in d.items())

rawDescription: Python - csv.DictWriter() or writerow() rounding my floats?


rawDescription: NLTK: can I add terminal to grammar that is already generated


code:
# iterate over all groups
for key, group in groups:
    print('key: ' + key)
    print('group:')
    print(group)
    print('\n')

rawDescription: Read hierarchical (tree-like) XML into a pandas dataframe, preserving hierarchy


code: d = {'column{}'.format(i): value for i, value in enumerate(targets)}

rawDescription: Python: dict comprehension from a list with key and value being strings?


code:
for k in d:
    d[k.split()[0]] = d.pop(k)
d

rawDescription: Editing keys of a dictionary in Python

description: Editing keys of a dictionary in Python


code: ts = events.resample('1H', how='mean', fill_method='ffill')

rawDescription: How do I get a Pandas TimeSeries for user sessions (using Pandas or Numpy)

description: Get a Pandas TimeSeries for user sessions (using Pandas or Numpy)


code:
from numba import autojit

def filtfunc(a):
    idx = []
    for ii in range(a.shape[0]):
        if (a[ii, 0] > 1):
            idx.append(ii)
            if (len(idx) == 2):
                break
    return a[idx]

jit_filter = autojit(filtfunc)

rawDescription: is it possible to combine a logical and a limit condition in a numpy array slice operator

description: Is it possible to combine a logical and a limit condition in a numpy array slice operator


code:
def powers(n):
    l = []
    for i in range(1, n+1):
        l.append(2**i)
    return l

rawDescription: I need a function that start with a positive integer(n) and returns a list of powers of 2, starting with 2


rawDescription: Fastest way to retrieve newly registered users' instances in Django web app


code:
import re

m = """01-someText151645.txt,Wed Feb 1 16:15:18 2012,1328112918.57801-HalfMeg151646.txt,Wed Feb 1 16:15:18 2012,1328112918.578"""

print(m)

addNewLineBefore = lambda matchObject: "\n" + matchObject.group(0)

print ( re.sub(r'\d{2}-',addNewLineBefore,m) )

rawDescription: Regex for Two Digits and a Hyphen

description: Regex for Two Digits and a Hyphen


code: any(all(c in match for c in x) for x in main)

rawDescription: best way to match these string or list?

description: Match these string or list


code:
list_of_skill_ids = [1, 2]
qry = session.query(Person)
for skill_id in list_of_skill_ids:
    qry = qry.filter(Person.skills.any(Skill.id == skill_id))

print('\n'.join("{}".format(_) for _ in qry.all()))

rawDescription: SQLAlchemy - Query parent by its childer, filter a join to match every children in a list


code:
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']

rawDescription: Reloading submodules in IPython

description: Reloading submodules in IPython


rawDescription: Select all siblings (including text) of comment in xpath


code:
import glob
from shutil import move
from tempfile import NamedTemporaryFile
for fle in glob.iglob("./*.txt"):
    with open(fle) as f,NamedTemporaryFile(dir=".",delete=False) as temp:
        for line in f:
            if line.rstrip() == line_old:
                temp.write(line_new + "\n")
            else:
                temp.write(line)
        move(temp.name,fle)

rawDescription: Open every text file in directory then replace particular line in each


code:
def create_custom_subclass(cls):
    class sub(cls):
        def set_value(self):
            more_set_value()
            super().set_value()
    return sub

AA = create_custom_subclass(A)
a = AA()
a.set_value()

rawDescription: Python, how to flexibly create subclass?

description: Python, how to flexibly create subclass


code: a[..., numpy.newaxis] * b[numpy.newaxis, ...]

rawDescription: Elementwise multiplication of arrays of different shapes in python


rawDescription: Kurtosis,Skewness of a bar graph? - Python


rawDescription: How can I get a list of the symbols in a sympy expression?

description: Get a list of the symbols in a sympy expression


code:
d['combs'] = d.pattern.map(getCombs)
d.combs

rawDescription: Itertools: selecting in pandas based on previous three rows, or previous elements in a list


rawDescription: Loading a config file from operation system independent place in python


code: df1.to_csv("out.csv", encoding="utf8")

rawDescription: Cleaning HTML tables with Pandas

description: Cleaning HTML tables with Pandas


code:
x = "dsjcosnag"
y = "dog"
print(checkYinX(y,x))
print(checkYinX('cat',x))

rawDescription: How to search through a string to see if i can spell a word

description: Search through a string to see if i can spell a word


rawDescription: Is there any function that returns the out edges of a node?


code:
totals = {}
for key in ['month__count', 'recipients__sum', 'unsubscribes__sum', ...]:
    totals[key] = sum(month.get(key, 0) for month in stats)

rawDescription: Find Sum of Columns of Data in Django Like and Excel File


rawDescription: Matrix Approximation and Predicting Timeseries in Python/R with SVD


code:
with open(filename, "rb") as ifile:
    with open(jpegfilename, "wb") as ofile:
        ifile.read(6)
        prev = None
        while True:
            chunk = ifile.read(4096)
            if chunk:
                if prev:
                    ofile.write(prev)
                prev = chunk
            else:
                break
        if prev:
            ofile.write(prev[:-1])

rawDescription: Best way to remove first 6 bytes, and very last byte. Python

description: Remove first 6 bytes, and very last byte. Python


code:
import pandas as pd
import numpy as np
np.random.seed(1)

def setup(regular=True):
    N = 10
    x = np.arange(N)
    a = np.arange(N)
    b = np.arange(N)

    if regular:
        timestamps = np.linspace(0, 120, N)
    else:
        timestamps = np.random.uniform(0, 120, N)

    df = pd.DataFrame({
        'Category': [True] * N + [False] * N,
        'Time': np.hstack((timestamps, timestamps)),
        'Value': np.hstack((a, b))
    })
    return df

def between(a, b):
    def between_percentage(series):
        return float(len(series[(a <= series) & (series < b)])) / float(len(series))
    return between_percentage

def toeach_category(subf):
    def percentage(t):
        return between(1, 3)(
            subf.ix[(t - 60 < subf['Time']) & (subf['Time'] <= t), 'Value'])
    result = subf[['Time']].applymap(percentage)
    return result

df = setup(regular=False)
df.sort(['Category', 'Time'], inplace=True)
df['Result'] = df.groupby(['Category']).apply(toeach_category)
print(df)

rawDescription: Customizing rolling_apply function in Python pandas


code:
SAVE = 'save'
ENTER = 'enter'

def heardEnter():
  i, o, e = select.select([sys.stdin], [], [], 0.0001)
  for s in i:
    if s == sys.stdin:
      input = sys.stdin.readline()
      if 's' in input:
         return SAVE
      else:
         return ENTER
  return None

rawDescription: Two seperate key strokes to save and quit a while loop


code:
LBRACK,RBRACK = map(Suppress, "[]")
qualExpr = Word(alphanums+'$!&|')
qualExprCondition = LBRACK + qualExpr + RBRACK

key_value = Group(key_qs + value + Optional(qualExprCondition("qual")))
def addQualifierToKey(tokens):
    tt = tokens[0]
    if 'qual' in tt:
        tt[0] += '/' + tt.pop(-1)
key_value.setParseAction(addQualifierToKey)

rawDescription: Parsing a CS:GO language file with encoding in Python


code:
lists = [range(10*i, 10*(i+1)) for i in range(4)]
lists

rawDescription: Python: Random from multiple lists, no repeats


code:
def zigzag(seq):
  return seq[::2], seq[1::2]

seq = np.array([1,1,5,1,5,5,1,5,1,1])

result = zigzag(seq)
print(result)

rawDescription: Python : How to vectorize my split function with Numpy


code:
N = len(series)/len(series2007)
series[:] = np.tile(series.loc[dateindex.year == 2007].values, N)

rawDescription: Pandas: Select from date in MultiIndex

description: Pandas: Select from date in MultiIndex


code: w in words

rawDescription: what's a simple way to search a very long text file for a word in python?

description: What's a simple way to search a very long text file for a word in python


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

data1 = np.random.normal(0, 1, 1000)
data2 = np.random.normal(-2, 1.5, 1000)

fig, ax = plt.subplots()

bins = np.linspace(-10, 5, 50)
ax.hist(data1, bins=bins, color='blue', label='Dataset 1',
        alpha=0.5, histtype='stepfilled')
ax.hist(data2, bins=bins, color='green', label='Dataset 2',
        alpha=0.5, histtype='stepfilled')

ax.axvline(data1.mean(), color='blue', linewidth=2)
ax.axvline(data2.mean(), color='green', linewidth=2)

# Add arrows annotating the means:
for dat, xoff in zip([data1, data2], [15, -15]):
    x0 = dat.mean()
    align = 'left' if xoff > 0 else 'right'
    ax.annotate('Mean: {:0.2f}'.format(x0), xy=(x0, 1), xytext=(xoff, 15),
            xycoords=('data', 'axes fraction'), textcoords='offset points',
            horizontalalignment=align, verticalalignment='center',
            arrowprops=dict(arrowstyle='-|>', fc='black', shrinkA=0, shrinkB=0,
                            connectionstyle='angle,angleA=0,angleB=90,rad=10'),
            )

ax.legend(loc='upper left')
ax.margins(0.05)
plt.show()

rawDescription: Average line for bar chart in matplotlib


rawDescription: Python: Eval with undefined variables (2*x+x = 3*x)


rawDescription: Upload files in Google App Engine

description: Upload files in Google App Engine


code:
from django.db import models
from django.contrib.auth.models import User

class Event(models.Model):
    title = models.CharField(max_length=100)
    datetime = models.DateTimeField()

class EventInvite(models.Model):
    event = models.ForeignKey(Event)
    guest = models.ForeignKey(User)
    accepted = models.BooleanField(default=False)
    viewed = models.BooleanField(default=False)

rawDescription: How to get the count of views of a particular event?

description: Get the count of views of a particular event


code:
import argparse
class CapitalisedHelpFormatter(argparse.HelpFormatter):
    def add_usage(self, usage, actions, groups, prefix=None):
        if prefix is None:
            prefix = 'Usage: '
        return super(CapitalisedHelpFormatter, self).add_usage(
            usage, actions, groups, prefix)
parser = argparse.ArgumentParser(add_help=False, formatter_class=CapitalisedHelpFormatter)
parser._positionals.title = 'Positional arguments'
parser._optionals.title = 'Optional arguments'
parser.add_argument('-v', '--version', action='version',
                    version='%(prog)s 1.0', help="Show program's version number and exit.")
parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
                    help='Show this help message and exit.')
print(parser.format_help())

rawDescription: Customize argparse help message

description: Customize argparse help message


code:
start_time = time.time()
# your code
elapsed_time = time.time() - start_time

rawDescription: Measuring elapsed time with the Time module


code:
import numpy
numpy.asarray([1,2,3])
numpy.asarray(numpy.array([2,3]))
numpy.asarray(1)
numpy.asarray((2,3))
numpy.asarray({1:3,2:4})

rawDescription: Python function to accept numpy ndarray or sequence as arguments


code: parser = parse_args(sys.argv[1:])

rawDescription: How do you write tests for the argparse portion of a python module?

description: Write tests for the argparse portion of a python module


code:
for name,line in data_dict.items():
    line["name"]=name
    row=[]
    for feature in featuresq:
        row.append(line.get(feature, float('nan')))
    f.writerow(row)
    FILE.flush()

rawDescription: Python csvwriter only writes up to 132 rows


code:
import signal
class Foo():
    def __init__(self, name):
        self.myname = name
        signal.signal(signal.SIGTERM, self.my_callback)
        self.myqueue = Queue.Queue()

    def my_callback(self):
        logging.error("%s %s %s", self.myname, psutil.blah_getmypid(), len(self.myqueue))

rawDescription: Easy way to tell apart python multiprocessing's OS processes


code: plt.hist(data, bins=np.arange(data.min(), data.max()+1), align='left')

rawDescription: Python: Frequency of occurrences

description: Python: Frequency of occurrences


code:
Aone = df.groupby('A').filter(lambda x: len(x) == 1)
Aone

rawDescription: Only allow one to one mapping between two columns in pandas dataframe


code: latex_show_urls = 'footnote'

rawDescription: Printable PDF output with links as footnotes


code:
for ele in arr:
    if ele != "":
        newArray.append(stripEscape(ele))

for ele in newArray:
    logFile.write("ele: "+ele+'\n')
    if re.match('/table', ele):
        logFile.write("END OF TABLE FOUND")
        logFile.write("\nele: "+ele+'\n')
        break

rawDescription: Remove escape sequences from parsed HTML


code: Counter((item[0], item[1]) for item in a)

rawDescription: Searching for a word pattern in a Python dataset


code:
tables = []
myXML = ET.fromstring(fileAsString)
for table in myXML.findall('./eventTable'):
    transactions = []
    tables.append(transactions)
    for transaction in table.findall('./eventTransaction'):
        info = {}
        for element in table.findall('.//*[value]'):
            info[element.tag] = element.find('./value').text or ''
        coding = transaction.find('./eventCoding')
        if coding is not None:
            for tag in 'eventType', 'eventCode':
                element = coding.find('./%s' % tag)
                if element is not None:
                    info[tag] = element.text or ''
            for index, element in enumerate(coding.findall('./footnoteId')):
                info['eventCoding_FTNT_%d' % index] = element.get('id', '')
        if info:
            transactions.append(info)

rawDescription: How to associate values of tags with label of the tag the using ElementTree in a Pythonic way

description: Associate values of tags with label of the tag the using ElementTree in a Pythonic way


code:
from django.contrib import admin
from django.db import models

def getter_for_related_field(name, admin_order_field=None, short_description=None):
    """
        Create a function that can be attached to a ModelAdmin to use as a list_display field, e.g:
        client__name = getter_for_related_field('client__name', short_description='Client')
    """
    related_names = name.split('__')
    def getter(self, obj):
        for related_name in related_names:
            obj = getattr(obj, related_name)
        return obj
    getter.admin_order_field = admin_order_field or name
    getter.short_description = short_description or related_names[-1].title().replace('_',' ')
    return getter

class RelatedFieldAdminMetaclass(admin.ModelAdmin.__metaclass__):
    """
        Metaclass used by RelatedFieldAdmin to handle fetching of related field values.
        We have to do this as a metaclass because Django checks that list_display fields are supported by the class.
    """
    def __getattr__(self, name):
        if '__' in name:
            getter = getter_for_related_field(name)
            setattr(self, name, getter) # cache so we don't have to do this again
            return getter
        raise AttributeError # let missing attribute be handled normally

class RelatedFieldAdmin(admin.ModelAdmin):
    """
        Version of ModelAdmin that can use related fields in list_display, e.g.:
        list_display = ('address__city', 'address__country__country_code')
    """
    __metaclass__ = RelatedFieldAdminMetaclass
    def queryset(self, request):
        qs = super(RelatedFieldAdmin, self).queryset(request)

        # include all related fields in queryset
        select_related = [field.rsplit('__',1)[0] for field in self.list_display if '__' in field]

        # Include all foreign key fields in queryset.
        # This is based on ChangeList.get_query_set().
        # We have to duplicate it here because select_related() only works once.
        # Can't just use list_select_related because we might have multiple__depth__fields it won't follow.
        model = qs.model
        for field_name in self.list_display:
            try:
                field = model._meta.get_field(field_name)
            except models.FieldDoesNotExist:
                continue
            if isinstance(field.rel, models.ManyToOneRel):
                select_related.append(field_name)

        return qs.select_related(*select_related)

#### USAGE ####
class FooAdmin(RelatedFieldAdmin):
    # these fields will work automatically:
    list_display = ('address__phone','address__country__country_code','address__foo')

    # ... but you can also define them manually if you need to override short_description:
    address__foo = getter_for_related_field('address__foo', short_description='Custom Name')

rawDescription: Get value of field from referenced model displayed in Django Admin site


code:
from d import D, evaluateExpr
from sympy import Matrix
sympy.var(x, y, z, commutative=False)
curl  = Matrix( [[ D(x), D(y), D(z) ]] )
field = Matrix( [[ x**2*y, x*y*z, -x**2*y**2 ]] )
evaluateExpr( curl.cross( field ) )
# [-x*y - 2*x**2*y, 2*x*y**2, -x**2 + y*z]

rawDescription: Differential Operator usable in Matrix form, in Python module Sympy


code:
fmt = '{:16.8E}'
line_fmt = fmt * 5
print(line_fmt.format(*arr[0:5])) # `arr` is the name of your 1d array

rawDescription: Printing a 1d array in 5E16.8 formatting


code: from utils.hasClassIWantToImport import ClassIWant

rawDescription: Python Path Override

description: Python Path Override


rawDescription: Python objects in list as JSON

description: Python objects in list as JSON


code: average = math.ceil(0.5* (float(data[2]) + float(data[3])))

rawDescription: CSV programming read write

description: CSV programming read write


code:
a_player = Player('monty', 0)
a_player.name
a_player.score

rawDescription: Dynamic Table Creation and ORM mapping in SqlAlchemy


code: exec( pyCode, global_namespace, lobaca_namespace );

rawDescription: How to reinitialise an embedded Python interpreter?

description: Reinitialise an embedded Python interpreter


code:
def display_content(request, page_name):
    ...

rawDescription: Django - using regex in urls.py to pass values


rawDescription: python: list manipulation

description: Python: list manipulation


code:
if not d.viewkeys() & {'amount', 'name'}:
    raise ValueError

rawDescription: python: what is best way to check multiple keys exists in a dictionary?

description: Python: what is best way to check multiple keys exists in a dictionary


code: key=lambda line: int(line.split()[1])

rawDescription: merge two files sorted numerically by an integer in each line without reading into memory and without sorting

description: Merge two files sorted numerically by an integer in each line without reading into memory and without sorting


code:
d = {'p1': val1, 'p2': val2}
cur.execute("""
    select *
    from t
    where col1 = %(p1)s and col2 = %(p2)s
    """, d
)

rawDescription: Psycopg2 production appropriate mogrify?

description: Psycopg2 production appropriate mogrify


rawDescription: Multivariate polynomial fit on soccer data


code: # Finally, send all non-media requests to the Django server.

rawDescription: Django-uWSGI-nginx using https

description: Django-uWSGI-nginx using https


code:
plt.xticks(np.arange(0,10), neworder)
plt.yticks(np.arange(0,10), neworder)

rawDescription: 're-sort' / adapt ticks of matshow matrix plot


code:
def f(x):
  return x
f = substitude_args({})(f) # notice the double call

rawDescription: Python Decorator 3.0 and arguments to the decorator


code:
def add(x, y):
    return x+y

def print_two_plus_three():
    result = add(2, 3)
    print(result)

rawDescription: Python 3.3: Functions calling other functions


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
color_cycle = ax._get_lines.color_cycle
# or ax._get_lines.prop_cycle on version >= 1.5
# Note that prop_cycle cycles over dicts, so you'll want next(cycle)['color']

rawDescription: Get matplotlib color cycle state

description: Get matplotlib color cycle state


rawDescription: How to change multiprocessing shared array size?

description: Change multiprocessing shared array size


code:
def pumpWx():
    global app
    def processor():
        app.Yield(True)
    while 1:
        time.sleep(0.01)
        utils.executeDeferred( processor )

def initializePumpThread():
    global pumpedThread
    global app
    if pumpedThread == None:
        app = wx.App(False)
        pumpedThread = threading.Thread(target = pumpWx, args = ())
        pumpedThread.start()

rawDescription: Using external GUI libraries to make user interfaces in Autodesk Maya


code:
import pprint
pprint.pprint([[i.match(j) for j in targetLines] for i in matchLines ])

rawDescription: most concise way to operate over two lists, returning list of lists in python

description: Most concise way to operate over two lists, returning list of lists in python


code:
# myproject/account/admin.py

class StaffUserAdmin(models.ModelAdmin):
    ...
    def changelist_view(self, request, extra_context=None):
        groups = Group.objects.exclude(name__in=['Press',]).values_list('name')
        extra_context = {
            'groups': [x[0] for x in groups],
        }
        return super(StaffUserAdmin, self).changelist_view(request,
            extra_context=extra_context)

rawDescription: Possible to limit filters ManyToMany/Foreign Key in Django admin for a model where the relationship is defined on the other model?


code:
from itertools import groupby
from collections import defaultdict

d = defaultdict(lambda: defaultdict(list))
with open("file.txt") as f:
    for k, val in groupby(f, lambda x: x.strip() != ""):
        if k:
            k, alb, songs = next(val),next(val), val
            d[k.rstrip()][alb.rstrip()] = list(map(str.rstrip, songs))

from pprint import pprint as pp

pp(d)

{'Bob Dylan': {'1966 Blonde on Blonde': ['-Rainy Day Women #12 & 35',
                                         '-Pledging My Time',
                                         '-Visions of Johanna',
                                         '-One of Us Must Know (Sooner or '
                                         'Later)',
                                         '-I Want You',
                                         '-Stuck Inside of Mobile with the '
                                         'Memphis Blues Again',
                                         '-Leopard-Skin Pill-Box Hat',
                                         '-Just Like a Woman',
                                         '-Most Likely You Go Your Way '
                                         "(And I'll Go Mine)",
                                         '-Temporary Like Achilles',
                                         '-Absolutely Sweet Marie',
                                         '-4th Time Around',
                                         '-Obviously 5 Believers',
                                         '-Sad Eyed Lady of the Lowlands']},
 'Led Zeppelin': {'1969 II': ['-Whole Lotta Love',
                              '-What Is and What Should Never Be',
                              '-The Lemon Song',
                              '-Thank You',
                              '-Heartbreaker',
                              "-Living Loving Maid (She's Just a Woman)",
                              '-Ramble On',
                              '-Moby Dick',
                              '-Bring It on Home'],
                  '1979 In Through the Outdoor': ['-In the Evening',
                                                  '-South Bound Saurez',
                                                  '-Fool in the Rain',
                                                  '-Hot Dog',
                                                  '-Carouselambra',
                                                  '-All My Love',
                                                  "-I'm Gonna Crawl"]}}

rawDescription: Append items to dictionary Python

description: Append items to dictionary Python


code:
from operator import itemgetter
from itertools import groupby, imap

def unique_justseen(iterable, key=None):
    "List unique elements, preserving order. Remember only the element just seen."
    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
    # unique_justseen('ABBCcAD', str.lower) --> A B C A D
    return imap(next, imap(itemgetter(1), groupby(iterable, key)))

rawDescription: Removing duplicate elements from a Python list containing unhashable elements while preserving order?


code:
def findCaller(self):
    """
    Find the stack frame of the caller so that we can note the source
    file name, line number and function name.
    """
    f = currentframe()
    #On some versions of IronPython, currentframe() returns None if
    #IronPython isn't run with -X:Frames.
    if f is not None:
        f = f.f_back
    rv = "(unknown file)", 0, "(unknown function)"
    while hasattr(f, "f_code"):
        co = f.f_code
        filename = os.path.normcase(co.co_filename)
        if filename == _srcfile:
            f = f.f_back
            continue
        rv = (co.co_filename, f.f_lineno, co.co_name)
        break
    return rv

rawDescription: How get the called function to loggin with decorators?


rawDescription: How to unset EOL option in TCP packet with scapy

description: Unset EOL option in TCP packet with scapy


code:
import pickle

aList = ['useless', 'info']
bList = [1000,5000]

aFile=open('aFile.dat', 'w')
aFile.write(pickle.dumps({"aList":aList,"bList":bList}))
aFile.close()

rawDescription: How do I write two lists to a dat file using pickle?

description: Write two lists to a dat file using pickle


code: return totalSeconds

rawDescription: Define a python function time2sec with three optional keyword arguments hour minute and second


code:
for ln in input_text.splitlines():
    values = ln.split()
    y.append(values[-1])
    d = dict(zip(features, values[:-1]))
    samples.append(d)

rawDescription: handling too many categorical features using scikit-learn

description: Handling too many categorical features using scikit-learn


code:
import subprocess

hosts_file = open("hosts.txt","r")
lines = hosts_file.readlines()
hosts_file.close()

for line in lines:
    ping = subprocess.Popen(["ping", "-n", "3",line.strip()], stdout=subprocess.PIPE, stderr=subprocess.POPEN)
    with open('PingResults.txt', 'ab') as fh:
        for line in ping.stdout.readlines():
            fh.write(line)
    ping.stdout.close()

rawDescription: Python console and text output from Ping including \n\r


code:
data = []
temp = []
for sn in ['/home/pi/sensoren/sensor{:d}'.format(i) for i in range(1,11)]:
                                                            #xrange if Python 2.x
    with open(sn) as f:
        data.append(f.read())
# the data list now contains all sensor data
for num, s in enumerate(data):
    # check for CRC
    d = s.strip()
    if d.startswith("YES"):
        t = d.split("t=")
        # populate temp list
        if t[1] == '-62':
            temp.append("00")
        else:
            temp.append(t[1])

rawDescription: Python: threaded reading from multiple files


rawDescription: For Loop Count Single Word String Not Work?


code:
class Rectangle():
    x = random.randrange(0, 701)
    y = random.randrange(0, 501)
    width = random.randrange(20,71)
    height = random.randrange(20,71)
    change_x = random.randrange(-3,4)
    change_y = random.randrange(-3,4)
    def move(self):
        self.x += self.change_x
        self.y += self.change_y
    def draw(self):
        pygame.draw.rect(screen, green, [self.x,self.y, self.width, self.height], 0)

rawDescription: List of 10 rectangles, meant to draw every one, only draws one


code:
import pickle
import cPickle
import marshal
import json

def maked(N=5400):
  d = {}
  for x in range(N):
    k = 'key%d' % x
    v = [x] * 5
    d[k] = v
  return d
d = maked()

def marsh():
  return marshal.dumps(d)

def pick():
  return pickle.dumps(d)

def pick1():
  return pickle.dumps(d, -1)

def cpick():
  return cPickle.dumps(d)

def cpick1():
  return cPickle.dumps(d, -1)

def jso():
  return json.dumps(d)

def rep():
  return repr(d)

rawDescription: Fast JSON serialization (and comparison with Pickle) for cluster computing in Python?


rawDescription: Median of a list with NaN values removed, in python


code:
a = np.repeat((np.arange(3000) + 1)[:, None], 3, 1)
b = a + 1

dist = np.linalg.norm(a - b, axis=1)

rawDescription: Euclidean distance in Python

description: Euclidean distance in Python


rawDescription: numpy 2d array (coordinates) need to assign into 3D array, to some particular bin

description: Numpy 2d array (coordinates) need to assign into 3D array, to some particular bin


code:
#!/usr/bin/env python
from subprocess import Popen, PIPE

pad = Popen(["sox", "input.wav", "-t", "wav", "-", "pad", "0.0", "3.0"],
            stdout=PIPE)
trim = Popen(['sox', '-t', 'wav', '-', 'out.wav', 'trim', '0.0', '3.0'],
             stdin=pad.stdout)
pad.stdout.close() # notify pad on write if trim dies prematurely
pipestatus = [p.wait() for p in [pad, trim]]

rawDescription: Wait for external program to finish writing to file


code:
variable = func.unzip(ifile, instances)
func.changecs(variable)

rawDescription: How to use a list in other function?

description: Use a list in other function


rawDescription: the Html and the soup result is way different

description: The Html and the soup result is way different


code:
def fun(a, axis, state):
    return numpy.rollaxis(a, axis)[state]

rawDescription: numpy index on a variable axis

description: Numpy index on a variable axis


code:
spinner = itertools.cycle("|/~\\")
while not t.ready():
    sys.stdout.write("\r%s: still analyzing %s" % (time.ctime(), next(spinner)))
    sys.stdout.flush()
    time.sleep(.5)

rawDescription: Show function status using Python standard library


rawDescription: How to get byte offset in a file in python

description: Get byte offset in a file in python


rawDescription: mongo - find items who at least match an array of values

description: Mongo - find items who at least match an array of values


code: [list(i) for i in zip(*myList)]

rawDescription: How to change the major order of lists in python?

description: Change the major order of lists in python


code:
from Tkinter import *

root = Tk()
content = Label(root, padx=30,pady=30,background = "white")
content.grid(column=0, row=0, sticky=(N, S, E, W))
title_frame = Label(content, borderwidth=5, relief="sunken", padx=30,pady=30,background = "white")
title_frame.grid(column=0, row=0, sticky=(N))
body_frame = Label(content, borderwidth=5, relief="sunken", padx=30,pady=30,background = "white")
body_frame.grid(column=0, row=1, sticky=(N,W,E))
config_frame = Label(content, borderwidth=5, relief="sunken", padx=30,pady=30,background = "white")
config_frame.grid(column=0, row=2, sticky=(N, W))
button_frame = Label(content, borderwidth=5, relief="sunken", padx=30,pady=30,background = "orange")
button_frame.grid(column=1, row=2, sticky=(S, E))

title_entry = Entry(title_frame, background="lightblue")
title_entry.grid(column=1, row=0)
title_label = Label(title_frame,text = "Page title",background = "white")
title_label.grid(column=0,row=0)

body_text = Text(body_frame, background="lightblue")
body_text.grid(column=1,row=0)
body_label = Label(body_frame,text = "Page body content",background = "white")
body_label.grid(column=0, row=0)

header_entry = Entry(config_frame, background="lightblue")
header_entry.grid(column=1, row=0)
header_label = Label(config_frame,text = "header",background = "white")
header_label.grid(column=0,row=0)

footer_entry = Entry(config_frame, background="lightblue")
footer_entry.grid(column=1, row=1)
footer_label = Label(config_frame,text = "footer",background = "white")
footer_label.grid(column=0,row=1)

postBtn = Button(button_frame, text="Post")
postBtn.grid(row=0, column=0)
exitBtn = Button(button_frame, text="Exit")
exitBtn.grid(row=0, column=1)

rawDescription: Issues with layout management in Tkinter Python application


code:
class DiscreteSlider(Slider):
    """A matplotlib slider widget with discrete steps."""
    def __init__(self, *args, **kwargs):
        """Identical to Slider.__init__, except for the "increment" kwarg.
        "increment" specifies the step size that the slider will be discritized
        to."""
        self.inc = kwargs.pop('increment', 0.5)
        Slider.__init__(self, *args, **kwargs)

    def set_val(self, val):
        discrete_val = int(val / self.inc) * self.inc
        # We can't just call Slider.set_val(self, discrete_val), because this
        # will prevent the slider from updating properly (it will get stuck at
        # the first step and not "slide"). Instead, we'll keep track of the
        # the continuous value as self.val and pass in the discrete value to
        # everything else.
        xy = self.poly.xy
        xy[2] = discrete_val, 1
        xy[3] = discrete_val, 0
        self.poly.xy = xy
        self.valtext.set_text(self.valfmt % discrete_val)
        if self.drawon:
            self.ax.figure.canvas.draw()
        self.val = val
        if not self.eventson:
            return
        for cid, func in self.observers.iteritems():
            func(discrete_val)

rawDescription: Can I make matplotlib sliders more discrete?

description: Make matplotlib sliders more discrete


code:
DATABASES = {
     'default': {
         'NAME': 'db.sqlite3',
         'ENGINE': 'django.db.backends.sqlite3',
     },
     'train': {
         'NAME': 'train.db',
         'ENGINE': 'django.db.backends.sqlite3',
     },
     'bus': {
         'NAME': 'bus.db',
         'ENGINE': 'django.db.backends.sqlite3',
     },
}

DATABASE_ROUTERS = [ 'yourapp.DatabaseAppsRouter']

DATABASE_APPS_MAPPING = {'train': 'train', 'bus': 'bus'}

rawDescription: Single django app to use multiple sqlite3 files for database


code: zip(*i)

rawDescription: Numpy array with position

description: Numpy array with position


rawDescription: Index of element in Numpy array

description: Index of element in Numpy array


code:
spectra_dict = dict(((str(spectraItem[0]), str(spectraItem[25])), spectraItem) for spectraItem in spectraFinal)
returnList = []
for r120item in r120Final:
    key = (r120item[2].strip(), r120item[10])
    if key not in spectra_dict:
        returnList.append(r120item)
    else:
        return_item = some_function_of(r120item, spectra_dict[key])
        returnList.append(return_item)

rawDescription: Nested for loop to search 2 lists

description: Nested for loop to search 2 lists


code: rdd1.map(lambda tup: (tup[0], -abs(tup[1])) if tup[0] < 0 else (tup[0], abs(tup[1])))

rawDescription: modify sign of numbers in two different columns of an RDD in PySpark

description: Modify sign of numbers in two different columns of an RDD in PySpark


code: return np.where(np.logical_or(f < min_freq, f > max_freq), sig, 0)

rawDescription: How to convert complex numbers back into "normal" numbers after performing FFT

description: Convert complex numbers back into "normal" numbers after performing FFT


code:
x = list('ciaobelu')
r = range(len(x))
r.sort(key=x.__getitem__)
r

rawDescription: undo or reverse argsort(), python

description: Undo or reverse argsort(), python


code:
ServerDict = {
'list1': {
'IP_' : '@IPADDR1',
'Username_' : '@USER',
'Password_' : '@PASSWD',
'dirlocation' : '@DIR'
},
'list2': {
'IP_' : '@IPADDR2',
'Username_' : '@USER',
'Password_' : '@PASSWD',
'dirlocation' : '@DIR'
}
}

rawDescription: Python - Is it possible to have a dictionary in a list?


code:
user_rel_ids = fields.Many2many(comodel_name='course',
                        relation='user_course_rel',
                        column1='user_id',
                        column2='course_id')

rawDescription: Filling Many2many field (odoo 8)

description: Filling Many2many field (odoo 8)


code: labels = dict( ((i, j), i * 10 + j) for i, j in G.nodes() )

rawDescription: Remove rotation effect when drawing a square grid of MxM nodes in networkx using grid_2d_graph


code:
x = 'Hello world'
x.replace('l', '@')
help(str.replace)

rawDescription: How to I select individual characters out of a sting and replace them with another [Python 3]?


code: arr[(arr == 0).sum(axis=1).argsort()]

rawDescription: NumPy sort matrix rows by number of non-zero entries


code:
size_count = size_count.reset_index()
size_count.columns = ['level', 'community size', 'number of communities']

rawDescription: How to dynamically update a plot in a loop?

description: Dynamically update a plot in a loop


code:
from re import findall
findall('\[([^\]]*)\]', '[abc] [def] [zzz]')

rawDescription: String split on specific characters

description: String split on specific characters


code:
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)

rawDescription: How do you you run a Twisted application via Python (instead of via Twisted)?

description: You run a Twisted application via Python (instead of via Twisted)


code:
g = globals()
for i in range(1, 5):
    g['depth_{0}'.format(i)] = []

depth_1
depth_2
depth_3
depth_4
depth_5

rawDescription: dynamically declare/create lists in python

description: Dynamically declare/create lists in python


code:
with open('nameOfYourSaveFile', 'w') as saveFile:
    for i in xrange(10):
         saveFile.write(name[i] + str(phoneNumber[i]) + email[i] + "\n")

rawDescription: Python- Saving Results to a File and Recalling Them


code:
for k in xrange(2, len(lists)):
    for comb in itertools.combinations(cost_lists, k):
        for group in itertools.product(*comb):
            if sum(g[0] for g in group) <= threshold:
                cost_global.append(group)

rawDescription: Find the permutations that sums to the three smallest numbers


code:
def words(lines):
    for line in lines:
        for word in line.split():
            yield word

rawDescription: manipulating and searching within large files in python

description: Manipulating and searching within large files in python


rawDescription: Remove non-GtkListBoxRow parent from GtkListBox


code:
def standardizeCellWise(matrix,mu_cell,sigma_cell):
    matrix_cut = matrix[:,0:channels,:,:]
    matrix_cut = (matrix_cut - mu_cell[None,:])/sigma_cell[None,:]
    mask = ~np.isfinite(matrix_cut)
    matrix_cut[mask] = 0
    matrix[:,0:channels,:,:] = matrix_cut
    return matrix

rawDescription: Per-cell standardization efficiently in NumPy


code:
import dateutil.rrule as dr
import dateutil.parser as dp
import dateutil.relativedelta as drel

start=dp.parse("19/02/2010")   # Third Friday in Feb 2010

rawDescription: Generating recurring dates using python?

description: Generating recurring dates using python


code:
from sqlalchemy.orm import validates

class Entry(Base):
    __table__ = ...

    @validates('entry')
    def _set_entry(self, key, value):
        self.cached_entry = markdown(value)
        return value

rawDescription: Auto updating properties in sqlalchemy

description: Auto updating properties in sqlalchemy


code:
sql = 'UPDATE aprtable SET apr = ? WHERE neighborhood = ? and income = ? and risk_factor = ?'
args = [0.125, 'Allston', 25000, 5]
cursor.execute(sql, args)

rawDescription: Dynamically fill a python dictionary

description: Dynamically fill a python dictionary


code:
import os

def gallery(request):
    path="C:\\somedirectory"  # insert the path to your directory
    img_list =os.listdir(path)
    return render_to_response('gallery.html', {'images': img_list})

rawDescription: Django: Auto-generating a list of files in a directory


code:
{'im ': True, 'm s': True, 'jim': True, 'ilv': True, ' si': True, 'lva': True, 'sil': True}
False

rawDescription: Creating a feature dictionary for Python machine learning (naive bayes) algorithm


rawDescription: Log Scale Matplotlib PatchCollection Colors


code:
from zipstream import ZipStream

class Zipit:
  def __init__( self, path):
    self.it = iter(ZipStream(path,compression=0))
    self.next_chunk = ""
    self.length = -1
    self.path = path
    self.__is_zipit__=''
  @property
  def size(self):
    if self.length < 0:
      self.length = 0
      zip_object = ZipStream(self.path,compression=0)
      for data in zip_object:
        self.length += len(data)
    return self.length

  def growChunk( self ):
    self.next_chunk = self.next_chunk + self.it.next()
  def read( self, n ):
    if self.next_chunk == None:
      return None
    try:
      while len(self.next_chunk)<n:
        self.growChunk()
      rv = self.next_chunk[:n]
      self.next_chunk = self.next_chunk[n:]
      return rv
    except StopIteration:
      rv = self.next_chunk
      self.next_chunk = None
      return rv

rawDescription: Generator for multipart form data with python requests


code: [h, v] = testLines;

rawDescription: Algorithm to group sets of points together that follow a direction


code: THH = np.bitwise_and(a, 2**12 - 1)

rawDescription: python array of decimals into binary numbers efficienty

description: Python array of decimals into binary numbers efficienty


code:
class MyFloat(float):
    def __format__(self, format_string):
        if format_string.endswith('z'):  # 'fz' is format sting for floats without leading the zero
            format_string = format_string[:-1]
            remove_leading_zero = True
        else:
            remove_leading_zero = False

        string = super(MyFloat, self).__format__(format_string)
        return _remove_leading_zero(self, string) if remove_leading_zero else string
        # `_remove_leading_zero` function is same as in the first example

rawDescription: Print floating point values without leading zero


code: return eval(attrname)

rawDescription: Hide deprecated methods from tab completion


rawDescription: IronPython scripts execution from C# code


rawDescription: Zip lists of tuples

description: Zip lists of tuples


rawDescription: Verifying counter falls in particular range or not in a packet capture


rawDescription: How to save and load an array of complex numbers using numpy.savetxt?

description: Save and load an array of complex numbers using numpy.savetxt


code:
data1 = []
with open(raw_input("Which is list1?")) as handle:
    data1.extend(l.rstrip() for l in handle)
# ...

rawDescription: Simple Nested loop with Python

description: Simple Nested loop with Python


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup("""
<html>
    <head>
    </head>
    <body>
        <from>The first `from` tag</from>
        <from>The second `from` tag</from>
        <from>The third `from` tag</from>
    </body>
</html>""", "html.parser")
soup.find('from').string
soup.find_all('from')
soup.find_all('from')[2].string

rawDescription: Python; BeautifulSoup and inbuilt Functions


code:
ab = a[:,None,:] - b
out = np.einsum('ijk,ijk->ij',ab,ab)

rawDescription: NumPy Broadcasting: Calculating sum of squared differences between two arrays


code:
def define_var(dictionary, entry, counter):
    d_name = next(k for k, v in globals().items() if v  is  dictionary)
    for i in range(counter):
        print("reason%d = %s['%s_%d']" % (i + 1, d_name, entry, counter))

print(define_var(result_dict, 'start', 3))

reason1 = result_dict['start_3']
reason2 = result_dict['start_3']
reason3 = result_dict['start_3']

rawDescription: How to pass the name of a dictionary

description: Pass the name of a dictionary


code: #! /usr/bin/env python3

rawDescription: Using subprocess with script using another version


code:
import boto
c =boto.connect_s3()
fp = open('myfiletoupload.txt')
content_length = len(fp.read())
c.generate_url(300, 'PUT', 'test-1332789015', 'foobar', headers={'Content-Length': str(content_length)}, force_http=True)

rawDescription: How to generate a temporary url to upload file to Amazon S3 with boto library?

description: Generate a temporary url to upload file to Amazon S3 with boto library


code:
with open("oplist.txt") as f:
    temp_list = [x.rstrip() for x in f]
    name = raw_input("What name would you like to remove: ")
    temp_list.remove(name) # just pass name no need for intermediate variable
    with open("oplist.txt", "w") as target: # reopen with w to overwrite
        for line in temp_list: # iterate over updated list
             target.write("{}\n".format(line)) # we need to add back in the new line
                                                # chars we stripped or all words will be on one line

rawDescription: Removing data from a list from a raw_input variable


code:
task_map = {
    'upload': UploadDirectory,
    'something': SomethingElse,
}

rawDescription: Mapping a returned string to a specific function


code:
import sys
import yaml

from yaml.representer import Representer
from yaml.dumper import Dumper
from yaml.emitter import Emitter
from yaml.serializer import Serializer
from yaml.resolver import Resolver

yaml_str = """\
attrs:
  first:
  second: value2
"""

class MyRepresenter(Representer):
    def represent_none(self, data):
        return self.represent_scalar(u'tag:yaml.org,2002:null',
                                 u'')

class MyDumper(Emitter, Serializer, MyRepresenter, Resolver):
    def __init__(self, stream,
            default_style=None, default_flow_style=None,
            canonical=None, indent=None, width=None,
            allow_unicode=None, line_break=None,
            encoding=None, explicit_start=None, explicit_end=None,
            version=None, tags=None):
        Emitter.__init__(self, stream, canonical=canonical,
                indent=indent, width=width,
                allow_unicode=allow_unicode, line_break=line_break)
        Serializer.__init__(self, encoding=encoding,
                explicit_start=explicit_start, explicit_end=explicit_end,
                version=version, tags=tags)
        MyRepresenter.__init__(self, default_style=default_style,
                default_flow_style=default_flow_style)
        Resolver.__init__(self)

MyRepresenter.add_representer(type(None),
                              MyRepresenter.represent_none)

data = yaml.load(yaml_str)
yaml.dump(data, stream=sys.stdout, Dumper=MyDumper, default_flow_style=False)

rawDescription: Can I dump blank instead of null in yaml/pyyaml?

description: Dump blank instead of null in yaml/pyyaml


code:
def wp2_bubble(blist):
    cmpcount, swapcount = 0, 0
    n = len(blist)
    while True:
        swapped = False
        for i in range(1, n):
            cmpcount += 1
            if blist[i-1] > blist[i]:
                swapcount += 1
                blist[i-1], blist[i] = blist[i], blist[i-1]
                swapped = True
        n -= 1
        if not swapped:
            break
    return blist, cmpcount, swapcount

import random
alist = [random.randrange(100) for _ in range(100)]
bb, cb, sb = bogo_bubble(alist[:])
b1, c1, s1 = wp1_bubble(alist[:])
b2, c2, s2 = wp2_bubble(alist[:])
assert bb == b1 == b2
print('bogo_bubble: {} cmp, {} swap'.format(cb, sb))
print('wp1_bubble : {} cmp, {} swap'.format(c1, s1))
print('wp2_bubble : {} cmp, {} swap'.format(c2, s2))

rawDescription: Is this most efficient to bubble sort a list in python?


code:
def bincount_vectorized(A):

    n3 = A.shape[1]
    nrows = y.max()+1
    id = y[:,None] + nrows*np.arange(n3)
    A[:nrows] -= np.bincount(id.ravel(),B.ravel()).reshape(n3,nrows).T
    return A

rawDescription: Vectorize addition into array indexed by another array


rawDescription: Dealing with floating points: With numpy python in particular


code:
from subprocess import call, STDOUT

rc = call("./generate-output", stdout=sck, stderr=STDOUT)

rawDescription: how to call stdout.write from subprocess.Popen?

description: Call stdout.write from subprocess.Popen


rawDescription: Change set of indices

description: Change set of indices


code:
a = range(3)
b = a[:]                  # make b a new copy of a
b.append(3)
a, b                      # a is left unchanged

rawDescription: Python objects confusion: a=b, modify b and a changes!


code:
# visualize the references in your bad objects
objgraph.show_refs(your_bad_object, filename='your_bad_object.png')

rawDescription: How to get a python function's dependencies for pickling?

description: Get a python function's dependencies for pickling


code:
# find starting byte of last codepoint
pos = len(msg) - 1
while pos > -1 and ord(msg[pos]) & 0xC0 == 0x80:
    # character at pos is a continuation byte (bit 7 set, bit 6 not)
    pos -= 1
msg = msg[:pos]

rawDescription: How to remove last utf8 char of a python string

description: Remove last utf8 char of a python string


code:
linetemp = '  12     27   435'
nr = [int(i) for i in linetemp.split()]
nr

rawDescription: How to get three integers from a specific line in a file with Python?

description: Get three integers from a specific line in a file with Python


rawDescription: Call a list variable from a for loop in Python


rawDescription: PyQt or PySide: QTextEdit deselect all

description: PyQt or PySide: QTextEdit deselect all


code:
resp, items = m.search(None, '(FROM "EIA_eLists@eia.gov")')
items = items[0].split()

my_msg = [] # store relevant msgs here in please
msg_cnt = 0
break_ = False

rawDescription: Extract information from Gmail with Python


code:
import itertools as IT
import csv

def int_wrapper(mydata):
    for v in mydata:
        yield map(int, v)

with open('data', 'rU') as o:
    mydata = csv.reader(o)
    header = next(mydata)
    reader = int_wrapper(mydata)
    for key, group in IT.groupby(reader, lambda row: (row[0]-1)//25+1):
        year = key*25
        total = sum(row[1] for row in group)
        print(year, total)

rawDescription: Group rows in a CSV by blocks of 25

description: Group rows in a CSV by blocks of 25


rawDescription: Pass bash file list to python CLI function


code:
import re
rep = re.compile('\$limit_value =.*;')

with open('/path/to/file/index.php', 'r+') as php:
    data = rep.sub('$limit_value = 5;', php.read())
    php.seek(0) # Places the text "Input" in the file at the beginning of the file
    php.write(data)
    php.truncate() # This will cause all trailing data to be flushed.
                            # reason for doing this is because your default value of `$limit_value` might
                            # make your total content written back to the file shorter of that was writter before.
                            # there for there might be trailing data we need to truncate away.

rawDescription: Changing the value in a file dynamically from python


code:
class Permalink(models.Model):
    key = models.CharField(primary_key = True, max_length = 8)
    refersTo = models.ForeignKey(MyContentModel, unique = True)

rawDescription: How to generate shareable links in django? (similar to pastebin links)

description: Generate shareable links in django? (similar to pastebin links)


code: y = np.linspace(-2, -3, 6)

rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


rawDescription: How to test a project that need keyboard input with travis-ci.org?

description: Test a project that need keyboard input with travis-ci.org


code:
def Hamming_check_0_or_1(genome, posn, sequence):
    errors = 0
    for i in xrange(25):
        if genome[posn+i] != sequence[i]:
            errors += 1
            if errors >= 2:
                return errors
    return errors

rawDescription: Search for string allowing for one mismatch in any location of the string


rawDescription: calculate total events in month using pandas

description: Calculate total events in month using pandas


rawDescription: Dict into Dict Python

description: Dict into Dict Python


code:
class Book(PostponedOpMixin):
    ...
    authors = models.ManyToManyField(Author)
    ...

instance = Book()
instance.title = "Romeo and Juliet"
instance.postpone('authors.add', shakespeare)
...

# and some time later:
instance.save()

rawDescription: Initializing objects belonging to ManyToManyField from data in-memory


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

data = [np.random.normal(0, std, 1000) for std in range(1, 6)]
plt.boxplot(data, notch=True, patch_artist=True)

plt.show()

rawDescription: python matplotlib filled boxplots

description: Python matplotlib filled boxplots


code:
from operator import itemgetter
tmp1 = sorted(mydictList, key=itemgetter('b'))

rawDescription: Removing dictionaries from a list on the basis of duplicate value of key


code:
res['duration'] = res['exit'] - res['load']
res

rawDescription: validate rows before computing values using python/pandas DataFrame

description: Validate rows before computing values using python/pandas DataFrame


rawDescription: Reduce resolution of array through summation


code:
from django import template

register = template.Library()

@register.simple_tag
def active(request, pattern):
    path = request.path
    if path == pattern:
        return 'active'
    return ''

rawDescription: Compare request.path with a reversed url in Django template


code: [i for i in s.split() if i.isdigit()]

rawDescription: Extract a digit from a unicode string

description: Extract a digit from a unicode string


rawDescription: Dynamically escape % sign and brackets { } in a string


rawDescription: create new rank column in python , or use sort and reset index rank - how to?

description: Create new rank column in python , or use sort and reset index rank - how to


rawDescription: python create empty object of arbitrary type?

description: Python create empty object of arbitrary type


code:
class Photo(db.Model):
 imageblob = db.BlobProperty()

rawDescription: Python app engine: how to save a image?

description: Python app engine: how to save a image


code:
pname = input("What is your name")
correct = input("What is your score")
SCORE_FILENAME  = "Class1.txt"
MAX_SCORES = 3

try: scoresFile = open('Class1.txt', "r+")
except IOError: scoresFile = open('Class1.txt', "w+") # File not exists
actualScoresTable = []
for line in scoresFile:
        tmp = line.strip().replace("\n","").split(",")

        for index, score in enumerate(tmp[1:]):
            tmp[1+index] = str(score)

        actualScoresTable.append({
                                "name": tmp[0],
                                "scores": tmp[1:],
                                })
scoresFile.close()

new = True
for index, record in enumerate( actualScoresTable ):
    if record["name"] == pname:
        actualScoresTable[index]["scores"].append(correct)
    if len(record["scores"]) > MAX_SCORES:
        actualScoresTable[index]["scores"].pop(0) # OR del actualScoresTable[index]["scores"][0]
    new = False
    break
if new:
    actualScoresTable.append({
                            "name": pname,
                            "scores": [correct],
                            })

scoresFile = open(SCORE_FILENAME, "w+") # Truncating file (write all again)
for record in actualScoresTable:
    for index, score in enumerate(record["scores"]):
        record["scores"][index] = str(score)
        scoresFile.write( "%s,%s\n" % (record["name"],(record["scores"][index])) )
scoresFile.close()

rawDescription: how to change how the code writes the data in my file

description: Change how the code writes the data in my file


code:
def chunks(l, n):
    n = max(1, n)
    return [l[i:i + n] for i in range(0, len(l), n)]

new_list = chunks(tuples, 1000)

rawDescription: how to transform pandas dataframe for insertion via executemany() statement?

description: Transform pandas dataframe for insertion via executemany() statement


code: bin_edges = [np.r_[-np.inf, edge, np.inf] for edge in bin_edges]

rawDescription: How to find bin edges of given bin number returned by scipy.stats.binned_statistic_dd()?

description: Find bin edges of given bin number returned by scipy.stats.binned_statistic_dd()


rawDescription: Assign unique id to columns pandas data frame


code:
df[df != 0.].dropna(axis=1) # to remove the columns with 0
df[df != 0.].dropna(axis=0) # to remove the rows with 0

rawDescription: Filter out rows/columns with zero values in MultiIndex dataframe


code: [f.group(1) for f in re.finditer('"(.+?)"', input)]

rawDescription: Python split string on quotes

description: Python split string on quotes


code:
def get_vars(s):
    d = {}
    while True:
        try:
            s % d
        except KeyError as exc:
            # exc.args[0] contains the name of the key that was not found;
            # 0 is used because it appears to work with all types of placeholders.
            d[exc.args[0]] = 0
        else:
            break
    return d.keys()

rawDescription: Python: extract all placeholders from format string


rawDescription: How simple list functions could be implemented in Python


code:
needed_positions = set(["PG", "SG", "SF", "C"])
results = {}
for name, pos, cost, pts in listOfPlayers:
    if not needed_positions:
        #all spots filled
        break
    if pos in results:
        #this position already filled
        continue
    results[pos] = (name, pos, cost, pts)
    needed_positions.remove(pos)

rawDescription: Python Sorting lists by value

description: Python Sorting lists by value


rawDescription: From Matlab to Python - Solve function

description: From Matlab to Python - Solve function


code:
for x in data:
    print(x, end=' ')

rawDescription: python: printing horizontally rather than current default printing

description: Python: printing horizontally rather than current default printing


code:
from itertools import zip_longest
serial_result = map(lambda x:(x[0]**2,x[1]**3), zip_longest(range(20), range(10),fillvalue=1))

rawDescription: Is it possible to include mutiple equations in a lambda function


code:
sample = """IO_SET(BLOCK, key1, function(1+2,3, val11), key2, val2, key3, (3U)+cVAL3);"""

from pyparsing import *

SEMI,LPAREN,RPAREN,COMMA = map(Suppress,";(),")
#identifier = Combine(Optional(Word(nums+'_')) + Word(alphas, alphanums+'_'))
identifier = Word(alphas, alphanums+'_')
#integer= Combine(Optional('-') + Word(nums))
integer = Regex(r"[+-]?\d+[Uu]?[Ll]?")
realnum = Combine(integer.copy() + '.' + Optional(Word(nums)))

fn_call1 = Forward()
fn_call2 = Forward()
# this order is *critical*
value = realnum | fn_call1 | fn_call2 | identifier | integer

expr = infixNotation(value,
            [
            (oneOf('* /'), 2, opAssoc.LEFT),
            (oneOf('+ -'), 2, opAssoc.LEFT),
            ])
key_value = Group(identifier + COMMA + expr)
kv_args = identifier + Optional(COMMA + delimitedList(key_value))
fn_call1 <<= Group(identifier + LPAREN + Group(kv_args) + RPAREN)
simple_args = Optional(delimitedList(expr))
fn_call2 <<= Group(identifier + LPAREN + Group(simple_args) + RPAREN)

value.parseString(sample).pprint()

rawDescription: Not so simple recursive descent in PyParsing


code:
for i in pixels:
    for j in tabela:
        if i == j[0]:
            arrayBits.append(j[1])

rawDescription: How to make comparisons between two large lists fast python

description: Make comparisons between two large lists fast python


code:
def to_document(self):
    return self.__dict__
@classmethod
def from_document(cls, doc):
    return cls(**doc)

rawDescription: python convert object into json for mongodb

description: Python convert object into json for mongodb


code:
def is_unique(items, key=None):
    for k, g in itertools.groupby(sorted(items, key=key), key=key):
        if len(list(itertools.islice(g, 2))) > 1:
            return False
    return True

rawDescription: Python Check If List Is a Mathematical Set Fast


rawDescription: Modifying diagonals in multidimensional numpy arrays


code:
#!/usr/bin/env python3

# standard includes
import sys

# dbus includes
import dbus

# project includes
import common

def client(mes):
    bus = dbus.SessionBus()

    try:
        proxy = bus.get_object(common.ECHO_BUS_NAME, common.ECHO_OBJECT_PATH)
    except dbus.DBusException as e:
        # There are actually two exceptions thrown:
        # 1: org.freedesktop.DBus.Error.NameHasNoOwner
        #   (when the name is not registered by any running process)
        # 2: org.freedesktop.DBus.Error.ServiceUnknown
        #   (during auto-activation since there is no .service file)
        # TODO figure out how to suppress the activation attempt
        # also, there *has* to be a better way of managing exceptions
        if e._dbus_error_name != 'org.freedesktop.DBus.Error.ServiceUnknown':
            raise
        if e.__context__._dbus_error_name != 'org.freedesktop.DBus.Error.NameHasNoOwner':
            raise
        print('client: No one can hear me!!')
    else:
        iface = dbus.Interface(proxy, common.ECHO_INTERFACE)
        iface.echo(mes)

def main(exe, args):
    if args:
        client(' '.join(args))
    else:
        sys.exit('Usage: %s message...' % exe)

if __name__ == '__main__':
    main(sys.argv[0], sys.argv[1:])

rawDescription: SImple (but specific) listener and sender Python 3 DBus example


code: set(chain.from_iterable(values for key, values in rev_multidict.items() if len(values) > 1))

rawDescription: Find dictionary keys with duplicate values


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse

fig, ax = plt.subplots()

ax.axis('equal')
ell = Ellipse(xy=[0,0], width=30, height=10, angle=0,
              edgecolor='b', lw=4, facecolor='none')

ax.add_artist(ell)
ax.set(xlim=[-100, 100], ylim=[-100, 100])

plt.show()

rawDescription: Can't plot ellipse in python without fillcolor


code:
s, t = 'acegikmoqsuwy\nbdfhjlnprtvxz', 'bdfhjlnprtvxzacegikmoqsuwy'
tmp = list(s + t)
tmp[0::2], tmp[1::2] = s, t
print(''.join(tmp))

rawDescription: How you can unite-merge parts of a sliced string?


code:
parser = argparse.ArgumentParser()
parser.add_argument('-m')
parser.add_argument('-u')

args = parser.parse_args()
if not (args.m or args.u):
    sys.exit(1) # should exit non-zero on failures

rawDescription: Argument checks best practices

description: Argument checks best practices


code:
for word in wordlist1:
   if word.lower() not in filterlist:
        words.append(word)

rawDescription: Exclude list of words when reading a file


code:
t2.set_index('letters',inplace=True)
t2_map = t2.target.to_dict()

rawDescription: "Index Match" functionality in Excel not captured in pandas Merge (or is it?)


code: path = getCurrentTerminalPath()

rawDescription: Find the Current Directory of the Current Terminal Tab in Python


code:
def f1(x):
    return 'f1 %s' % x

def f2(x):
    return 'f2 %s' % x

def f3(x):
    return 'f3 %s' % x

rawDescription: Can't figure this function composition code


code:
import itertools
l = [{'row':1}, {'row':2}, {'row':1}, {'row':3}, {'row':1}]
row = lambda d: d['row']
[list(grp) for _, grp in itertools.groupby(sorted(l, key=row), key=row)]

rawDescription: convert list of dict into list of list of dict

description: Convert list of dict into list of list of dict


code:
from subprocess import call
call(["java", "-jar", "foo.jar"])

rawDescription: How to run jar files in python

description: Run jar files in python


code: form = AccountSettingsForm(request.POST, obj=request.user, country=request.user.account.country)

rawDescription: WTForms and Django OneToOneFields

description: WTForms and Django OneToOneFields


rawDescription: Tkinter press button with command

description: Tkinter press button with command


code:
import Image
im = Image.open("test.jpg")
max(im.getcolors(im.size[0]*im.size[1]))

rawDescription: main color detection in Python

description: Main color detection in Python


code:
def screen2iso(self, x, y):
    x = x / 2
    xx = (y + x) / (self.SETTING['TILE_WIDTH'] / 2)
    yy = (y - x) / (self.SETTING['TILE_WIDTH'] / 2)
    return xx, yy

rawDescription: Python pygame Detect if mouse is over non transparent part of surface


code:
base_h, base_s, base_v = rgb_to_hsv(base_r, base_g, base_b)
target_h, target_s, target_v = rgb_to_hsv(target_r, target_g, target_b)
delta_h, delta_s, delta_v  = target_h-base_h, target_s-base_s, target_v- base_v

rawDescription: Changing the color of an image based on RGB value


code:
print
print()

rawDescription: How to print on the same line in a loop?

description: Print on the same line in a loop


code:
import pylab as plt

xs = [1, 2, 1, 4, 3, 2]
ys = [1, 3, 2, 2, 3, 1]
labels = [1, 1, 0, 2, 1, 3]

label_dict = {0: 'r', 1: 'k', 2: 'b', 3: 'g'}
legend_dict = {0: 'foo', 1: 'bar', 2: 'baz', 3: 'biff'}

seen = set()
for x, y, label in zip(xs, ys, labels):
    if label not in seen:
        plt.scatter(x, y, c=label_dict.get(label), label=legend_dict.get(label))
    else:
        plt.scatter(x, y, c=label_dict.get(label))
    seen.add(label)

plt.legend()
plt.show()

rawDescription: Depict legend without repeats

description: Depict legend without repeats


rawDescription: Pandas stack/groupby to make a new dataframe


code:
import os
import sys
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer

class MyHTTPRequestHandler(SimpleHTTPRequestHandler):
    def translate_path(self,path):
        path = SimpleHTTPRequestHandler.translate_path(self,path)
        if os.path.isdir(path):
            for base in "index", "default":
                for ext in ".html", ".htm", ".txt":
                    index = path + "/" + base + ext
                    if os.path.exists(index):
                        return index
        return path

def test(HandlerClass = MyHTTPRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)

if __name__ == '__main__':
    test()

rawDescription: SimpleHTTPServer add default.htm default.html to index files


code:
def make(self, size):

    with open('res.txt', 'w+') as file_: # file is a builtin function in python 2
        # also, use with statements for files used on only a small block, it handles file closure even if an error is raised.
        for i in range(1, size+1):
            prod = itertools.product(self.chars, repeat=i)

            for j, r in enumerate(prod):
                text = ''.join(r)
                md5 = self.getMD5(text)
                res = text+'\t'+md5
                print(res + ' %.3f%%' % ((j+1)/float(self.get_length(size))*100))
                file_.write(res+'\n')

rawDescription: Python: itertools.product consuming too much resources


code:
#make proxy artists
#make list of one line -- doesn't matter what the coordinates are
line = [[(0, 0)]]
#set up the line collections
lc = LineCollection(2 * line, linestyles = ['solid', 'dashed'], colors = ['black', 'black'])
lc2 = LineCollection(2 * line, linestyles = ['solid', 'dashed'], colors = ['blue', 'blue'])
lc3 = LineCollection(3 * line, linestyles = ['solid', 'dashed', 'solid'], colors = ['blue', 'red', 'green'])
#create the legend
plt.legend([lc, lc2, lc3], ['text', 'more text', 'extra line'], handler_map = {type(lc) : HandlerDashedLines()}, handlelength = 2.5)

rawDescription: Two line styles in legend

description: Two line styles in legend


code: df.groupby(['ID','Category']).agg({'Date_Field' : [min, max]})

rawDescription: establish begin/end dates via groupby

description: Establish begin/end dates via groupby


code: fileURLS = re.findall('http.*NPPES_Data_Dissemination.*\.zip', r.text)

rawDescription: Python Downloading Data File from Web-Scraped URL


code:
def hide(root):
    root.withdraw()

def show(root):
    root.update()
    root.deiconify()

rawDescription: tkinter: how to not display the empty root window when creating it

description: Tkinter: how to not display the empty root window when creating it


code:
import sys
from PyQt4.QtGui import QApplication
from MainWindow import MainWindow
from LoginError import LoginError

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

    try:
        main = MainWindow()
        main.show()
    except LoginError:
        # do something if the user can't log in
        sys.exit()

    sys.exit(app.exec_())

rawDescription: How to close a login dialog and show the main window (PyQt4)

description: Close a login dialog and show the main window (PyQt4)


code:
reg = re.compile(r'''
     (?xs)               # no need for i, but for s (dot matches newlines)
     (?:\b\w\.\s*)       # e.g. A. or b. (word boundary to restrict to 1 letter)
     ((?:(?!\b\w\.).)+)  # everything until the next A. or b.
     ''')

rawDescription: Negating previously matched word group

description: Negating previously matched word group


code: lines = [map(int, line.strip('<>,\n').split(',')) for line in f]

rawDescription: Splitting Lists elements further

description: Splitting Lists elements further


rawDescription: grep output not same as "re.findall()" output in python3

description: Grep output not same as "re.findall()" output in python3


code:
rect = Rectangle(0, "red", width=100, height=20)
circ = Circle(0, "blue", radius=5)

rawDescription: Python Abstract Programming

description: Python Abstract Programming


code:
df['Year'] = df['date'].dt.year
df2 = df.set_index(['Year', 'Season'], inplace=False)

rawDescription: Selecting time-series data in a specific sequence using pandas


rawDescription: Splitting a comma-separated string

description: Splitting a comma-separated string


code:
source = dict()
for mapping in yourlist:
    if 'X' in mapping:
        source = mapping
    else:
        mapping.update(source)

rawDescription: Concatenating list of dictionaries

description: Concatenating list of dictionaries


code:
import scipy.interpolate as interp
z = arange(0,4)
x = np.array([1,2,4,3])
f = interp.interp1d(z, x)
newx = f(np.linspace(z[0],z[-1],7))

rawDescription: Line smoothing with Numpy/SciPy

description: Line smoothing with Numpy/SciPy


code:
EXCLUDE_FILES = ['README', 'INSTALL', '.cvsignore']

mytarfile.add(..., filter=lambda x: None if x.name in EXCLUDE_FILES else x)

rawDescription: Python tarfile and excludes

description: Python tarfile and excludes


code:
asis:abc
asis:acb
asis:bac
asis:bca
asis:cab
asis:cba

rawDescription: python 2.7 permutation of string starting from index

description: Python 2.7 permutation of string starting from index


code:
pairs = { 'word1':0, 'word2':0, 'word3':2000, 'word4':64, 'word5':0, 'wordn':8 }
any(v > 0 for v in pairs.itervalues())
any(v > 3000 for v in pairs.itervalues())

rawDescription: Check if any value of a dictionary matches a condition


code: form = DogImageForm(user=request.user)

rawDescription: Access request.user in modelForm

description: Access request.user in modelForm


code:
import pylab
import matplotlib

def my_circle_scatter(axes, x_array, y_array, radius=0.5, **kwargs):
    for x, y in zip(x_array, y_array):
        circle = pylab.Circle((x,y), radius=radius, **kwargs)
        axes.add_patch(circle)
    return True

def my_square_scatter(axes, x_array, y_array, size=0.5, **kwargs):
    size = float(size)
    for x, y in zip(x_array, y_array):
        square = pylab.Rectangle((x-size/2,y-size/2), size, size, **kwargs)
        axes.add_patch(square)
    return True

def my_polygon_scatter(axes, x_array, y_array, resolution=5, radius=0.5, **kwargs):
    ''' resolution is number of sides of polygon '''
    for x, y in zip(x_array, y_array):
        polygon = matplotlib.patches.CirclePolygon((x,y), radius=radius, resolution=resolution, **kwargs)
        axes.add_patch(polygon)
    return True

axes=pylab.axes()
my_circle_scatter(axes, [0,0.5], [0,0.5], radius=2, alpha=.5, color='b')
my_square_scatter(axes, [-3,-4,2,3], [1,-3,0,3], size=.5, alpha=.5, color='r')
my_polygon_scatter(axes, [-1,-2,3], [-3,0,3], radius=.5, resolution=3, alpha=.5, color='g')
my_polygon_scatter(axes, [4,1.5,3], [2,-1,-3], radius=.5, resolution=5, alpha=.5, color='k')
pylab.axis('scaled')
pylab.axis([-5,5,-5,5])
pylab.show()

rawDescription: Plot/scatter position and marker size in the same coordinates


code:
print("import is in progress")

def foo():
    pass

rawDescription: python import multiple times

description: Python import multiple times


code:
data = [[int(n) for n in item.split()] for item in data]

DF = pd.DataFrame(data, columns=['pid', 'timestamp'])

rawDescription: Python Pandas: Comparison of Min Max Values Per Group


code:
#!/usr/bin/env python

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import Session

Base = declarative_base()
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

    def __init__(self, name, fullname, password):
        self.name = name
        self.fullname = fullname
        self.password = password

    def __repr__(self):
       return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)

engine = create_engine('sqlite:///:memory:', echo=True)

Base.metadata.create_all(engine)
session = Session(bind=engine)
ed_user = User('ed', 'Ed Jones', 'edspassword')
session.add(ed_user)
session.commit()

result = session.query(*[c for c in User.__table__.c if c.name != 'password']).all()
print(result)

rawDescription: Retrieving all columns but some with SQLAlchemy


code: has = ['401k:T', 'health_in:F', 'has_childcare:T']

rawDescription: How to Make Efficient Google-App-Engine Schema with Lots of BooleanPropertys


code:
import csv

d = dict()

with open(r'd:/file.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        # if the family name doesn't
        # exist in our dictionary,
        # set it with a default value of a blank dictionary
        if row[2] not in d:
            d[row[2]] = dict()

        # If the meal type doesn't exist for this
        # family, set it up as a key in their dictionary
        # and set the value to int value of the count
        if row[1] not in d[row[2]]:
            d[row[2]][row[1]] = int(row[0])
        else:
            # Both the family and the meal already
            # exist in the dictionary, so just add the
            # count to the total
            d[row[2]][row[1]] += int(row[0])

rawDescription: Organizing and printing information by a specific row in a csv file


code:
import numpy as np

def sub_sums(arr, nrows, ncols):
    h, w = arr.shape
    h = (h // nrows)*nrows
    w = (w // ncols)*ncols
    arr = arr[:h,:w]
    return (arr.reshape(h // nrows, nrows, -1, ncols)
               .swapaxes(1, 2)
               .reshape(h // nrows, w // ncols, -1).sum(axis=-1))

arr = np.asarray([range(0, 5),
                  range(4, 9),
                  range(8, 13),
                  range(12, 17)])

print(sub_sums(arr, 2, 2))

rawDescription: Sums of subarrays

description: Sums of subarrays


rawDescription: Python - How to sort a dictionary based on its value as well it key


code:
"i ate breakfast."
"This is , a sentence."
"What time is it?"
"I a ,d am."
"I a,d am."

rawDescription: Regular expression of a sentence

description: Regular expression of a sentence


code:
class ReadDirectoryRequest(multiprocessing.Process):

    def _perform_and_wait4request(self, path, recursive, event_buffer, nbytes):
        hdl = CreateFileW(path, FILE_LIST_DIRECTORY, WATCHDOG_FILE_SHARE_FLAGS,
                       None, OPEN_EXISTING, WATCHDOG_FILE_FLAGS, None)
        #print("path: " + path)
        aux_buffer = ctypes.create_string_buffer(BUFFER_SIZE)
        aux_n = ctypes.wintypes.DWORD()
        #print("_perform_and_wait4request! PID:" + str(os.getpid()))
        #print("CALLBACK THREAD: " + str(threading.currentThread()) + "\n----------")
        try:
            ReadDirectoryChangesW(hdl, ctypes.byref(aux_buffer),
                              len(event_buffer), recursive,
                              WATCHDOG_FILE_NOTIFY_FLAGS,
                              ctypes.byref(aux_n), None, None)
        except WindowsError as e:
            print("!" + str(e))
            if e.winerror == ERROR_OPERATION_ABORTED:
                nbytes = 0
                event_buffer = []
            else:
                nbytes = 0
                event_buffer = []
        # Python 2/3 compat
        nbytes.value = aux_n.value
        for i in xrange(self.int_class(aux_n.value)):
            event_buffer[i] = aux_buffer[i]
        CloseHandle(hdl)
        try:
            self.lck.release()
        except:
            pass

    def __init__(self, handle, recursive):
        buffer = ctypes.create_string_buffer(BUFFER_SIZE)
        self.event_buffer = multiprocessing.Array(ctypes.c_char, buffer)
        self.nbytes = multiprocessing.Value(ctypes.wintypes.DWORD, 0)
        targetPath = handle2file.get(handle, None)
        super(ReadDirectoryRequest, self).__init__(target=self._perform_and_wait4request, args=(targetPath, recursive, self.event_buffer, self.nbytes))
        self.daemon = True
        self.lck = multiprocessing.Lock()
        self.result = None
        try:
            self.int_class = long
        except NameError:
            self.int_class = int
        if targetPath is None:
            self.result = ([], -1)

    def CancelIo(self):
        try:
            self.result = ([], 0)
            self.lck.release()
        except:
            pass

    def read_changes(self):
        #print("read_changes! PID:" + str(os.getpid()))
        #print("CALLBACK THREAD: " + str(threading.currentThread()) + "\n----------")
        if self.result is not None:
            raise Exception("ReadDirectoryRequest object can be used only once!")
        self.lck.acquire()
        self.start()
        self.lck.acquire()
        self.result = (self.event_buffer, self.int_class(self.nbytes.value))
        return self.result

rawDescription: Watchdog compatibility: A workaround for "CancelIoEx"


code: df.apply(pd.Series.value_counts, axis=1)[['C1', 'C2', 'C3']].fillna(0)

rawDescription: Count occurrences of items in Series in each row of a DataFrame


code:
filename="myFileName.something"
fileInfo=QtCore.QFileInfo(filename)
name=fileInfo.baseName()
myCommand="rungms %s.inp 13-64 1 0 %s.out"%(name,name)

rawDescription: Get name of file for command line

description: Get name of file for command line


code:
items = [{'name':'a'},{'name':'b'},{'name':'c'}]
','.join([i['name'] for i in items])

rawDescription: Taking a list of items and displaying a value from each item as a string


code:
class Employee(object):
    def __init__(self, *initial_data, **kwargs):
        for dictionary in initial_data:
            for key in dictionary:
                setattr(self, key, dictionary[key])
        for key in kwargs:
            setattr(self, key, kwargs[key])

rawDescription: Set attributes from dictionary in python


code:
def download_xls(self, request):
    os.chdir('/tmp')
    xls_name = re.sub('\s+', '_', "%s_%s_%s.xlsx" % (
        request.user.username.lower(),
        self.report.name.lower(),
        datetime.now().strftime('%y%m%d_%H%I%S')))
    output = io.BytesIO()

    workbook = Workbook(output, {'in_memory': True})
    worksheet1 = workbook.add_worksheet()
    worksheet2 = workbook.add_worksheet()

    worksheet1.write("A1", "hello1")
    worksheet2.write("A1", "hello2")

    workbook.close()

    output.seek(0)

    response = HttpResponse(content_type='application/ms-excel')
    response['Content-disposition'] = "attachment; filename=%s" % xls_name

    return response

rawDescription: Downloading a file with django

description: Downloading a file with django


code:
t = threading. Thread(target=func, args=[])
t.start()

rawDescription: How to wait for an input without blocking timer in python?

description: Wait for an input without blocking timer in python


code: self.assertEqual(object.next(), "123")

rawDescription: Python mocking requests.get content and iter_lines()


code: next(entry['id'] for entry in stop_list if entry['name'] == name)

rawDescription: How to get a value from a list of dictionary Python?

description: Get a value from a list of dictionary Python


code:
mister = [['ququ.kz', 1], ['gp.kz', 1], ['gmail.ru', 1], ['mail.ru', 1], ['tlc.com', 1], ['mail.ko', 1], ['microsoft.jp', 1], ['hotmail.eu', 1], ['soman.com', 1], ['swedenborgen.sn', 1], ['customergoogle.com', 1], ['mail.jp', 2], ['gmail.com', 3], ['mail.ru', 3], ['hotmail.com', 3], ['mail.jp', 3], ['mail.com', 4], ['hotmail.com', 4], ['gmail.com', 4], ['mail.kz', 5], ['mail.cn', 7], ['hotmail.com', 9], ['customers.kz', 9], ['microsoft.com', 10], ['conestogamall.com', 13]]
print(*mister, sep='\n')

rawDescription: How to use one print() in python to print list items line by line - not in one streak?

description: Use one print() in python to print list items line by line - not in one streak


code:
def plotLine(p1, p2):
    plt.plot( [p1[0], p2[0]], [p1[1], p2[1]] )

Lat = [1,2,3,4]
Long = [2,3,1,3]
id_point=['A','B','C','D']

# Fill a dictionary with the points
points = {} # Create empty dictionary
for idx, point in enumerate(zip(Lat,Long)):
    points[id_point[idx]] = point

# Plot points and their names
plt.plot(Lat, Long,'o') #Plot the points as you did
for key in points:
    plt.annotate(key, xy=points[key]) #Print name of point

plotLine(points['A'], points['B']) #Connect point A and B
plt.show()

rawDescription: How to give id to point and draw line point to point using matplotlib.plyplot in python

description: Give id to point and draw line point to point using matplotlib.plyplot in python


code: all_counts = Counter(chain.from_iterable(map(set, all_lists)))

rawDescription: Counting appearance of an element in many lists


rawDescription: How to get all tasks and periodic tasks in Celery

description: Get all tasks and periodic tasks in Celery


code:
values = []
for _ in range(_):
    values.append([name1, name2, value1, value2])

rawDescription: Trying to create a (list or array, not sure) with data I have outputted from a nested for loop


code: make_dict("product: Netatalk version: 2.2.0 extrainfo: name: WNDR4500; protocol 3.3 ostype: Unix")

rawDescription: Dictionary like operations on string in python3


code:
def clickGo():
    buttons = ['geh,','DAT,','GDH,','gl1,']
    for item in xrange[4]: #<4 is total number of switches
        if checkSwitches()[item]: #checking for Trues ( which im assuming 'isChecked()' returns)
             doButtonJunk(buttons[item])

rawDescription: Using checkboxes in python to select which files to write/export


code:
_corrections = {}

def autocorrect(sequence):
    normalized = () # used as keys into _autocorrection_dict
    corrected = []  # values from _autocorrection_dict
    for item in sequence:
        if isinstance(item, str):
            normalized += (item.lower(),)
            corrected = _corrections.setdefault(normalized, corrected + [item])

        elif isinstance(item, tuple):
            sub_norm = tuple(subitem.lower() for subitem in item)
            if normalized + (sub_norm,) not in _corrections:
                sub_corrected = ()
                for subitem in item:
                    sub_result = _corrections.setdefault(normalized + (subitem.lower(),),
                                                         corrected + [subitem])
                    sub_corrected += (sub_result[-1],)
                _corrections[normalized + (sub_norm,)] = corrected + [sub_corrected]
            normalized += (sub_norm,)
            corrected = _corrections[normalized]

        else:
            raise TypeError("Unexpected item type: {}".format(type(item).__name__))

    return corrected

rawDescription: Auto-correct case spelling of a word database


code: nltk.tokenize.RegexpTokenizer("\\w+|[^\\w\\s]+").tokenize("Let's check this out.")

rawDescription: Preserving contractions with textblob ngrams


code:
import sqlite3
the_global_connection = sqlite3.connect( "stocks.db" )

rawDescription: Automate Opening and Closing the Database Connection


rawDescription: Subsets for a string

description: Subsets for a string


code:
#!/usr/bin/env python
from __future__ import print_function
import io

with io.open('d.txt','r',encoding='utf-8',errors='ignore') as infile, \
     io.open('d_parsed.txt','w',encoding='ascii',errors='ignore') as outfile:
    for line in infile:
        print(*line.split(), file=outfile)

rawDescription: Python read from file and remove non-ascii characters


code:
def consec(l):
    for k, v in groupby(l):
        lst = list(v)
        if len(lst) > 1 or lst[0]:
            for ele in lst:
                yield ele

myList[:] = (consec(myList))
print(myList)

rawDescription: How to remove blank element in between non-blank elements in list?

description: Remove blank element in between non-blank elements in list


code:
lst = ['a', ['b', 'c', ['d', 'i'], 'e'], 'f', ['g', 'h', ['j', 'k', 'l', 'm']]]

def print_list(lst, level=0):
    print('    ' * (level - 1) + '+---' * (level > 0) + lst[0])
    for l in lst[1:]:
        if type(l) is list:
            print_list(l, level + 1)
        else:
            print('    ' * level + '+---' + l)

print_list(lst)

rawDescription: Python recursively printing a tree from a list structure


code:
import os
root = './'
files = [(path,f) for path,_,file_list in os.walk(root) for f in file_list]
out_file = open('master.txt','w')
for path,f_name in files:
    in_file = open('%s/%s'%(path,f_name), 'r')

    # write out root/path/to/file (space) file_contents
    for line in in_file:
        out_file.write('%s/%s %s'%(path,f_name,line))
    in_file.close()

    # enter new line after each file
    out_file.write('\n')

out_file.close()

rawDescription: Python text files merge from subdirectory


code:
seen = set()
uniq = [x for x in a if x not in seen and not seen.add(x)]

rawDescription: Find and list duplicates in Python list

description: Find and list duplicates in Python list


rawDescription: Python append method not working correctly


code:
string = 'Fr-Mo'
days = string.split('-')
start = days_order.index(days[0])
end = days_order.index(days[1], start + 1) + 1

rawDescription: Python: get items from list between 2 known items


code: Apple.objects.order_by('a', 'b')

rawDescription: Django 1.9: Create complex custom filter method for QuerySet


code:
from __future__ import print_function
print(*a)

rawDescription: How does "foo(*a)" work in Python?

description: How does "foo(*a)" work in Python


rawDescription: Removing punctuation except intra-word dashes Python


code: new_key._Key__app = 'new-app-id'

rawDescription: programmatically convert a string of datastore key for a new app ID? (Master/slave -> HRD migration)

description: Programmatically convert a string of datastore key for a new app ID? (Master/slave -> HRD migration)


code: re.split(r'\s+and\s+|,(?!\s*Ph\.D\.)\s*', 'Joe, Dave, Professional, Ph.D. and Someone else')

rawDescription: python regex to split on certain patterns with skip patterns

description: Python regex to split on certain patterns with skip patterns


code:
def key_press_wrapper():
    your_function1()
    your_function2()

rawDescription: Python Tkinter: Binding Same Key Twice?

description: Python Tkinter: Binding Same Key Twice


code:
from selenium import webdriver

headers = { 'Accept':'*/*',
    'Accept-Encoding':'gzip, deflate, sdch',
    'Accept-Language':'en-US,en;q=0.8',
    'Cache-Control':'max-age=0',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'
}

for key, value in enumerate(headers):
    webdriver.DesiredCapabilities.PHANTOMJS['phantomjs.page.customHeaders.{}'.format(key)] = value

rawDescription: Selenium PhantomJS custom headers in Python


code:
def someDecorator(arg=None):
    def decorator(func):
        def wrapper(*a, **ka):
            return func(*a, **ka)
        return wrapper

    if callable(arg):
        return decorator(arg) # return 'wrapper'
    else:
        return decorator # ... or 'decorator'

rawDescription: Using python decorator with or without parentheses


code: return x, y

rawDescription: why can't I change the variables using kwargs inside a function?

description: Why can't I change the variables using kwargs inside a function


rawDescription: numpy, named columns

description: Numpy, named columns


code:
class ContextMixin:
    extra_context = {}

    def get_context_data(self, **kwargs):
        context = super(ContextMixin, self).get_context_data(**kwargs)
        context.update(self.extra_context)
        return context

class FooUpdate(ContextMixin, UpdateView):
    model = Foo
    extra_context={'page_title': 'foo-objects name should go here'}

rawDescription: Get object attribute in class based view


code:
EXTRA_DATA = [
    ('refresh_token', 'refresh_token', True),
    ('expires_in', 'expires_in'),
    ('token_type', 'token_type', True),
    ('scope', 'scope'),
]

rawDescription: Decide when to refresh OAUTH2 token with Python Social Auth


code:
@login_required
def tags(request):
    all_tags = Tag.objects.all()
    context = base_context(request)
    if request.method == 'POST':
        if 'status_check' in request.POST:
            status = int(request.POST['select'])
            tag = request.POST['tag']
            user = request.user

            new_tag = Tag.object.create(slug=tag)
            TagStatus.objects.create(status=status, tag=new_tag, user=user)

            response = simplejson.dumps({"status": "Successfully changed status"})
        else:
            response = simplejson.dumps({"status": "Error"})
            return HttpResponse (response, mimetype='application/json')
    status_form = TagStatusForm()
    context['all_tags'] = all_tags
    return render_to_response('tags/tags.html', context, context_instance=RequestContext(request))

rawDescription: Django object isn't saving username with get_or_create()


code: newlist

rawDescription: python add two list and createing a new list

description: Python add two list and createing a new list


code:
import re
import math
from optparse import OptionParser

length_regexp = 'Duration: (\d{2}):(\d{2}):(\d{2})\.\d+,'
re_length = re.compile(length_regexp)

from subprocess import check_call, PIPE, Popen
import shlex

def main():
    filename, split_length = parse_options()
    if split_length <= 0:
        print("Split length can't be 0")
        raise SystemExit

    p1 = Popen(["ffmpeg", "-i", filename], stdout=PIPE, stderr=PIPE, universal_newlines=True)
    # get p1.stderr as input
    output = Popen(["grep", 'Duration'], stdin=p1.stderr, stdout=PIPE, universal_newlines=True)
    p1.stdout.close()
    matches = re_length.search(output.stdout.read())
    if matches:
        video_length = int(matches.group(1)) * 3600 + \
                       int(matches.group(2)) * 60 + \
                       int(matches.group(3))
        print("Video length in seconds: {}".format(video_length))
    else:
        print("Can't determine video length.")
        raise SystemExit

    split_count = math.ceil(video_length / split_length)

    if split_count == 1:
        print("Video length is less than the target split length.")
        raise SystemExit

    for n in range(split_count):
        split_start = split_length * n
        pth, ext = filename.rsplit(".", 1)
        cmd = "ffmpeg -i {} -vcodec copy  -strict -2 -ss {} -t {} {}-{}.{}".\
            format(filename, split_start, split_length, pth, n, ext)
        print("About to run: {}".format(cmd))
        check_call(shlex.split(cmd), universal_newlines=True)

def parse_options():
    parser = OptionParser()

    parser.add_option("-f", "--file",
                      dest="filename",
                      help="file to split, for example sample.avi",
                      type="string",
                      action="store"
    )
    parser.add_option("-s", "--split-size",
                      dest="split_size",
                      help="split or chunk size in seconds, for example 10",
                      type="int",
                      action="store"
    )
    (options, args) = parser.parse_args()

    if options.filename and options.split_size:

        return options.filename, options.split_size

    else:
        parser.print_help()
        raise SystemExit

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print(e)

rawDescription: Using Python script to cut long videos into chunks in FFMPEG


code:
sortbit(3)
sortbit(4)

rawDescription: appending values to list and adding to dictionary

description: Appending values to list and adding to dictionary


rawDescription: How to find out if there are any duplicates in list of lists

description: Find out if there are any duplicates in list of lists


rawDescription: numpy.where equivalent for csr_matrix python

description: Numpy.where equivalent for csr_matrix python


code: grouped.agg(custom_agg, default=np.sum, other={'CHROM': np.mean})

rawDescription: Python pandas to partially collapse 2d matrix


code: y.loc[index1, 3] = y.loc[index2, 2].values

rawDescription: Editing values in a pandas dataframe using data from another part of the dataframe


rawDescription: zip function help with tuples

description: Zip function help with tuples


code:
def mypartial(func, x):

    def newfunc(val):
        return x + val

    return newfunc

add_3 = mypartial(myadd, 3)  #equivalent to add_3 = newfunc
print(add_3(2))  #=>5

rawDescription: Function in Class __init__ Dict | Functions Evaluated on Call of Class


code:
def fizz_count(x):
    count=0
    for string in x:
        if string == 'fizz':
            count = count + 1
    return count

rawDescription: Counting a specific string in the list in Python


code:
l = table[ (length, gc) ]
l.append( (start) )
table[ (length, gc) ] = l

rawDescription: Python multiprocessing: losing counts after pool.join()?


code: mydict = collections.defaultdict(list, likes)

rawDescription: Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python?


code:
try:
   x=sum(similarity(i,j) for i in a for j in b)
except TypeError:
   x=0

rawDescription: Python, best way to write a sum of two for loops


code:
p = pd.PeriodIndex(freq='m', start='2000-1', periods=18)
starts = df['LIST_DATE'].apply(lambda t: t.to_period(freq='m')).value_counts()
ends = df['END_DATE'].apply(lambda t: t.to_period(freq='m')).value_counts()

rawDescription: Create a Pandas dataframe with counts of items spanning a date range


code:
from social_auth.backends.facebook import FacebookBackend
class CustomFacebookBackend(FacebookBackend):
    name = 'facebook'

    def get_user_details(self, response):
        """Return user details from Facebook account"""
        return {'username': response['name'],
                'email': response.get('email', ''),
                'first_name': response.get('first_name', ''),
                'last_name': response.get('last_name', '')}

rawDescription: How to show user a form to set username when using django with django-social-auth

description: Show user a form to set username when using django with django-social-auth


code:
def highestNumber(l):
    l.sort()
    return l[-1]

rawDescription: Python: Function returning highest value in list without max()?


code:
x,y,z = 5,10,20  # works
x,y = 5,10,20    # does not work
x,y,z = 5,10     # does not work

rawDescription: Circle Clicking game simple python

description: Circle Clicking game simple python


code:
from collections import defaultdict
from itertools import count
from functools import partial

label_to_number = defaultdict(partial(next, count(1)))
[(label_to_number[label], label) for label in labels]

rawDescription: Python: Enumerate a list of string 'keys' into ints


code: {i:j for i,*j in list1}

rawDescription: Converting List to Dict

description: Converting List to Dict


code:
cols = df.columns[df.columns.str.contains('B')]
df[cols] = df[cols].mul(df.A, axis = 0)

rawDescription: Replace certain column with `filter(like = "")` in Pandas