code:
class ObservingMeta(type):
    def __call__(cls, *args, **kw):
         instance = super(ObservingMeta, cls).__call__(*args, **kw)
         for attr in vars(cls).values():
             if hasattr(attr, '__observer__'):
                 # register bound method
                 bound = attr.__get__(instance, cls)
                 Observable.instance().obs.append(bound)
         return instance

rawDescription: How to use decorator in observer pattern for Python 2.7

description: Use decorator in observer pattern for Python 2.7


code:
unsigned = ord(character)
signed = unsigned - 256 if unsigned > 127 else unsigned

rawDescription: convert ascii character to signed 8-bit integer python

description: Convert ascii character to signed 8-bit integer python


code:
from xml.etree import ElementTree as ET
ET.register_namespace('com',"http://www.company.com") #some name

# build a tree structure
root = ET.Element("{http://www.company.com}STUFF")
body = ET.SubElement(root, "{http://www.company.com}MORE_STUFF")
body.text = "STUFF EVERYWHERE!"

# wrap it in an ElementTree instance, and save as XML
tree = ET.ElementTree(root)

tree.write("page.xml",
           xml_declaration=True,encoding='utf-8',
           method="xml")

rawDescription: Emitting namespace specifications with ElementTree in Python


code: [(x, df.columns[y]) for x,y in np.argwhere(df)]

rawDescription: Python pandas: Getting the locations of a value in dataframe


code:
files = set(files)
if 'B.csv' in files:
    fileList.append(os.path.join(dirpath, 'B.csv'))
elif 'A.csv' in files:
    fileList.append(os.path.join(dirpath, 'A.csv'))

rawDescription: Searching recursively for files to add to list, but if one type of file is found ignore other type


code: arr = arr.view(np.recarray)

rawDescription: How to convert Python dictionary object to numpy array

description: Convert Python dictionary object to numpy array


code: import a

rawDescription: Generate graph of the imports

description: Generate graph of the imports


code:
lst = []
lst += 'spam'
lst

rawDescription: How to recursive iterparse an LXML tree avoiding to enter twice a node?

description: Recursive iterparse an LXML tree avoiding to enter twice a node


rawDescription: Splitting a String Python within a list

description: Splitting a String Python within a list


code:
import numpy as np
import pandas as pd
NaN = np.nan

df = pd.DataFrame(
    {'a':['y',NaN,'y',NaN,NaN,'x','x','y',NaN],
     'b':[NaN,'x',NaN,'y','x',NaN,NaN,NaN,'y'],
     'd':[32,12,55,98,23,11,9,91,3]})

melted = pd.melt(df, id_vars=['d'], value_vars=['a', 'b'])
result = pd.pivot_table(melted, values='d', index=['value'], columns=['variable'],
                        aggfunc=np.median)
print(result)

rawDescription: summarizing data frame in pandas - python

description: Summarizing data frame in pandas - python


code:
class CountingWrapper(object):
    def __init__(self, *args, **kwargs):
        self.segment_count = 0
        self.f = open(*args, **kwargs)
    def write(self, *args, **kwargs):
        self.segment_count += 1
        return self.f.write(*args, **kwargs)

payloadRecon = CountingWrapper('TCPStreamPayload.txt', 'a')
payloadRecon.write('dsfsd')
assert payloadRecon.count == 1

rawDescription: Python Increasing counter by 1 every time something is written to a file


code: label1.place(x=1, y=1)

rawDescription: How to temporarily remove ( not delete and replace ) Tkinter widget without using just .place?

description: Temporarily remove ( not delete and replace ) Tkinter widget without using just .place


code:
from gi.repository import Nautilus, GObject
from urllib import unquote
from subprocess import Popen, PIPE

def getexiftool(filename):
    options = '-fast2 -f -m -q -q -s3 -ExifIFD:DateTimeOriginal'
    exiftool = Popen(['/usr/bin/exiftool'] + options.split() + [filename],
                     stdout=PIPE, stderr=PIPE)
    output, errors = exiftool.communicate()
    return output.split('\n')

class MyExtension(Nautilus.ColumnProvider, Nautilus.InfoProvider, GObject.GObject):
    def __init__(self):
        pass

    def get_columns(self):
        return (
            Nautilus.Column(name='MyExif::DateTime',
                            attribute='Exif:Image:DateTime',
                            label='Date Original',
                            description='Data time original'
            ),
        )

    def update_file_info_full(self, provider, handle, closure, file_info):
        if file_info.get_uri_scheme() != 'file':
            return

        filename = unquote(file_info.get_uri()[7:])
        attr = ''

        if file_info.get_mime_type() in ('image/jpeg', 'image/png'):
            GObject.timeout_add_seconds(1, self.update_exif,
                                        provider, handle, closure, file_info)
            return Nautilus.OperationResult.IN_PROGRESS

        file_info.add_string_attribute('Exif:Image:DateTime', attr)

        return Nautilus.OperationResult.COMPLETE

    def update_exif(self, provider, handle, closure, file_info):
        filename = unquote(file_info.get_uri()[7:])

        try:
            data = getexiftool(filename)
            attr = data[0]
        except:
            attr = ''

        file_info.add_string_attribute('Exif:Image:DateTime', attr)

        Nautilus.info_provider_update_complete_invoke(closure, provider,
                               handle, Nautilus.OperationResult.COMPLETE)
        return False

rawDescription: Speed up nautilus python-extensions for reading image's Exif


code:
from np.lib.stride_tricks import as_strided
strided = as_strided(signs,
                     strides=(signs.itemsize,signs.itemsize),
                     shape=(signs.shape,N))

rawDescription: Reasoning about consecutive data points without using iteration


code:
class TimeClockIN(models.Model):
    timestamp = models.DateTimeField()
    driver = models.ForeignKey(Driver, blank=True)

rawDescription: ModelForm returning field is required, not saving to sqliteDB


code: theta_degrees = (i % 360 for i in theta_degrees)

rawDescription: Simple loop for making sure angle is less than 360 [Python]


rawDescription: Reading a raw binary data in python and converting it into ascii


code:
myModel_on_mywindow.status[0] = 2
myModel.mapper.toFirst()

rawDescription: How to use QDataWidgetMapper in Qt or PyQt?

description: Use QDataWidgetMapper in Qt or PyQt


code:
import sys
sys.path.insert(0, '/tmp/python/')

import mylib

rawDescription: Python Import From Specific Location (Multiple Libraries Installed)


rawDescription: Get XML parent tag with regular expressions


code:
class SmithManager(PeopleManager):
    def get_queryset(self):
        return super(SmithManager, self).get_query_set().filter(last_name='Smith')

rawDescription: subclassing models.Manager

description: Subclassing models.Manager


rawDescription: Python: Comparing all elements of two arrays and modifying 2nd array


code:
d = {'a': {1: -0.25, 2: -0.2},
     'b': {1: 'foo', 2: 'bar'}}

print("Original", d)

for k in d:
    d[k] = tuple(map(lambda x: x[1], sorted(d[k].items())))

print("Converted", d)

for k in d:
    d[k] = {i: elem for i, elem in enumerate(d[k], 1)}

print("Re-converted", d)

rawDescription: how to convert dict element of dict to tuple and viceversa?

description: Convert dict element of dict to tuple and viceversa


rawDescription: Algorithm to sort object by attribute value without allowing gaps or duplicates


code:
with open("Class1.txt") as fobj:
    scores = {}
    for line in fobj:
        name, score = line.split(',')
        name = name.strip()
        score = int(score)
        scores.setdefault(name, []).append(score)

rawDescription: How to sort notepad data in average order?

description: Sort notepad data in average order


code: df['new_sample'] = (df[['B','C']] == 0).any(1).astype(int)

rawDescription: Python pandas dataframe max in a group based on conditions on other columns


rawDescription: Python Compilation in Terminal

description: Python Compilation in Terminal


code:
lis = [[1,2,3],[4,5,6]]
foo = lis[:]
foo is lis              #lis and foo are different
[id(x) for x in lis]    #but inner lists are still same
[id(x) for x in foo]    #same IDs of inner lists, i.e foo[0] is lis[0] == True
foo[0][0] = 100         # modifying one will affect the other as well
lis[0],foo[0]

rawDescription: List being identified with another, using new items in the loop


rawDescription: Python: turn tuples into array

description: Python: turn tuples into array


rawDescription: Is a chained if...else expression in python faster than if..elif..else statements?


code: [dict(i.items()+j.items()+k.items()) for i, j, k in zip(list1, list2, list3)]

rawDescription: Merge dictionaries from multiple lists in Python


code:
def re_round(li, _prec=5):
     try:
         return round(li, _prec)
     except TypeError:
         return type(li)(re_round(x, _prec) for x in li)

rawDescription: Python Quickest way to round every float in nested list of tuples


code:
q = ndb.query()
cursor = ndb.Cursor(urlsafe=self.request.get('cursor'))
items, next_curs, more = q.fetch_page(10, start_cursor=cursor)
if more:
    next_c = next_curs.urlsafe()
else:
    next_c = None
self.generate('home.html', {'items': items, 'cursor': next_c })

rawDescription: Pagination in Jinja2 on Google App Engine


code: [line for line in csv.reader(data.split('\n')) if len(line) > 1]

rawDescription: shortest Python solution for creating list from csv string

description: Shortest Python solution for creating list from csv string


code:
@app.route('/login', methods=['GET', 'POST'])
def login():
    old_session = session.copy()
    ...
    login_user(user)
    session.update(old_session)
    ...

rawDescription: Copy user session when anonymous user logs in with Flask-Login


code:
import multiprocessing
import time

def worker(i):
    time.sleep(i)
    return i

if __name__ == "__main__":
    pool = multiprocessing.Pool()
    result = pool.map_async(worker, range(15))
    while not result.ready():
        print("num left: {}".format(result._number_left))
        time.sleep(1)
    real_result = result.get()
    pool.close()
    pool.join()

rawDescription: Counting total number of tasks executed in a multiprocessing.Pool during execution


code:
x = {}  # each time a dict object is created
y = {}

rawDescription: Python initialize multiple variables to the same initial value


code:
fruit = food_groups['fruit']
fruit_count = len(fruit)

rawDescription: Using counter on array for one value while keeping index of other values


rawDescription: Extract ip addres and other stuff from a bind log string using python


code: notepad_print('datafile.txt', {'szHeader' : ('', 1), 'szTrailer': ('', 1)})

rawDescription: hide header and footer on text files when direct print using win32 and python

description: Hide header and footer on text files when direct print using win32 and python


code:
n = len(b)
x = np.linalg.solve(A,b)
pos = np.where(x>=0.)[0]

while len(pos) < n:
    Ap = A[pos][:,pos]
    bp = b[pos]
    xp = np.linalg.solve(Ap, bp)
    x = np.zeros(len(b))
    x[pos] = xp
    pos = np.where(x>=0.)[0]

rawDescription: Numpy: Linear system with specific conditions. No negative solutions


rawDescription: Comparing each element between 2 sets?

description: Comparing each element between 2 sets


code:
import re
a = re.compile('a')
a
type(a)
repr(a)

rawDescription: Adding re.compile to list

description: Adding re.compile to list


rawDescription: How to make a sprite follow your mouse cursor using pygame?

description: Make a sprite follow your mouse cursor using pygame


code:
class MyUpdateDict(dict):
    def __init__(self, *args, **kwargs):
        self.update(*args, **kwargs)

    def __setitem__(self, key, value):
        # optional processing here
        super(MyUpdateDict, self).__setitem__(key, value)

    def update(self, *args, **kwargs):
        if args:
            if len(args) > 1:
                raise TypeError("update expected at most 1 arguments, "
                                "got %d" % len(args))
            other = dict(args[0])
            for key in other:
                self[key] = other[key]
        for key in kwargs:
            self[key] = kwargs[key]

    def setdefault(self, key, value=None):
        if key not in self:
            self[key] = value
        return self[key]

rawDescription: Subclassing Python dictionary to override __setitem__


code:
api_root = endpoints.api(name='myservice', version='v1', description='MyService API')

@api_root.collection(resource_name='first')
class FirstService(remote.Service):
  ...

@api_root.collection(resource_name='second')
class SecondService(remote.Service):
  ...

rawDescription: Cloud Endpoints with Multiple Services Classes


code:
import collections

class RevDict(collections.MutableMapping):

    def __init__(self):
        self.current_revno = 0
        self.dict = {}
        self.delta_index = [[]]

    def __setitem__(self, key, value):
        if key in self.dict:
            rlist = self.dict[key]
            last_revno = rlist[-1][0]
            rtup = (self.current_revno, value)
            if last_revno == self.current_revno:
                rlist[-1] = rtup
                # delta_index already has an entry for this rlist
            else:
                rlist.append(rtup)
                self.delta_index[self.current_revno].append(rlist)
        else:
            rlist = [(self.current_revno, value)]
            self.dict[key] = rlist
            self.delta_index[self.current_revno].append(rlist)

    def __getitem__(self, key):
        if not key in self.dict:
            raise KeyError(key)
        return self.dict[key][-1][1]

    def new_revision(self):
        self.current_revno += 1
        self.delta_index.append([])

    def roll_back(self, target_revno):
        assert 0 <= target_revno < self.current_revno
        for revno in xrange(self.current_revno, target_revno, -1):
            for rlist in self.delta_index[revno]:
                assert rlist[-1][0] == revno
                del rlist[-1]
        del self.delta_index[target_revno+1:]
        self.current_revno = target_revno

    def __delitem__(self, key):
        raise TypeError("RevDict doesn't do del")

    def keys(self):
        return self.dict.keys()

    def __contains__(self, key):
        return key in self.dict

    def iteritems(self):
        for key, rlist in self.dict.iteritems():
            yield key, rlist[-1][1]

    def __len__(self):
        return len(self.dict)

    def __iter__(self):
        return self.dict.iterkeys()

rawDescription: delta-dictionary/dictionary with revision awareness in python?

description: Delta-dictionary/dictionary with revision awareness in python


rawDescription: python parse bind configuration with nested curly braces

description: Python parse bind configuration with nested curly braces


code: ['This is also a tag to be retrieved']

rawDescription: How to retrieve a HTML tag based on a regular expression

description: Retrieve a HTML tag based on a regular expression


code: input[0:max(int(e) for e in (d['@Number'] for d in input))]

rawDescription: Removing duplicate records from a Python list


code: url(r'^$', TemplateView.as_view(template_name='pages/home.html') ,  name="home")

rawDescription: Cannot pass variables to django home template from another template in app


code: parameters = [getattr(root, 'OM%02d' % i) for i in range(1, 51)]

rawDescription: Loop a python script

description: Loop a python script


code:
df.index = df.index.astype(str)  # unicode in python 3?
s = StringIO()
df.to_csv(s, quoting=2)
s.getvalue()

rawDescription: Pandas, to_csv () to a specific format

description: Pandas, to_csv () to a specific format


code: layout.setSpacing(10) # 10 pixels between each layout item

rawDescription: PySide Qt: Auto vertical growth for TextEdit Widget, and spacing between widgets in a vertical layout


rawDescription: Counting number of elements in nested list


rawDescription: How to conduct complex operations using sympy?

description: Conduct complex operations using sympy


rawDescription: 2 dimensional array insertion in php python equivalent


code: data_3 = data_2.reset_index().merge(data_1.reset_index(), on=['Date','Product','Hub'], how='left')

rawDescription: Optimal filling of pandas DataFrame column by matching values in another DataFrame


code:
coef, n = [5, - 1.5], 50
xs = np.linspace(0, 10, n)[:,np.newaxis]
xs = np.hstack([xs, xs**2])
noise = 2 * np.random.randn(n)
ys = np.dot(xs, coef) + noise

rawDescription: curve fitting with integer inputs Python 3.3

description: Curve fitting with integer inputs Python 3.3


code:
cur = connection.cursor(pymysql.cursors.DictCursor)

# Query IDs.
cur.execute("SELECT id FROM history WHERE category = %s;", ['DATA'])
rows = cur.fetchall()
num_rows = int(cur.rowcount)

# Create a generator yielding the id field from each row.
x = (row['id'] for row in rows)

D = np.fromiter(iter=x, dtype=float, count=-1)

rawDescription: python3 work with values of fetchall and DictCursor

description: Python3 work with values of fetchall and DictCursor


code: all_phrases = collections.Counter(phrase for subject in subjects for phrase in phrases(subject))

rawDescription: Python: Finding unknown repeated word(s) in a list of strings


code:
if set(alphabet) == set(sentence):
    print('pangram')
else:
    print('not pangram')

rawDescription: Testing sentence against string of alphabet to see if all letters are in the sentence


code:
import numpy
data = numpy.array([0.0, 35., 2., 44., numpy.pi, numpy.sqrt(2.)])
data
numpy.where(data < 4)
numpy.where(data > 44.)
numpy.where(data >= 44.)

rawDescription: Filter array returning arguments

description: Filter array returning arguments


rawDescription: Ordering a list of items in place to compare clustering solutions


code: command= "TEST ACTION;client_service_platform;CONDITION_TYPE_TRIGGER_NAME CONDITION_OPERATOR_LIKE Weighted Successful,CONDITION_TYPE_HOST CONDITION_OPERATOR_EQUAL tt1scp1; OPERATION_TYPE_MESSAGE userid1,OPERATION_TYPE_EMAIL userid1,OPERATION_TYPE_EMAIL userid2"

rawDescription: python - elegantly handle sequence of multiple arguments

description: Python - elegantly handle sequence of multiple arguments


code:
import StringIO
import pandas as pd

df = """index  Benny  Daniel   Doris   Eric   Jack    Zoe
Age        75      30      95     25     28     23
Salary   2000    9000  100000  10000  12000  20000"""
df = pd.read_csv(StringIO.StringIO(df),sep="\s+").set_index('index')
d = {'Parrot lovers': ['Doris', 'Benny'], 'Tea Drinkers': ['Doris', 'Zoe'],\
 'Maintainance': ['Benny', 'Jack'], 'Coffee Drinkers': ['Benny', 'Eric'],\
 'Senior Management': ['Doris', 'Zoe', 'Jack']}

rawDescription: Grouping by multiple criteria in pandas

description: Grouping by multiple criteria in pandas


code: sav = sorted(sav, key=lambda x: int(x[3]))

rawDescription: Sorting an array by a number string (Python 3.4.2)


code:
drug_list = [ '17A', '96A', '56B']
dictonary = {}
for i in file_list:
    k = i.split('.')[-2]
    if k in drug_list:
        if k in dictonary:
            dictonary[k].append(i)
        else:
            dictonary[k] = [i]

rawDescription: combine two lists into a dictionary if a pattern matches

description: Combine two lists into a dictionary if a pattern matches


code:
from mpl_toolkits.axes_grid.axislines import SubplotZero
from matplotlib.transforms import BlendedGenericTransform
from matplotlib import patches
import matplotlib.pyplot as plt
import numpy

if 1:
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    ax.axhline(linewidth=1.7, color="k")
    ax.axvline(linewidth=1.7, color="k")

    plt.xticks([])
    plt.yticks([])

    ax.text(0, 1.05, r'$y$', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
    ax.text(1.03, 0, r'$x$', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    x = numpy.linspace(-1.499999999, 5, 10000)

    yy = numpy.log(2*x + 3)/2 + 3

    ax.plot(x, yy, linewidth=1.2, color="black")

    plt.ylim(-2, 5)
    plt.xlim(-5, 5)

    plt.arrow(5, -0.003, 0.1, 0, width=0.015, color="k", clip_on=False, head_width=0.12, head_length=0.12)
    plt.arrow(0.003, 5, 0, 0.1, width=0.015, color="k", clip_on=False, head_width=0.12, head_length=0.12)

    plt.text((numpy.e**(-6) - 3)/2, 0, r'$(\frac{1}{2} (e^{-6} - 3), 0)$', position=((numpy.e**(-6) - 3)/2 + 0.1, 0.1))
    plt.plot((numpy.e**(-6) - 3)/2, 0, 'ko')

    plt.text(0, numpy.log(3)/2 + 3, r'$(0, \frac{1}{2} \log_e{\left (3 \right )} + 3)$', position=(0.1, numpy.log(3)/2 + 3 + 0.1))
    plt.plot(0, numpy.log(3)/2 + 3, 'ko')

    plt.savefig('AnswersSA1a.png')

rawDescription: How to make 'fuller' axis arrows with matplotlib

description: Make 'fuller' axis arrows with matplotlib


code:
ar = numpy.array([['apple', 'b'],['c', 'd']])
ar
ar = numpy.array([['apple', 'banana'],['c', 'd']])
ar
ar.dtype

rawDescription: How to get type of multidimensional Numpy array elements in Python

description: Get type of multidimensional Numpy array elements in Python


code: sorted(yourlist, key=sort_key)

rawDescription: Very specific sorting in Python

description: Very specific sorting in Python


code:
suffix = ('st' if dt.day in [1,21,31]
               else 'nd' if dt.day in [2, 22]
               else 'rd' if dt.day in [3, 23]
               else 'th')
u'{date}{suffix}, {year} at {time}'.format(
    date=format_date(dt, "MMMM dd", locale='en'),
    suffix=suffix, year=dt.year,
    time=format_time(dt, "HH:mm V"))

rawDescription: Convert date to natural language in python?


code: #!/usr/bin/env python

rawDescription: How to use AJAX to receive content from Python

description: Use AJAX to receive content from Python


code:
import operator
from collections import Counter
from math import factorial
def npermutations(l):
    """From stackoverflow 16453188"""
    num = factorial(len(l))
    mults = Counter(l).values()
    den = reduce(operator.mul, (factorial(v) for v in mults), 1)
    return num / den

rawDescription: Speeding Up a Python While Loop

description: Speeding Up a Python While Loop


rawDescription: Finding a circle in an undirected graph

description: Finding a circle in an undirected graph


rawDescription: Can I efficiently swap two class instances by swapping __dict__?

description: Efficiently swap two class instances by swapping __dict__


code:
from functools import reduce # Okay, okay, 2 lines!
reduce (lambda r, x: r + [{'weekday_name': days_of_the_week[x]}] if x in days_of_the_week
                     else r + [{'weekday_name': r[-1]['weekday_name'], 'starting_time': x}] if len(r[-1]) == 3
                     else (r[-1].update({'starting_time': x}), r)[1] if len(r[-1]) == 1
                     else (r[-1].update({'ending_time': x}), r)[1],
        filter(lambda x: x in days_of_the_week or x[0].isdigit(), input_array), [])

rawDescription: python algorithm to be done in a pythonic fashion?

description: Python algorithm to be done in a pythonic fashion


code:
print(get_field_value(soup, 'Name'))  # prints 'AWO-Seniorenzentrum Kenten'
print(get_field_value(soup, 'Land'))  # prints 'Deutschland'

rawDescription: Trouble extracting data from html-doc with BeautifulSoup


code: [dict(zip(['label', 'value'], list(item))) for item in data]

rawDescription: Create a Json from a tuple - python

description: Create a Json from a tuple - python


code:
import Tkinter # Replace "Tkinter" with "tkinter" for Python 3.x.
tk = Tkinter.Tk()
tk.withdraw()
print(tk.selection_get())

rawDescription: Accessing selection clipboard from ipython


code:
def random_mix_rp1(seq_a, seq_b):
    iters = [iter(seq_a), iter(seq_b)]
    lens = [len(seq_a), len(seq_b)]
    while all(lens):
        r = random.randrange(sum(lens))
        itindex = r < lens[0]
        it = iters[itindex]
        lens[itindex] -= 1
        yield it.next()
    for it in iters:
        for x in it: yield x

rawDescription: Random list with rules

description: Random list with rules


code:
class CmdHandler(object):
    def __call__(self):
        return sum1.num_press(0)

bttn_0["command"] = CmdHandler()

rawDescription: Need help rewriting a Python function without using lambda


code:
np.random.randn2 = lambda *args, **kwarg: np.random.randn(*args).astype(kwarg.get('dtype', np.float64))
x = np.random.randn2(10, 10, dtype='f')

rawDescription: Can I specify a numpy dtype when generating random values?

description: Specify a numpy dtype when generating random values


rawDescription: Packing 4 Integers as ONE INTEGER?

description: Packing 4 Integers as ONE INTEGER


code:
MIDDLEWARE_CLASSES = (
    # ...
    'your_app.middleware.SqlPrintMiddleware',
    # ...
)

rawDescription: Is there a way to log the total number of queries made in a django view?


code:
import re
from scrapy.selector import Selector
inputtext = """<script type="text/javascript">
    window.DETAILS_PAGE_MAP_GLOBALS = {
        GOOGLE_MAPS_LONGITUDE: 55.4159330979,
        GOOGLE_MAPS_LATITUDE: 25.1549968578
    };
</script>"""
selector = Selector(text=inputtext, type="html")
regexp = re.compile(r'GOOGLE_MAPS_LONGITUDE:\s*(\d+\.\d+),\s*GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)')
selector.xpath('.//script[contains(text(), "window.DETAILS_PAGE_MAP_GLOBALS")]/text()').re(regexp)

rawDescription: python how to get the data of this script

description: Python how to get the data of this script


code:
def dyld_env(env, var):
    if env is None:
        env = os.environ
    rval = env.get(var)
    if rval is None:
        return []
    return rval.split(':')
def dyld_image_suffix(env=None):
    if env is None:
        env = os.environ
    return env.get('DYLD_IMAGE_SUFFIX')

def dyld_framework_path(env=None):
    return dyld_env(env, 'DYLD_FRAMEWORK_PATH')

def dyld_library_path(env=None):
    return dyld_env(env, 'DYLD_LIBRARY_PATH')

def dyld_fallback_framework_path(env=None):
    return dyld_env(env, 'DYLD_FALLBACK_FRAMEWORK_PATH')

def dyld_fallback_library_path(env=None):
    return dyld_env(env, 'DYLD_FALLBACK_LIBRARY_PATH')

def dyld_image_suffix_search(iterator, env=None):
    """For a potential path iterator, add DYLD_IMAGE_SUFFIX semantics"""
    suffix = dyld_image_suffix(env)
    if suffix is None:
        return iterator
    def _inject(iterator=iterator, suffix=suffix):
        for path in iterator:
            if path.endswith('.dylib'):
                yield path[:-len('.dylib')] + suffix + '.dylib'
            else:
                yield path + suffix
            yield path
    return _inject()

def dyld_override_search(name, env=None):
    # If DYLD_FRAMEWORK_PATH is set and this dylib_name is a
    # framework name, use the first file that exists in the framework
    # path if any.  If there is none go on to search the DYLD_LIBRARY_PATH
    # if any.

    framework = framework_info(name)

    if framework is not None:
        for path in dyld_framework_path(env):
            yield os.path.join(path, framework['name'])

    # If DYLD_LIBRARY_PATH is set then use the first file that exists
    # in the path.  If none use the original name.
    for path in dyld_library_path(env):
        yield os.path.join(path, os.path.basename(name))

def dyld_executable_path_search(name, executable_path=None):
    # If we haven't done any searching and found a library and the
    # dylib_name starts with "@executable_path/" then construct the
    # library name.
    if name.startswith('@executable_path/') and executable_path is not None:
        yield os.path.join(executable_path, name[len('@executable_path/'):])

def dyld_find(name, executable_path=None, env=None):
    """
    Find a library or framework using dyld semantics
    """
    for path in dyld_image_suffix_search(chain(
                dyld_override_search(name, env),
                dyld_executable_path_search(name, executable_path),
                dyld_default_search(name, env),
            ), env):
        if os.path.isfile(path):
            return path
    raise ValueError("dylib %s could not be found" % (name,))

def dyld_default_search(name, env=None):
    yield name

    framework = framework_info(name)

    if framework is not None:
        fallback_framework_path = dyld_fallback_framework_path(env)
        for path in fallback_framework_path:
            yield os.path.join(path, framework['name'])

    fallback_library_path = dyld_fallback_library_path(env)
    for path in fallback_library_path:
        yield os.path.join(path, os.path.basename(name))

    if framework is not None and not fallback_framework_path:
        for path in DEFAULT_FRAMEWORK_FALLBACK:
            yield os.path.join(path, framework['name'])

    if not fallback_library_path:
        for path in DEFAULT_LIBRARY_FALLBACK:
            yield os.path.join(path, os.path.basename(name))

rawDescription: Which paths does python ctypes module search for libraries on Mac OS?


code:
def dispatch_command(function, *args, **kwargs):
    ...
    parser = argparse.ArgumentParser(formatter_class=PARSER_FORMATTER)
    set_default_command(parser, function)
    dispatch(parser, *args, **kwargs)

rawDescription: Python’s argh library: preserve docstring formatting in help message


code:
import traceback
class MyFile(file):
    @staticmethod
    def open(*args, **kwargs):
        return MyFile(*args, **kwargs)

    def __init__(self, *args, **kwargs):
        self._file = self._open(*args, **kwargs)
        print('Opening %s from %s' % (
            self._file.name, ''.join(traceback.format_stack())))

    def close(self):
        print('Closing file %s from %s' % (
            self._file.name, ''.join(traceback.format_stack())))
        self._file.close()

# Now the monkey-patching
file = MyFile
MyFile._open = open
open = MyFile.open

o = open('hello', 'w+')

rawDescription: How can I find out which line of code is leaving a file open?

description: Find out which line of code is leaving a file open


rawDescription: how to remove "empty" space between subplots?

description: Remove "empty" space between subplots


rawDescription: Python 3.4.3 and PySqlite3 not Inserting content on Table


code:
import re
re.findall('http://.*?\.pdf', s)

rawDescription: Stripping links returned by beautfulsoup


code: [word.rstrip("$") for word in words]

rawDescription: Removing last character from each element in array (Python)


code:
from StringIO import StringIO
from csv import DictReader
fh = StringIO("""
id,case1,case2,case3

123,null,X,Y

342,X,X,Y

456,null,null,null

789,null,null,X
""".strip())
dr = DictReader(fh)
dr.next()

rawDescription: Python strings / match case

description: Python strings / match case


code:
length_d = defaultdict(set)
for value in d.values():
    length_d[len(value)].add(frozenset(value))
max(length_d)
length_d[max(length_d)]

rawDescription: Returning the longest set in a dictionary of sets?


code:
Number_List = [0,1,2,3,4,5,6,7,8,9]
for Index, Number in enumerate(Number_List[1:], start=1):
  Number_List[Index] = Number + 1

rawDescription: More elegant way for updating a slice of a list


code: df.index = pd.to_datetime(df.index)

rawDescription: Pandas dataframe reduce row values between specific dates


code:
import time
while True:
    print("TIME: %s" % time.time())
    time.sleep(5)

rawDescription: Execute script on Snort alert

description: Execute script on Snort alert


rawDescription: Filter images from tweets

description: Filter images from tweets


code:
x = 1
y = 2
def swap_xy():
  global x, y
  (x, y) = (y, x)

dis.dis(swap_xy)

rawDescription: Is a variable swap guaranteed to be atomic in python?


code:
columns = 0, 1, 9, 4, 6, 5, 19
getter = operator.itemgetter(*columns)
# ...
writer.writerow(getter(row))

rawDescription: manipulating TSV file

description: Manipulating TSV file


code:
event = QuantityChangedEvent(self.GetId())
self.GetEventHandler().ProcessEvent(event)
# or ...
#wx.PostEvent(self, event)

rawDescription: Generate a custom CommandEvent in wxPython


code:
a=tile((numpy.array([[[0, 0, 0]]])),(3,3,1))
resol_val1 = a.shape
resol_val1
a

rawDescription: python program to replicate the given matrix

description: Python program to replicate the given matrix


code:
for link in links:
    item = MyItem()
    url = link.select('span/a/@href').extract()
    item['link'] = allowed_domains[0] + url
    yield item

rawDescription: Adding text string to scraped data

description: Adding text string to scraped data


code:
import random
letters = list(still_to_scramble)
random.shuffle(letters)
scrambled = ''.join(letters)

rawDescription: Python splitting strings and jumbling the middle


code:
import multiprocessing,os,shutil
processes=16

in_queue = multiprocessing.Queue()
out_queue = multiprocessing.Queue()

def example_function(path, qin, qout):
    os.chdir(path)

    for i in iter(qin.get, 'stop'):
        print(os.getcwd())
        qout.put(i*i)

devshm='/dev/shm/'
# create processes & folders
procs = []
for i in range(processes):
    path = devshm+str(i)+'/'
    os.mkdir(path)
    #shutil.copy(some_files,path)

    procs.append(multiprocessing.Process(target=example_function, args=(path,in_queue, out_queue)))
    procs[-1].start()

# send input
for i in range(1000):
    in_queue.put(i)
# send stop signals
for i in range(processes):
    in_queue.put('stop')

# collect output
results = []
for i in range(1000):
    results.append(out_queue.get())

rawDescription: multiprocessing change current folder for every process

description: Multiprocessing change current folder for every process


code:
df = pd.concat([df1, df2])
df

rawDescription: Merge two CSV's with unique columns in python


code:
nrow = 1; ncol = 1;
fig, axs = plt.subplots(nrows=nrow, ncols=nrow)
axs = np.array(axs)

for ax in axs.reshape(-1):
  ax.set_ylabel(str(i))

rawDescription: matplotlib iterate subplot axis array through single list

description: Matplotlib iterate subplot axis array through single list


code:
class Whatever(object):

    def __init__(self, scale, getter=lambda x: 42):
        self.scale = scale
        self.getter = getter

    @property
    def y(self):
        return self.getter(self.scale)

plain = Whatever(33)
fancy = Whatever(47, lambda x: x*2)

rawDescription: Dynamic python properties

description: Dynamic python properties


code:
s1.update(s2[s2.notnull()])
s1

rawDescription: Overwriting (updating) a pandas Series with values from another Series?


code:
A = 1 / (2 * sigma^2)
B = mu / (2 * sigma^2)
C = mu^2 / sigma^2 + ln(height)

rawDescription: How can I perform a least-squares fitting over multiple data sets fast?

description: Perform a least-squares fitting over multiple data sets fast


code:
import re
st = "replace/    these**characters---all$$of&them....with_"
re.sub(r'[-/*$&.\s]+','_',st)

rawDescription: Filter a string for valid MySQL Column name


code:
@register.filter
def percent(value):
    if not is_number(value):
        return None
    return floatformat(Decimal(value) * Decimal(100.0), 2) + '%'

rawDescription: Calculate two values and calculate difference in percentage in Django


code: map(function, list)

rawDescription: Special chacacters in python 3.3

description: Special chacacters in python 3.3


code:
from django.contrib import admin

class TwitterUserAdmin(admin.ModelAdmin):
    form = TwitterUserForm

admin.site.register(TwitterUser, TwitterUserAdmin)

rawDescription: Making a CharField use a PasswordInput in the admin


code: create_shape('triangle', vertices = [( 0,0), (1, 10)])

rawDescription: Cascading optional parameters in Python

description: Cascading optional parameters in Python


code:
for i in range(1,100):
    X=io.imread('/home/oria/Desktop/more pics/'+str(i)+'.ppm')

rawDescription: Is it possible to use variable name in imread? Basic issue in Python


rawDescription: Move 3D plot z-axis label right (or left)


code:
try:
    event = events.get(False)
except Queue.Empty:
    pass

rawDescription: Calling While loop Function in __main__?

description: Calling While loop Function in __main__


code:
# 0 degrees Fahrenheit is -32 / 1.8 degrees Celsius
f = -32 / 1.8
s = str(f)
s
# floats between them...
fulpdiff(f, float(s))
# doubles between them...
dulpdiff(f, float(s))

rawDescription: floating point equality in Python and in general

description: Floating point equality in Python and in general


rawDescription: return all objects associated with a user

description: Return all objects associated with a user


rawDescription: Return the first item in a list matching a condition


rawDescription: Python: find maximum x-value and maximum y-value in text file


code:
class CustomClient(Client):
    def _render(self, request, formencode=False, realm=None):
        request.headers['User-Agent'] = "FooClient/1.0"
        return super()._render(request, formencode, realm)

rawDescription: Setting HTTP User-Agent header with requests-oauthlib


code:
class SystemAdmin(admin.ModelAdmin):
    form = EquipmentModelForm
    filter_horizontal = ('equipment',)

rawDescription: How to filter filter_horizontal in Django admin?

description: Filter filter_horizontal in Django admin


code: data[0] + data[1] # sum of the first and second numpy array

rawDescription: creating numpy arrays in a for loop

description: Creating numpy arrays in a for loop


code:
#! /usr/bin/env python3
from ctypes import *
dll = cdll.LoadLibrary('./libshmem.so')

class DataBlock(Structure):
    _fields_ = [('c', c_ubyte), ('l', c_ulong),
                ('f',c_float), ('d', c_double) ]

create_block = dll.create_block
create_block.argtypes = [c_char_p]
create_block.restype = c_int

write_block = dll.write_block
write_block.argtypes = [c_char_p, POINTER(DataBlock)]
write_block.restype = c_int

read_block = dll.read_block
read_block.argtypes = [c_char_p]
read_block.restype = DataBlock
#
# Create memory block
#
create_block(b"P0W")
#
# Write data block to shmem
#
in_data = DataBlock(ord('A'), 123, 12.32, 1.89721)
write_block(b"P0W", in_data)
#
# Read data block from shmem.
#
out_data = read_block(b"P0W")

print("{0} {1} {2} {3}".format(chr(in_data.c), in_data.l, in_data.f, in_data.d))
print("{0} {1} {2} {3}".format(chr(out_data.c), out_data.l, out_data.f, out_data.d))

rawDescription: Passing a C structure to a function in C DLL


code: d2 = dict((k, len(vallist)) for k, vallist in d.iteritems())

rawDescription: Read list of lists and output as dictionary, the count of values per key


code: [t for i, t in enumerate(l) if not any(is_subtuple(t, t2) for t2 in l[i+1:])]

rawDescription: Recursively reduce list of tuples

description: Recursively reduce list of tuples


code:
import random
x = random.randint(1, 8)
y = random.randint(1, 8)

if random.randint(0, 1): # flip coin to determine orientation
    grid[y-1][x] = 'X'
    grid[y][x] = 'X'
    grid[y+1][x] = 'X'
else:
    grid[y][x-1] = 'X'
    grid[y][x] = 'X'
    grid[y][x+1] = 'X'

rawDescription: Generating random X,Y coordinates in a grid


rawDescription: Extracting particular type of strings from a txt file


rawDescription: Not correct regular-expression in python


code:
locals()[s]
globals()[s]
getattr(other_object, s)

rawDescription: In Python, how do I get a variable via a string representation of the name of the variable?


rawDescription: Ordering items with known pair distances


code: map(hex,map(int, a))

rawDescription: How to use map for converting a list of decimals to hex in python

description: Use map for converting a list of decimals to hex in python


code: df['value_grp'] = (df.Values.diff(1) != 0).astype('int').cumsum()

rawDescription: How to use pandas to find consecutive same data in time series

description: Use pandas to find consecutive same data in time series


code:
from datetime import datetime, timedelta
s = "20150101000"
ts = datetime.strptime(s, '%Y%m%d%H%M')
for x in range(1,6):
    (ts - timedelta(minutes=x)).strftime('%Y%m%d%H%M')

rawDescription: python timestamp : Find all timestamps as string before 5 mins

description: Python timestamp : Find all timestamps as string before 5 mins


code:
@route('/update', method='POST')
def update():
    val1 = request.forms.get('par_1')
    val2 = request.forms.get('par_2')
    val3 = request.forms.get('par_3')
    val4 = request.forms.get('par_4')
    # Do something
    return template('page3', par_1=val1, par_2=val2, par_3=val3, par_4=val4)

rawDescription: Return valus from Python file to HTML buy press submit button?


code:
import re
target = '<a class="post-list-subject" href="(.*)">'
results = re.findall(target, htmltext)

rawDescription: Parsing HTML with str.split in Python

description: Parsing HTML with str.split in Python


code:
['-'.join(z[:i+1]) for i in range(2,len(z))]
['-'.join(z[:i+1]) for i in range(len(z)/2,len(z))]

rawDescription: Python way to split a particular string in a specific list


code:
def parse(line, regex, label):
    m = regex.match(line)
    if m:
        return ','.join([label] + m.groups())

rawDescription: Slow python parsing script

description: Slow python parsing script


rawDescription: Splitting by character using regular expressions


code:
if filename:
    with open(filename) as file:
        return file.read()

rawDescription: Get file path from askopenfilename function in Tkinter


code:
def reverse_file(of, rf):
    with open(of) as oldfile:
        with open(rf, "w") as reversefile:
            reversefile.write(oldfile.read()[::-1])

rawDescription: Python - Reversing a Whole File

description: Python - Reversing a Whole File


code:
# In your view somewhere
import json

def my_view(request):
    ...
    return render_to_response('my_template.html',{ 'my_json': json.dumps(my_dict) }, context_instance=RequestContext(request))

rawDescription: How to use following python dictionary in template using javascript?

description: Use following python dictionary in template using javascript


code:
class PollListView(ListView):
    queryset = Poll.objects.all().prefetch_related('votes')

rawDescription: Extra "row-level" data in ListView django


code:
df = pd.read_csv("jahmyst2.csv", header=None, names=range(3))
table_names = ["Inventory", "HP BladeSystem Rack", "Network Interface"]
groups = df[0].isin(table_names).cumsum()
tables = {g.iloc[0,0]: g.iloc[1:] for k,g in df.groupby(groups)}

rawDescription: Python Pandas - Read csv file containing multiple tables


code:
STATIC_URL = "/site_media/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, "site_media", "static")
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, "static_media"),
)

rawDescription: Django: css referencing media in static files (django dev / 1.3 / static files)


code:
c=random.sample(a_q, 3)
while c.count(q[i]) != 1:
    c=random.sample(a_q, 3)
random.shuffle(c)

rawDescription: Delete a string in a dictionary after it's shown


code:
from random import randint
help(randint)

rawDescription: Is there a Python function or method that displays object specifications?


code:
import json

with open('questions.json') as f:
    questions = json.load(f)
    for question in questions:
        print(question['question'])

rawDescription: Pythonic way to import multiple dictionaries from text file


code:
from sqlalchemy import func, over
sum_of_amount = label('sum_of_amount', func.sum(ModelClass.amount))
duplicates = over(func.count('*'),
                  partition_by=(ModelClass.category, sum_of_amount))
query = db_session.query(
    ModelClass.other_id,
    ModelClass.category,
    sum_of_amount,
    duplicates,
  ).group_by(
    ModelClass.other_id,
    ModelClass.category
  ).from_self(
    ModelClass.other_id,
    ModelClass.category,
    sum_of_amount
  ).filter(duplicates == 1)

rawDescription: SQLAlchemy filter out lines that are not distinct across multiple columns


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

def nonpythonic(previous_data, ix, iy, nx, ny):
    #this works, but is slow (for large arrays)
    new_data = np.zeros((ny,nx))
    for j in xrange(ny):
        for i in xrange(nx):
            #go through each item, check if it is within the bounds
            #and assign the data to the new_data array
            i_new = ix[j,i]
            j_new = iy[j,i]
            if ((i_new>=0) and (i_new<nx) and (j_new>=0) and (j_new<ny)):
                new_data[j,i]=previous_data[j_new,i_new]

    return new_data

def pythonic(previous_data, ix, iy):

    ny, nx = previous_data.shape
    iy_old, ix_old = np.indices(previous_data.shape)

    # note you must apply the same condition to both
    # index arrays
    valid = (iy >= 0) & (iy < ny) & (ix >= 0) & (ix < nx)

    new_data = np.zeros((ny,nx))

    new_data[iy_old[valid], ix_old[valid]] = previous_data[iy[valid], ix[valid]]
    return new_data

def main():
    #some 2D array:
    nx = 20
    ny = 30
    #array indices:
    iy, ix = np.indices((ny,nx))
    #modify indices (shift):
    iy = iy + 1
    ix = ix - 4
    #create some out of range indices (which might happen in my real scenario)
    iy[0,2:7] = -9999
    ix[0:3,-1] = 6666

    #some previous data which is the basis for the new_data:
    previous_data = np.ones((ny,nx))
    previous_data[2:8,10:20] = 2
    data_nonpythonic = nonpythonic(previous_data, ix, iy, nx, ny)
    data_pythonic = pythonic(previous_data, ix, iy)

    new_data = data_nonpythonic
    ef, axar = plt.subplots(1,2)
    im = axar[0].pcolor(previous_data, vmin=0,vmax=2)
    ef.colorbar(im, ax=axar[0], shrink=0.9)
    im = axar[1].pcolor(new_data, vmin=0,vmax=2)
    ef.colorbar(im, ax=axar[1], shrink=0.9)
    plt.show()
    print(np.allclose(data_nonpythonic, data_pythonic))

if __name__ == "__main__":
    main()

rawDescription: Shifting data in 2d array through shifted indices


code:
import re
text = "This is the oldest European-settled town in the continental U.S.\r\nExplore the town at your leisure\r\nUpgrade to add a scenic cruise aboard \r\n"
result = re.sub(r'[ .]*(?:\r?\n)+', '. ', text).strip()
print(result)

rawDescription: regex match certain characters but not with a period at the beginning

description: Regex match certain characters but not with a period at the beginning


code:
s1 = "foobar"
s2 = "fooba"
st1 = set(s1)
len(st1.intersection(s2)) == len(st1) - 1
s1 = "fooba"
s2 = "fooba"
st1 = set(s1)
len(st1.intersection(s2)) == len(st1) - 1

rawDescription: Finding words that contain all but one letter in string


code: forms = itertools.izip(base_forms, likes_forms)

rawDescription: How can I display multiple django modelformset forms in grouped fieldsets?

description: Display multiple django modelformset forms in grouped fieldsets


rawDescription: Python Beautiful Soup Print exact TD tag


rawDescription: RegEx Python Find and Print to a new document


rawDescription: Return rows only if all items of category are True


rawDescription: Dividing in Python

description: Dividing in Python


code:
class UserSerializer(serializers.ModelSerializer):
    referrer = serializers.CharField(max_length=300, allow_blank=True)
    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'referrer')
        write_only_fields = ('first_name', 'last_name', 'referrer')     #how to use this 'referrer' field to populate the Model fields?
        read_only_fields = ('id',)

rawDescription: DRF - ModelSerializer with a non-model write_only field


code:
newList2 = [
  [ j.Mirror(mirPlane) for j in i ]
  for i in otherElem
]

rawDescription: Nested list iterations

description: Nested list iterations


code:
item = driver.find_element_by_css_selector("form#analyze_url_form input[name=link]")
item.send_keys("http://finance.yahoo.com/news/skystar-bio-pharmaceutical-company-provides-133000048.html" + "\n")

rawDescription: Python: Selenium send_key not working

description: Python: Selenium send_key not working


rawDescription: Executing mathematical user inputed statements as code in Python 3


code: iter(fcn())

rawDescription: Is there a simpler construct for Python map(None, fcn())?


rawDescription: Numpy, 1:M joins on Arrays

description: Numpy, 1:M joins on Arrays


code:
import urllib2
import pandas as pd

link = 'http://www.ndbc.noaa.gov/data/dart_deployment_realtime/23228.dart'
df = pd.read_table(link, delimiter=r'\s+', skiprows=[1,3], header=1)

rawDescription: How to read Deep-ocean Assessment and Reporting of Tsunamis (DART®) data in python

description: Read Deep-ocean Assessment and Reporting of Tsunamis (DART®) data in python


code:
from myDirUtils import create_folder_structure, remove_folder, case_backup

def main_menu():
    finished = False
    while not finished:
        print("PLEASE CHOOSE AN OPTION BELOW BY ENTERING THE CORRESPONDING NUMBER: \n")
        print("[1]: CREATE CASE FOLDER STRUCTURE")
        print("[2]: DELETE X-WAYS CARVING FOLDER")
        print("[3]: BACK CASE UP TO SERVER")
        print("[4]: CLOSE PROGRAMME \n")
        try:
            choice = int(input("ENTER YOUR CHOICE HERE:"))
            if choice == 1:
                create_folder_structure()
            elif choice == 2:
                remove_folder()
            elif choice == 3:
                case_backup()
            elif choice == 4:
                finished = True
            else:
                print("INVALID CHOICE!! PLEASE ENTER A NUMBER BETWEEN 1-3")
        except ValueError:
            print("INVALID CHOICE!! PLEASE ENTER A NUMBER BETWEEN 1-3")

if __name__ == "__main__":
    # execute only if run as a script
    main_menu()

rawDescription: How can I call function from an imported module and then when i return to the original module use the text menu correctly?

description: Call function from an imported module and then when i return to the original module use the text menu correctly


code:
def compile_object(facets):
  displist = glGenLists(1)
  glNewList(displist, GL_COMPILE)
  # You can call glColor inside of glBegin/glEnd, so I moved them
  # outside the loop, which might improve performance somewhat
  glBegin(GL_TRIANGLES)
  for facet in facets:
    glColor( facet['color'] )
    for v in facet['vertices']:
      glVertex(v)
  glEnd()
  glEndList()
  return displist

rawDescription: OpenGL giving triangles colors in a list


code:
a = np.ma.array(np.zeros(4,int), mask=True, fill_value=-9999)
a[2]=3
a
a[2]=a.fill_value
a
np.ma.masked_object(a,a.fill_value)

rawDescription: Automatically mask np.ma array when item set equal to fill_value


rawDescription: Getting the date of the last day of this [week/month/quarter/year]


code:
import Image
im1 = Image.open("18-japanese-food-instagram-1.jpg")
im_small = im1.resize((width, height), Image.ANTIALIAS)
im_small.save("18-japanese-food-instagram-1_small.jpg")

rawDescription: Django: Download Image from URL, Resize it, append "small" to the end of the filename


rawDescription: Remove all occurrences of several chars from a string


rawDescription: adding the same object twice to a ManyToManyField

description: Adding the same object twice to a ManyToManyField


code:
df1 = pd.DataFrame(np.random.normal(size=8).reshape(4,2),index=[1,2,1,4],columns=['a','b'])
df2 = pd.DataFrame(np.random.normal(size=8).reshape(2,4),index=['c','d'],columns=[5,6,7,8])
df1.join(df2.T.set_index(df1.index))

rawDescription: Dataframe columns from Dataframe rows in Pandas


rawDescription: Match words that are not inside the characters < > using regular expressions


rawDescription: Python enum - getting value of enum on string conversion


code:
#!/usr/bin/env python
from subprocess import Popen, PIPE
import argparse
from os.path import expanduser, join
from time import time

def issue_command(command):
    process = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
    return process.communicate()

home = expanduser("~")
default_file = join(home, "command_log")

parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", type=argparse.FileType("a"), default=default_file)
parser.add_argument("-p", "--profile", action="store_true")
parser.add_argument("command", nargs=argparse.REMAINDER)
args = parser.parse_args()

if args.profile:
    start = time()
    out, err = issue_command(args.command)
    runtime = time() - start
    entry = "{}\t{}\n".format(" ".join(args.command), runtime)
    args.file.write(entry)
else:
    out, err = issue_command(args.command)
    entry = "{}\n".format(" ".join(args.command))
    args.file.write(entry)

args.file.close()

rawDescription: logging last Bash command to file from script

description: Logging last Bash command to file from script


code:
import Bio

INPUT  = "bio_input.fas"
OUTPUT = "bio_output.fas"

def main():
    records = Bio.SeqIO.parse(INPUT, 'fasta')
    filtered = (rec for rec in records if any(ch != 'N' for ch in rec.seq))
    Bio.SeqIO.write(filtered, OUTPUT, 'fasta')

if __name__=="__main__":
    main()

rawDescription: How to remove all-N sequence entries from fasta file(s)

description: Remove all-N sequence entries from fasta file(s)


code:
# read input file
with open(input_filename) as fh:
    lines = fh.readlines()

# sort lines
lines.sort(key=lambda line: int(line.split()[0]))

# write output file
with open(output_filename, 'w') as fh:
    fh.writelines(lines)

rawDescription: sorted() only sorting by first digit

description: Sorted() only sorting by first digit


code:
class Bar:
    def __init__(self, start, end, open, volume, high=None, low=None, last=None):
        self.start = start
        self.end = end
        self.open = open
        self.high = open if high is None else high
        self.low = open if low is None else low
        self.last = open if last is None else last
        self.volume = int(volume)

rawDescription: How to use the value of a non-default argument as the default value for a default argument in Python?

description: Use the value of a non-default argument as the default value for a default argument in Python


code:
from IPython.core.magic_arguments import argument, magic_arguments

@magic_arguments()
@argument('module')
def magic_import(self, arg):
    code = 'import {}'.format(arg)
    print('--> {}'.format(code))
    self.shell.run_code(code)

ip = get_ipython()
ip.define_magic('get', magic_import)

rawDescription: How to write an ipython alias which executes in python instead of shell?

description: Write an ipython alias which executes in python instead of shell


rawDescription: Print Difference Between Time in Ms

description: Print Difference Between Time in Ms


rawDescription: How to set key value pair of json output in scrapy?

description: Set key value pair of json output in scrapy


code:
async def tcp_client(host, port, loop=None):
    reader, writer = await asyncio.open_connection(host, port, loop=loop)
    async for line in reader:
        print(line.rstrip())
    writer.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(tcp_client('127.0.0.1', 42, loop))
loop.close()

rawDescription: asyncio queue consumer coroutine

description: Asyncio queue consumer coroutine


code:
import os
from setuptools import setup
from nvpy import nvpy

setup(
    name = "myscript",
    version = "1.0",
    author = "Charl P. Botha",
    author_email = "cpbotha@vxlabs.com",
    description = "Demo of packaging a Python script as DEB",
    license = "BSD",
    url = "https://github.com/cpbotha/nvpy",
    packages=['myscript'],
    entry_points = {
        'console_scripts' : ['myscript = myscript.myscript:main']
    },
    data_files = [
        ('share/applications/', ['vxlabs-myscript.desktop'])
    ],
    classifiers=[
        "License :: OSI Approved :: BSD License",
    ],
)

rawDescription: debianzing a python program to get a .deb

description: Debianzing a python program to get a .deb


code:
def weighted_random_choice(chromosomes):
    max = sum(chromosome.fitness for chromosome in chromosomes)
    pick = random.uniform(0, max)
    current = 0
    for chromosome in chromosomes:
        current += chromosome.fitness
        if current > pick:
            return chromosome

rawDescription: Fitness proportionate selection (roulette wheel selection) in Python


code:
my_func_1(5)
my_func_1(5, square=True)
my_func_1(5, plus_3=True, square=True)
my_func_1(5, cube=True)

rawDescription: difference bewteen *args and **args in python?

description: Difference bewteen *args and **args in python


code:
def render(nodes, parent = 0):
    if parent not in nodes:
        return
    print('
')
    for n in nodes[parent]:
        print('
Node %d
' % n)
        render(nodes, n)
    print('
')

rawDescription: Nested <ul><li> navigation menu using a recursive Python function


rawDescription: Stripping line edings before appending to a list?


code: datetime.datetime.now().__format__('The current month is %B')

rawDescription: How do I convert date to Day/Month/Year (20/Jan/2012) in python

description: Convert date to Day/Month/Year (20/Jan/2012) in python


code:
img = gimp.image_list()[0]
c = img.layers[0]
c
pdb.gimp_item_get_children(c)
c2 = gimp.Item.from_id(4)
c2

rawDescription: Get sublayers from group layer with Python in Gimp


code: SHRINKSNAKE = pygame.USEREVENT+0

rawDescription: How to make a Python function sleep some time while the rest of the game continues?

description: Make a Python function sleep some time while the rest of the game continues


rawDescription: Python urllib2 request error

description: Python urllib2 request error


code:
from subprocess import Popen, PIPE

p = Popen(['a.out'], shell=True, stdout=PIPE, stdin=PIPE)
for ii in range(10):
    value = str(ii) + '\n'
    #value = bytes(value, 'UTF-8')  # Needed in Python 3.
    p.stdin.write(value)
    p.stdin.flush()
    result = p.stdout.readline().strip()
    print(result)

rawDescription: input to C++ executable python subprocess

description: Input to C++ executable python subprocess


code: self.data[y*width + x]

rawDescription: In which format does PIL's putdata need the data to be?


code: x,y,z = (float(f) for f in p.split())

rawDescription: Breaking an XML string into three floats


rawDescription: python setuptools install_requires is ignored when overriding cmdclass

description: Python setuptools install_requires is ignored when overriding cmdclass


code:
class hashablelist(list):
    def __hash__(self):
        return hash(tuple(self))

x = hashablelist(['a', 'b', 'c'])
y = hashablelist(['a', 'b', 'd'])
d = {}
d[x] = 'foo'
d[y] = 'bar'
d.items()
y[2] = 'c'
d.items()
del d[x]
del d[y]
d.items()
x in d
y in d
x in d.keys()
y in d.keys()

rawDescription: How to use a list of strings [which may contain any character] as keys?

description: Use a list of strings [which may contain any character] as keys


code:
try:
    del dict_1_hour[timestamp]
except KeyError:
    pass

rawDescription: How to release a dataframe in spark?

description: Release a dataframe in spark


code:
def check_running(self, script):
    """Return True if the script is running, False otherwise."""

rawDescription: Docstrings - one line vs multiple line

description: Docstrings - one line vs multiple line


code:
import re

pattern = re.compile(r"^Some \w+ text.$")

elements = driver.find_elements_by_css_selector("div.some_class")
for element in elements:
    match = pattern.match(element.text)
    if match:
        print(element.text)

rawDescription: Can I find an element using regex with Python and Selenium?

description: Find an element using regex with Python and Selenium


code:
import pickle
f = open('my_classifier.pickle', 'rb')
classifier = pickle.load(f)
f.close()

rawDescription: Save Naive Bayes Trained Classifier in NLTK


code:
def x_o_r(a, b):
    return format(int(a, 2) ^ int(b, 2), '08b')

[x_o_r(a, b) for a, b in product(x, repeat=2)]

rawDescription: Python - Result returns generator instead of list (comprehension)


code:
var = tk.StringVar()
rb0 = tk.Radiobutton(..., variable=var, value="in", text="in")
rb1 = tk.Radiobutton(..., variable=var, value="out", text="out")
rb2 = tk.Radiobutton(..., variable=var, value="unassigned", text="not assigned")

var.trace("w", lambda name1, name2, op, index=i, var=var:
          on_radiobutton(var, index))

rawDescription: Python - arrays of tkinter widgets changing with radiobutton clicks


code: setUserData(user, form)

rawDescription: Is there a better way to write these in python?


rawDescription: What is the difference between `super(...)` and `return super(...)`?


code: sum(row['keyA'] for row in rows)

rawDescription: Python in memory table data structures for analysis (dict, list, combo)


code: uniq = sorted(set(logf))

rawDescription: Summarizing log file to unique entries only


code: query = """SELECT element FROM table2 WHERE id IN (%s,%s,%s) """

rawDescription: Retrieving and selecting binary values from Mysql with Python 3


code: ['sad and unhappy']

rawDescription: How do I extract patterns from lists of POS tagged words? NLTK

description: Extract patterns from lists of POS tagged words? NLTK


code:
l = ['2,alex', '5,james', '3,ben']
l.sort(key=lambda x: int(x.split(',')[0]))
l

rawDescription: Python: Alphabetically sorting a list with letters and numbers in


code:
from os import curdir
from os.path import join as pjoin

from http.server import BaseHTTPRequestHandler, HTTPServer

class StoreHandler(BaseHTTPRequestHandler):
    store_path = pjoin(curdir, 'store.json')

    def do_GET(self):
        if self.path == '/store.json':
            with open(self.store_path) as fh:
                self.send_response(200)
                self.send_header('Content-type', 'text/json')
                self.end_headers()
                self.wfile.write(fh.read().encode())

    def do_POST(self):
        if self.path == '/store.json':
            length = self.headers['content-length']
            data = self.rfile.read(int(length))

            with open(self.store_path, 'w') as fh:
                fh.write(data.decode())

            self.send_response(200)

server = HTTPServer(('', 8080), StoreHandler)
server.serve_forever()

rawDescription: Simple Python Webserver to save file

description: Simple Python Webserver to save file


rawDescription: Coverting Hex array to Decimal in Python


code:
[{'ABC12346': {'serial_num': 'ABC12346', 'site_location': 'Europe'}},
 {'SER12345': {'serial_num': 'SER12345', 'site_location': 'North America'}},
 {'SER12346': {'serial_num': 'SER12346', 'site_location': 'North America'}},
 {'ABC12345': {'serial_num': 'ABC12345', 'site_location': 'South America'}},
 {'SER12347': {'serial_num': 'SER12347', 'site_location': 'South America'}}]

rawDescription: Sort Dictionary of Dictionaries on multiple child dictionary values


code:
list=[1,2,3,4]
# 3 in list evaluates to a boolean value, which is then assigned to the variable A
A=3 in list
if A:
    print('True')

rawDescription: Using a Boolean in an if statement

description: Using a Boolean in an if statement


code:
where = np.zeros(len(a),dtype=bool)
where[3:21] = True
plt.fill_between(np.arange(len(a)),a,where=where)

rawDescription: Colouring the area under curve of plotted list


code:
def get_files_arrays(folder_file_dict=folder_file_dict):
    for folder_name_dict in folder_file_dict.itervalues():
        for filenames_array in folder_name_dict.itervalues():
            yield filenames_array

rawDescription: Python multi-threaded processing with limited CPU/ports


code:
with open("file.csv") as fin:
    fin.next()
    total = sum(int(r[1]) for r in csv.reader(fin))

rawDescription: Sum a csv column in python

description: Sum a csv column in python


code:
class Movie(Base, MyBaseClass, MetadataMixin('Movie')):
    pass

rawDescription: SQLAlchemy: Multiple Inheritance with dynamic 'association_proxy' creator function


code:
import timeit
import matplotlib.pyplot as plt

n = np.arange(10, 1000, 10)
op = np.zeros(n.shape[0])
me = np.zeros(n.shape[0])
th = np.zeros(n.shape[0])
jp = np.zeros(n.shape[0])
for j, size in enumerate(n) :
    a = np.random.rand(size, size)
    b, c = indices = np.sort(np.random.randint(size + 1,
                                               size=(2, size)), axis=0)
    np.testing.assert_almost_equal(sliced_sum_op(a, b, c),
                                   sliced_sum(a, b, c))
    np.testing.assert_almost_equal(sliced_sum_op(a, b, c),
                                   sum_between2(a, b, c))
    np.testing.assert_almost_equal(sliced_sum_op(a, b, c),
                                   sum_between_mmult(a, b, c))

    op[j] = timeit.timeit('sliced_sum_op(a, b, c)',
                          'from __main__ import sliced_sum_op, a, b, c',
                          number=10)
    me[j] = timeit.timeit('sliced_sum(a, b, c)',
                          'from __main__ import sliced_sum, a, b, c',
                          number=10)
    th[j] = timeit.timeit('sum_between2(a, b, c)',
                          'from __main__ import sum_between2, a, b, c',
                          number=10)
    jp[j] = timeit.timeit('sum_between_mmult(a, b, c)',
                          'from __main__ import sum_between_mmult, a, b, c',
                          number=10)
plt.subplot(211)
plt.plot(n, op, label='op')
plt.plot(n, me, label='jaime')
plt.plot(n, th, label='thorsten')
plt.plot(n, jp, label='japreiss')
plt.xlabel('n')
plt.legend(loc='best')
plt.show()

rawDescription: Sum between pairs of indices in 2d array


code:
with  open(fileToParse, "r") as f:
    for line in f:
        if not line.strip():
            continue
        lineDateTime = datetime.datetime(lineYear, lineMonth, lineDay, lineHour, lineMin, lineSec)
        if startDateTime < lineDateTime < endDateTime:
            writeFile.write(line + "\n")
        elif lineDateTime > endDateTime:
            break

rawDescription: Efficiently parsing text file for datetimes


code:
from fabric.api import run
def runmyprogram():
    run('./program.sh > output 2> /dev/null < /dev/null &')

rawDescription: remotely start Python program in background

description: Remotely start Python program in background


code:
import cPickle as pickle
from sklearn.externals import joblib
from sklearn import preprocessing

le = preprocessing.LabelEncoder()
train_x = [0,1,2,6,'true','false']
le.fit_transform(train_x)

# Save your encoding
joblib.dump(le, '/path/to/save/model')
# OR
pickle.dump(le, open( '/path/to/model', "wb" ) )

# Load those encodings
le = joblib.load('/path/to/save/model')
# OR
le = pickle.load( open( '/path/to/model', "rb" ) )

# Then use as normal
new_x = [0,0,0,2,2,2,'false']
le.transform(new_x)
# array([0, 0, 0, 1, 1, 1, 3])

rawDescription: How to pre-process new instances for classification, so that the feature encoding is the same as the model with Scikit-learn?

description: Pre-process new instances for classification, so that the feature encoding is the same as the model with Scikit-learn


code:
import logging

logging.basicConfig(filename="test.log", level=logging.DEBUG)
logger = logging.getLogger("testlogger")

for i in range(0, 1000000):
    logger.info("iteration: %d", i)

rawDescription: Python logging extremely slow on Linux server... but fast on Linux development VM?


code: delimitedList(oneOf("alpha beta gamma"), '|')

rawDescription: pyparsing matching any combination of specified Literals

description: Pyparsing matching any combination of specified Literals


code:
from __future__ import print_function
for word in "Monty Python":
    print(word,end=' ')

rawDescription: Strings Iteration - Printing a String Horizontally


code: re.sub(r'\B[A-Z]', lambda x: '_' + x.group().lower() , re.sub(r'^[A-Z]', lambda m: m.group().lower(), 'AbcdEfgh'))

rawDescription: how to detect case change in python text and insert underscore on change location?

description: Detect case change in python text and insert underscore on change location


rawDescription: How to write a lot of nested 'for' loops (Recursively)

description: Write a lot of nested 'for' loops (Recursively)


code:
df.iloc[::2] + df.iloc[1::2].values
df.iloc[::2].values + df.iloc[1::2]

rawDescription: simplifying routine in python with numpy array or pandas

description: Simplifying routine in python with numpy array or pandas


rawDescription: Numpy - create matrix with rows of vector


rawDescription: Omit one parameter from view in Django?

description: Omit one parameter from view in Django


code:
def nonlinear_invert(f, x, y, z):
    def wrapped_func(observation_points, a, b, c):
        x, y, z = observation_points
        return func(x, y, z, a, b, c)

    xdata = np.vstack([x, y, z])
    model, cov = opt.curve_fit(wrapped_func, xdata, f)
    return model

rawDescription: Solving non-linear equations in python

description: Solving non-linear equations in python


rawDescription: What is the equivalent of MATLAB's repmat in NumPy


rawDescription: How to truncate the values of a 2D numpy array

description: Truncate the values of a 2D numpy array


code:
def login(request):
    # Do login stuff
    if user.is_active():
        request.session['categories'] = [ c.name for c in Category.objects.filter(author=request.user)] # add to the session
    return redirect('/somepage')

rawDescription: how to to display the category user created by the current user on every page

description: To display the category user created by the current user on every page


code:
from timeit import timeit
l1 = [''] * 1000
l2 = [''] * 1000
timeit(lambda:l1 == l2)
timeit(lambda:l1.count('') == len(l1))

rawDescription: in python which would be the fastest way to compare / test with an lists

description: In python which would be the fastest way to compare / test with an lists


code:
for sub in flatten(*a):
    yield sub

rawDescription: Recursive call in python seems not to descend


code:
from d import d
d.var = 5
d.printVar()

rawDescription: Confused by python package scoping

description: Confused by python package scoping


rawDescription: Why is complex class not optimized to cache objects in Python?


code:
df["timestamp"].diff()
df["timestamp"].diff() > pd.Timedelta(minutes=30)
(df["timestamp"].diff() > pd.Timedelta(minutes=30)).cumsum()

rawDescription: How to Partition Pandas DataFrame using DateTime


code:
def _generate_order_by(self, order_spec, query):
    """ Calculate the order by clause to use in SQL based on a set of
    model fields. """
    if order_spec != 'default_partner_name':
        return super(product_product, self)._generate_order_by(order_spec,
                                                               query)
    return """
        ORDER BY
        (
        select  min(supp.name)
        from    product_supplierinfo supinf
        join    res_partner supp
        on      supinf.name = supp.id
        where   supinf.product_id = product_product.id
        ),
        product_product.default_code
        """

rawDescription: Sorting OpenERP table by functional field


code:
from itertools import islice
nested_lst = [u'Tom', ['50', ' 1.85', ' 112', ' 60', ' 1.90', ' 115']]
x=nested_lst[1]
it=iter(x)
nested_lst[1]=[tuple( islice(it,3) ) for i in xrange(len(x)/3)]
nested_lst

rawDescription: Merging some elements inside a list

description: Merging some elements inside a list


code:
def mod(a,b):
    while a > b:
        a -= b
    return a

rawDescription: Project Euler 104: Need help in understanding the solution


code:
# Python 3
from collections import Counter

with open("corpus.txt", encoding="latin_1") as inf:
    wordcount = Counter(line.rstrip() for line in inf)

with open("lexic.txt", "w", encoding="utf-8") as outf:
    outf.write('Palabra\tTag\tApariciones\n')
    for word,count in wordcount.items():
        outf.write("{}\t{}\n".format(word, count))

rawDescription: Bad output format in .txt file

description: Bad output format in .txt file


code: line1 = line

rawDescription: Search for a word in two files and print the the two lines with tabular separation


code:
# make a COPY of the environment
environ = dict(os.environ)
# remove the query string from it
del environ['QUERY_STRING']
# parse the environment
form = cgi.FieldStorage(environ=environ)
# form contains no arguments from the query string!

rawDescription: Accept parameters only from POST request in python


code:
import pickle
with open("y.txt", "w") as outf:
    pickle.dump(y, outf)

rawDescription: Python - write symbolic expression (sympy) to txt file


code:
names_matrix = ([['lname', 'fname', 'city', 'state', 'zipcode'],
             ['Zdolfalos', 'Johnson', 'Terrell', 'Wilson', 'Key', 'Smith',
              'Alfonso'],
             ['Fred', 'Malcom', 'Monkey', 'Wilson', 'LeDoor', 'Jim Bob', 'Ralph'],
             ['Charlotte', 'Monroe', 'Broken Pine', 'Hogwart', 'Spot in Road',
              'Denver','Gastonia'],
             ['NC', 'NC', 'SC', 'VA', 'AL', 'NC', 'NC' ],
             ['28210', '28337', '28974', '27457', '36827', '28037', '28559'] ])
fixed_names = zip(*names_matrix[1:])
userFirstName = 'Fred'
userLastName = 'Zdolfalos'
for row in fixed_names:
    if userLastName in row and userFirstName in row:
        print(list(row))
    else:
        print('User Not Found!')

rawDescription: Python For In Loop Matrix for User Input


code:
# A.models.py
from polymorphic import PolymorphicModel

class Event(PolymorphicModel):
    commom_field = models.BooleanField()

    # no longer abstract

class SubEventA(Event):
    email = models.EmailField(unique=True)

class SubEventB(Event):
    title = models.TextField()

class SubEventC(Event):
    number = models.IntegerField(default=10)

# B.models.py

# it doesnt have to be polymorphic to reference polymorphic models
class OtherModel(models.Model):
    event = models.ForeignKey('A.Event')

rawDescription: Django model subclassing approaches

description: Django model subclassing approaches


code:
import numbers
def mapped(x):
    if isinstance(x,numbers.Number):
        return x
    for tpe in (int, float):
        try:
            return tpe(x)
        except ValueError:
            continue
    return 0
for sub  in someData:
    sub[:] = map(mapped,sub)

print(someData)
[[1.0, 4, 7, -50], [0, 0, 0, 12.5644]]

rawDescription: Converting all non-numeric to 0 (zero) in Python


code: newlist = [el for el in origlist if el]

rawDescription: elegant list manipulation in python

description: Elegant list manipulation in python


code: from __future__ import print_function

rawDescription: Python: using Perl style logical not and boolean negation


code:
# grab a player
p = Player.objects.get(name='Tom')

# see what rounds this player played in
rounds_played = p.rounds.all()

# who did this player play against?
[r.players for r in rounds_played]

# to see all rounds this player won
p.round_winner.all()

rawDescription: Modelling a swiss tournament in Django

description: Modelling a swiss tournament in Django


code: Query('"%s"' % ''.join(chr(i) for i in xrange(128)).replace('"','').replace('\\', ''))

rawDescription: Escaping search queries for Google's full text search service


code:
with lasfile.File(inFile, None, 'r') as f:
     # missing part
     points = [line.split(',')[:2] for line in lasfile]

rawDescription: Reading all lines in a file with list comprehension


code: x = data[row][colorder[col]]

rawDescription: Matrix data structure

description: Matrix data structure


code:
from collections import OrderedDict
pargs = ['arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6', 'arg7', 'arg8', 'arg9']
indices = ((x,y) for x in range(3) for y in range(3))
result = [OrderedDict([('event',p), ('i',i), ('j',j)]) for p,(i,j) in zip(pargs, indices)]
print(result) # [OrderedDict([('event', 'arg1'), ('i', 0), ('j', 0)]), OrderedDict([('event', 'arg2'), ('i', 0), ('j', 1)]), OrderedDict([('event', 'arg3'), ('i', 0), ('j', 2)]), OrderedDict([('event', 'arg4'), ('i', 1), ('j', 0)]), OrderedDict([('event', 'arg5'), ('i', 1), ('j', 1)]), OrderedDict([('event', 'arg6'), ('i', 1), ('j', 2)]), OrderedDict([('event', 'arg7'), ('i', 2), ('j', 0)]), OrderedDict([('event', 'arg8'), ('i', 2), ('j', 1)]), OrderedDict([('event', 'arg9'), ('i', 2), ('j', 2)])]

rawDescription: Building up a list of dictionaries from a few lists in Python


code:
import dis
dis.dis(f)

rawDescription: Assign variable to local scope of function in Python


code:
def the_decorator(arg1, arg2):

    def _method_wrapper(view_method):

        def _arguments_wrapper(request, *args, **kwargs) :
            """
            Wrapper with arguments to invoke the method
            """

            #do something with arg1 and arg2

            return view_method(request, *args, **kwargs)

        return _arguments_wrapper

    return _method_wrapper

rawDescription: Django add optional arguments to decorator


code:
def clean_username(self):
    username = self.cleaned_data['username']
    try:
        User.objects.get(username=username)
    except User.DoesNotExist:
        raise forms.ValidationError("The username you have entered does not exist.")
    return username

rawDescription: Separately validating username and password during Django authentication


code:
H, W = 5, 5
np.random.randint(-1, 2, size=(H,1))

rawDescription: Numpy array filled with random numbers so that you only change the value by one along the x/y axis


code:
tokens = PT().tokenize("Hei på deg øyerusk, du er meg en gammel dust, neida neida, det er ikke helt sant da."
                             "Men du, hvorfor så brusk, ikke klut i din susk på en runkete lust")

rawDescription: Utf-8 issues with python and nltk

description: Utf-8 issues with python and nltk


code: result.to_csv("Historical.csv", date_format='%d/%m/%Y', header = None)

rawDescription: Trouble Parsing data from JSON response with Python/Pandas Library


code:
class unicode(unicode):
    def __repr__(self):
            return __builtins__.unicode.__repr__(self).lstrip("u")

unicode('a')

rawDescription: Suppress the u'prefix indicating unicode' in python strings


code:
def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('users',
    sa.Column('uuid', sa.GUID(), nullable=False),
    sa.Column('email', sa.String(), nullable=False),
    sa.Column('password', sa.String(), nullable=False),
    sa.Column('created_on', sa.DateTime(timezone=True), nullable=True),
    sa.Column('last_login', sa.DateTime(timezone=True), nullable=True),
    sa.PrimaryKeyConstraint('uuid'),
    sa.UniqueConstraint('email'),
    sa.UniqueConstraint('uuid')
    )
    ### end Alembic commands ###

rawDescription: Alembic --autogenerate producing empty migration


code:
import contextlib

@contextlib.contextmanager
def time_measure(ident):
    tstart = time.time()
    yield
    elapsed = time.time() - tstart
    logger.debug("{0}: {1} ms".format(ident, elapsed))

rawDescription: Decorator to time specific lines of the code instead of whole method?


code:
d = {k: {a: int(b) for a, b in (v[i:i+2] for i in range(0, len(v), 2))}
     for k, v in d.items()}

rawDescription: merge to dictionaries preserving different values

description: Merge to dictionaries preserving different values


code:
result = [''.join(element) for element in data]
print(result)

rawDescription: List conversion/transformation

description: List conversion/transformation


code:
import tkinter as tk

# --- functions ---

def move(x, y):
    global empty_x, empty_y, game_running

    if game_running:
        # check and move tile
        if (empty_x, empty_y) in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:

            board[empty_y][empty_x] = board[y][x]
            board[y][x] = ' '

            buttons[empty_y][empty_x]['text'] = buttons[y][x]['text']
            buttons[y][x]['text'] = ' '

            empty_x = x
            empty_y = y

            if won():
                # show label "Hurray"
                label.lift()
                game_running = False

    else:
        # start game again

        shuffle() # shuffle tiles

        game_running = True

        # hide label
        label.lower() # or frame.lift()

def won():

    number = 0

    for y, row in enumerate(board):
        for x, char in enumerate(row, 1):
            number += 1
            if number == 9 and char == ' ':
                #print('A |%s| %d' % (char, number))
                return True
            elif char != str(number):
                #print('B |%s| %d' % (char, number))
                return False

    return True

def shuffle():
    # TODO: shuffle tiles

    # it can't put tiles in random places
    # because it can create game without solution

    pass

# --- data ---

board = [
    ['1', '2', '3'],
    ['4', '5', '6'],
    ['7', '8', ' '],
]

empty_x = len(board[0])-1
empty_y = len(board)-1

# --- main ---

root = tk.Tk()

# create label hidden behide frame

label = tk.Label(root, text="Hurray!\n\n(click any button to play again)", bg="red")
label.grid(row=0, column=0, ipadx=20, ipady=20)

# create frame with buttons to fast show/hide label

frame = tk.Frame(root)
frame.grid(row=0, column=0) # the same (row,col) to hide label

buttons = []

for y, row in enumerate(board):

    buttons_row = []

    for x, char in enumerate(row):

        b = tk.Button(frame, text=char, width=10, height=5, command=lambda x=x,y=y:move(x,y))
        b.grid(row=y, column=x)

        buttons_row.append(b)

    buttons.append(buttons_row)

# start game

shuffle() # shuffle tiles
game_running = True

# start "the engine"

root.mainloop()

rawDescription: Interactive game board with Tkinter Python - label updating


code:
register = template.Library()

def through(A1, b):
    t = "%s" % (C.objects.get(b=b, a=A1).in_stock)
    return t

register.filter(through)

rawDescription: Django Access Data in "through" table given both entities


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))

axes[0].plot(range(1, 4))
axes[1].plot(range(10, 40, 10), range(1, 4))

for ax in axes:
    ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
                xytext=(-5, 5), textcoords='offset points',
                ha='right', va='bottom')
plt.show()

rawDescription: Python/Matplotlib - How to put text in the corner of equal aspect figure


code: print('\033c', end=None)

rawDescription: How to clear terminal (Mac osx) scrollback?

description: Clear terminal (Mac osx) scrollback


rawDescription: Reads a word and prints all substrings, sorted by length in Python


code:
class Mojaklasa: # unless there are more methods I would not use a class
    def przenumeruj_pdb(self):
        nazwa = raw_input('Podaj nazwe pliku: ')
        with open(nazwa) as plik, open("out.txt", "w") as write: # with will close your iles
            for line in plik: # iterate over file object
                j = line.split()
                if len(j) > 5 and j[0] == "ATOM": # same as nested if's
                    write.write("{}\n".format(j[5].translate(None, ascii_letters)))

rawDescription: Converting str to int in Python, only numbers w/o characters


rawDescription: Python Tkinter - hide a widget after some time


code:
from django import template
from django.db.models import get_model
register=template.Library();

@register.simple_tag(takes_context=True)
def get_latest_news(context,context_variable):
    context[context_variable]=get_model('News','Article').objects.order_by('-publish_date')[0,10]
    return ''

rawDescription: How to handle additional blocks in Django?

description: Handle additional blocks in Django


code:
grouped = {}
for tup in information:
    grouped.setdefault(tup[0], []).append(tup)

bestvalues = {}
for group in grouped.itervalues():
    best = max(group, key=lambda g: g[2])
    bestvalues[tuple(best[:2])] = best[2]

bestvalues

rawDescription: Get the max value for given keys in a dictionary?


code:
import lxml.etree as ET

content = '''\
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE html>
<h:html xmlns:h="http://www.w3.org/1999/xhtml" xmlns:ml="http://foo">
  <h:head>
    <h:title>MathJax Test Page</h:title>
    <h:script type="text/javascript"><![CDATA[
      function test() {
        alert(document.getElementsByTagName("p").length);
      };
    ]]></h:script>
  </h:head>
  <h:body onload="test();">
    <h:p>test</h:p>
    <ml:foo></ml:foo>
  </h:body>
</h:html>
'''
dom = ET.fromstring(content)

xslt = '''\
<xsl:stylesheet version="1.0"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>

<!-- identity transform for everything else -->
<xsl:template match="/|comment()|processing-instruction()|*|@*">
    <xsl:copy>
      <xsl:apply-templates />
    </xsl:copy>
</xsl:template>

<!-- remove NS from XHTML elements -->
<xsl:template match="*[namespace-uri() = 'http://www.w3.org/1999/xhtml']">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="@*|node()" />
    </xsl:element>
</xsl:template>

<!-- remove NS from XHTML attributes -->
<xsl:template match="@*[namespace-uri() = 'http://www.w3.org/1999/xhtml']">
    <xsl:attribute name="{local-name()}">
      <xsl:value-of select="." />
    </xsl:attribute>
</xsl:template>
</xsl:stylesheet>
'''

xslt_doc = ET.fromstring(xslt)
transform = ET.XSLT(xslt_doc)
dom = transform(dom)

print(ET.tostring(dom, pretty_print = True,
                  encoding = 'utf-8'))

rawDescription: Define default namespace (unprefixed) in lxml


rawDescription: How to stepwise approximate f(x) using Euler's method given f'(x)

description: Stepwise approximate f(x) using Euler's method given f'(x)


code:
from dateutil.tz import tzlocal
datetime.now(tzlocal())

rawDescription: Get system local timezone in python

description: Get system local timezone in python


code:
import collections

def depth_first_search(node, get_children, depth=0):
    yield node, depth
    for child in get_children(node):
        # In the upcoming Python 3.3, the following can be written as
        # yield from depth_first_search(child, get_children, depth + 1)
        for n, d in depth_first_search(child, get_children, depth + 1):
            yield n, d

def breadth_first_search(node, get_children, depth=0):
    queue = collections.deque([(node, depth)])
    while queue:
        node, depth = queue.popleft()
        queue.extend((n, depth + 1) for n in get_children(node))
        yield node, depth

rawDescription: pythonic tree enumerator method using generator

description: Pythonic tree enumerator method using generator


code:
# write_to_stdin.py
import sys
input = sys.stdin.read()
sys.stdout.write('Received: %s'%input)

rawDescription: How do I make a python program give a command to a command shell?

description: Make a python program give a command to a command shell


code:
from .app import app
from hip_pocket import Mapper

mapper = Mapper(app)

mapper.add_url_rule("/", "index.index")
mapper.add_url_rule("/test", "index.test_endpoint", methods=["POST"])

mapper.add_url_rule("/say-hello/<name>",
                        "say_hello.greeter",
                        methods=["GET", "POST"])

rawDescription: How to have different py files to handle different routes?

description: Have different py files to handle different routes


code:
def __init__(self,parent,controller):
    ...
    self.CurrentQ = 0
    ...
    self.UserAnsEntry.bind("<Return>",self.TestEnterKey)
    ...
    self.UserAnsButton = ttk.Button(self,text="ENTER", command=self.TestEnterKey)
    ...

def TestEnterKey(self,event=None):
    self.CurrentQ += 1
    self.CurrentQStringVar.set(QStringList[self.CurrentQ])

rawDescription: Repeatedly iterating through a list, with buttons and bindings


code:
import matplotlib.pyplot as plt

fig = plt.figure()
x = [1,2,3,4,5]
y = x
ax = fig.add_subplot(1,1,1)
ax.set_yticks([3.7], minor=True)
ax.set_yticklabels(["100"], minor=True)
ax.plot(x,y)

y_ticks = ax.yaxis.get_major_ticks()
y_ticks[5].set_visible(False)
y_minor_ticks = ax.yaxis.get_minor_ticks()
y_minor_ticks[0].label.set_visible(False)

plt.show()

rawDescription: Matplotlib: add custom tick label and remove custom tick on y-axis


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

data1,data2,data3,data4 = (np.random.random(100),
                           np.random.random(100),
                           np.random.random(100),
                           np.random.random(100))

fig,ax = plt.subplots()

ax.plot(data1, label="1", color="k")
ax.plot(data2, label="2", color="r")
ax.plot(data3, label="3", color="g")

ax2 = ax.twinx()
ax2.plot(data4, label="4", color="b")

# First get the handles and labels from the axes
handles1, labels1 = ax.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()

# Add the first legend to the second axis so it displaysys 'on top'
first_legend = plt.legend(handles1, labels1, loc='center')
ax2.add_artist(first_legend)

# Add the second legend as usual
ax2.legend(handles2, labels2)

plt.show()

rawDescription: Matplotlib: how to adjust zorder of second legend?


code: ABC

rawDescription: Explain to me how .join() works in Python


code:
@asyncio.coroutine
def init(loop):
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/{name}', handle)

    srv = yield from loop.create_server(app.make_handler(),
                                        '127.0.0.1', 8080)
    print("Server started at http://127.0.0.1:8080")  # THIS PART
    return srv

rawDescription: Pros and cons of using return (yield from some_function())


code:
try:
    subscriptions = filters[word]
    # TODO do something with subscriptions
except:
    pass # probably don't need to do anything if not present

rawDescription: Fastest way of checking for word in huge list of keywords - Python performance


code:
import csv
d = {}
with open('input.csv', 'r') as f:
    csvr = csv.DictReader(f)
    for rec in csvr:
        if rec['Id'] not in d or int(rec['Var']) > int(d[rec['Id']]['Var']):
            d[rec['Id']] = rec
with open('output.csv', 'w') as f:
    csvw = csv.DictWriter(f, fieldnames=csvr.fieldnames)
    csvw.writeheader()
    csvw.writerows(d.itervalues())

rawDescription: Using Python to pull out max values to an output file


code:
process = Process(target=actualize_files_and_folders, args=[self])
process.start()

rawDescription: python simple thread not working

description: Python simple thread not working


code:
class myclassmethod(object):
    def __init__(self, method):
        self.method = method
    def __get__(self, instance, cls):
        return lambda *args, **kw: self.method(cls, *args, **kw)

rawDescription: Location of @classmethod

description: Location of @classmethod


code: from gettext import gettext as _

rawDescription: Translate argparse's internal strings

description: Translate argparse's internal strings


code: list = [item+':' for item in list]

rawDescription: How to add a character to the end of every string in a list?

description: Add a character to the end of every string in a list


code:
class A:
    def foo():
        pass
    def bar():
        pass

class B:
    def biz(): pass

class C(A, B):
    pass

rawDescription: How would I find where a function originates in source code?


rawDescription: Pandas - replacing column values

description: Pandas - replacing column values


rawDescription: How to view all elements of a Python Dictionary for Just One Value of one of the Elements in a Tuple Key

description: View all elements of a Python Dictionary for Just One Value of one of the Elements in a Tuple Key


code:
from math import sqrt

def generate_possible_factors(N):
    """generator for iterating through possible factors for N

    yields 2, every odd integer <= sqrt(N)
    """
    if N <= 3:
        return
    yield 2
    f = 3
    last = int(sqrt(N))
    while f <= last:
        yield f
        f += 2

rawDescription: How to use IPython.parallel map() with generators as input to function

description: Use IPython.parallel map() with generators as input to function


code:
def longest_snake(numbers, counts, path):
    best = path
    for n in sorted(counts, key=numbers.index):
        if counts[n] > 0 and (path == [] or abs(path[-1] - n) == 1):
            counts[n] -= 1
            res = longest_snake(numbers, counts, path + [n])
            if len(res) > len(best):
                best = res
            counts[n] += 1
    return best

rawDescription: Longest Snake Sequence in an Array

description: Longest Snake Sequence in an Array


code:
import re
import math
import time
# ...

rawDescription: Importing the entire Python standard library


code:
import os
_proc_status = '/proc/%d/status' % os.getpid()

_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
          'KB': 1024.0, 'MB': 1024.0*1024.0}

def _VmB(VmKey):
    '''Private.
    '''
    global _proc_status, _scale
     # get pseudo file  /proc/<pid>/status
    try:
        t = open(_proc_status)
        v = t.read()
        t.close()
    except:
        return 0.0  # non-Linux?
     # get VmKey line e.g. 'VmRSS:  9999  kB\n ...'
    i = v.index(VmKey)
    v = v[i:].split(None, 3)  # whitespace
    if len(v) < 3:
        return 0.0  # invalid format?
     # convert Vm value to bytes
    return float(v[1]) * _scale[v[2]]

def memory(since=0.0):
    '''Return memory usage in bytes.
    '''
    return _VmB('VmSize:') - since

def resident(since=0.0):
    '''Return resident memory usage in bytes.
    '''
    return _VmB('VmRSS:') - since

def stacksize(since=0.0):
    '''Return stack size in bytes.
    '''
    return _VmB('VmStk:') - since

rawDescription: Total memory used by Python process?

description: Total memory used by Python process


code:
def foo():
    for x in range(10):
        yield (yield x)

rawDescription: Attempting to understand yield as an expression


code:
List1 =[7,6,9]
sorted(List1)
List1           #List1 is not affected

rawDescription: Can anyone explain why this sorting won't work?


rawDescription: Find all possible ordered groups in a list


code:
df_met['wind_speed'].plot(figsize=(12,4))
df_wave['significant_wave_height'].plot(secondary_y=True);
ax = gca();
lines = ax.left_ax.get_lines() + ax.right_ax.get_lines()
ax.legend(lines, ['{} ({})'.format(l.get_label(), side) for l, side in zip(lines, ('left', 'right'))]);

rawDescription: How to get multiple legends from multiple pandas plots

description: Get multiple legends from multiple pandas plots


code:
user = "user"

matrix = {
    "user" : {
        "a" : "b",
        "c" : "d",
        "e" : "f",
    },
}

col = {
    "user" : {
        "a" : "b_2",
        "c" : "d_2",
    },
}

original.update(col[user])

print(original)

rawDescription: one liner for conditionally replacing dictionary values

description: One liner for conditionally replacing dictionary values


code:
with open("file.txt") as f:
    myvar = f.readline().rstrip()

rawDescription: f.readline() != '0' even if reading a line containing only 0

description: F.readline() != '0' even if reading a line containing only 0


code:
['Pnk Flooyd', 'Pink Fl', 'Poonk LLoyds', 'Pook Loyds']
['John Marvulli', 'John Michael Marvulli']
['Ld Zeppelin', 'Led Zepelin']
['Beetles', 'Beatlez', 'Beatles']

rawDescription: Python "in" Comparison of Strings of Different Word Length


code:
from rest_framework import permissions

class HasNiceHatOrHasNicePants(permissions.BasePermission):
    """
    Permission to check if user has a Nice Hat or has Nice Pants.
    If both are False do not return anything.
    """
    def has_permission(self, request, view):

        if request.user.has_nicehat() or request.user.has_nicepants():
            return True

rawDescription: OR style permissions for DjangoRestFramework


code:
theDate = myDatetime.strftime('%Y-%m-%d')
theTime = myDatetime.strftime('%H:%M:%S')

rawDescription: how to get the date from datetime

description: Get the date from datetime


code:
for thing in get_val(n+1, last+[k]):
    yield thing

rawDescription: Simple recursion with yield?

description: Simple recursion with yield


rawDescription: Serialize an already serialized json string?


rawDescription: Parallel and conditional: NoneType object has no attribute '__dict__'


code:
if LOGGING:
    with open(PATH_TO_LOGFILE, 'a') as logf:
        logf.write(some_txt)
else:
    print(some_txt)

rawDescription: How can I determine who is calling my Python script?

description: Determine who is calling my Python script


rawDescription: Insert new row every 2nd element of python list


code: type(self).immutable_attr = True

rawDescription: Mutating objects referenced by class attributes through instance methods


rawDescription: ply concatenating strings on grammar

description: Ply concatenating strings on grammar


code: my_list2, my_list1 = map(list, zip(*my_list))

rawDescription: Splitting a nested list into two lists

description: Splitting a nested list into two lists


code:
class YourDateField(models.DateField):
    def get_prep_lookup(self, lookup_type, value):
        if value and '/' in value:
            value = parse_slash_date(value)
        return super(YourDateField, self).get_prep_lookup(
            lookup_type, value)

rawDescription: Django Model DateField to_python

description: Django Model DateField to_python


code: sum( x == chosen_value for x in d.values() )

rawDescription: Python 2.7 Counting number of dictionary items with given value


rawDescription: Replace column separation of # with comma or tab


code:
p = subprocess.Popen(['./main/foo', '--config', 'config_file'],
  stderr=subprocess.STDOUT,
  stdout=open('temp.log', 'w'))

rawDescription: How to avoid passing shell constructs to executable using Popen

description: Avoid passing shell constructs to executable using Popen


code:
for i, j in zip(position, value):
    out_file.write(str(i) + '\t' + str(j) + '\n')

rawDescription: Write multiple columns on .xls through Python 2.7


code:
from operator import neg
L = [42, 10, 3, 8]
sum(map(neg, L[1:]), L[0])

rawDescription: How to subtract from a user-inputed list

description: Subtract from a user-inputed list


rawDescription: argparse: map user input to defined constant

description: Argparse: map user input to defined constant


code: doc[column] = [int(v) for v in value.split(',') if v.strip().isdigit()]

rawDescription: How to map a list to integers

description: Map a list to integers


code:
import pandas as pd
from pandas.io.data import DataReader
from datetime import datetime

symbols = ['GOOG','AAPL']

try:
    df = pd.read_excel('NewFile.xlsx')
except:
    df = pd.DataFrame()

for symbol in symbols:
    ClosingPrice = DataReader(symbol, 'yahoo', datetime(2015,1,1), datetime(2015,9,1))
    ClosingPrice = ClosingPrice.reset_index()
    ClosingPrice['Symbol'] = symbol
    df = df.append(ClosingPrice)

writer = pd.ExcelWriter('NewFile.xlsx', engine='xlsxwriter')
df.to_excel(writer,sheet_name='Sheet1',index=False)
writer.save()

rawDescription: How to write data to excel using python for stock data being pulled from yahoo

description: Write data to excel using python for stock data being pulled from yahoo


code: struct.pack_into(fmt, buffer, offset, v1, v2, ...)

rawDescription: Python, how to put 32-bit integer into byte array