code:
d={
    'global':
    {
        'www.test1.com': ['x', 'n'],
        'www.test2.com': ['x', 'y'],
        'www.test3.com': ['x'],
        'www.test4.com': ['x', 'y'],
        'www.test5.com': ['n']
    },
    'private':
    {
        'www.test6.com': ['m', 'n'],
        'www.test7.com': ['n'],
        'www.test8.com': ['m']
    }
}
new_d={key:dict(filter(lambda x:'n' in x[1], value.items())) for key, value in d.items() if dict(filter(lambda x:'n' in x[1], value.items()))}
new_d

rawDescription: Fetch only those part in dictionary of dictionary which contains particular string in value


code:
# print out the number of messages for each second
for sec, data in bins:
    print('{0} --- {1}'.format(sec, len(data)))

# write (sec, msg_per_sec) out to CSV file
import csv
with open("test.csv", "w") as f:
    csv.writer(f).writerows((s, len(d)) for s, d in bins)

# get average message per second
message_counts = [len(d) for s, d in bins]
avg_msg_per_second = float(sum(message_count)) / len(message_count)

rawDescription: Grouping Messages by Time Intervals

description: Grouping Messages by Time Intervals


code:
def succ(self, node):
    for i in range(len(node)-2):
        j=i+3
        if node[i:j]==[1,1,0]:
            yield node[:i]+[0,0,1]+node[j:]
        if node[i:j]==[0,1,1]:
            yield node[:i]+[1,0,0]+node[j:]
        if node[i:j]==[1,0,0]:
            yield node[:i]+[0,0,1]+node[j:]
        if node[i:j]==[0,0,1]:
            yield node[:i]+[1,0,0]+node[j:]

rawDescription: Depth-First search in Python

description: Depth-First search in Python


code:
class Foo(object):
   def some_method(self, a, b):
      self.foo = a
      self.bar = b
      return a+b

obj = Foo()
result = obj.some_method(1, 3) # `obj` is passed in as the instance (ie, self)
print(result) # This will print 4
print(obj.foo) # 1
print(obj.bar) # 3

rawDescription: Does this code imply a class and method "relationship?"


code: database = open(r"C:\Users\PC\Desktop\database.txt", "a")

rawDescription: When I reopen the program is everything fades in txt file


code:
import pandas as pd
import numpy as np
np.random.seed(42)
Num_members = int(10)
Num_groups = int(1)
members = pd.DataFrame({
    'ID': np.arange(Num_members),
    'groupID': np.random.random_integers(0, 2*Num_groups, Num_members),
    'groupmass': np.zeros(Num_members),
    'brightness': np.random.uniform(8,12, Num_members),
    'color':np.random.uniform(0,1,Num_members)
})

rawDescription: using pandas to create new columns based on intra-group rank-order

description: Using pandas to create new columns based on intra-group rank-order


code:
class Person(object):
    def __init__(self, name=None, address=None):
        self.name = name
        self.address = address

    def __eq__(self, other):
        return self.name == other.name and self.address == other.address

    def __hash__(self):
        return hash((self.name, self.address))

rawDescription: Object equallity in python collections.Counter


code:
ds = SupervisedDataSet(35, 1)

A2 = convertToList(A)
ds.addSample(A2, (1,))

E2 = convertToList(E)
ds.addSample(E2, (2,))

I2 = convertToList(I)
ds.addSample(I2, (3,))

O2 = convertToList(O)
ds.addSample(O2, (4,))

U2 = convertToList(U)
ds.addSample(U2, (5,))

rawDescription: How can I use a Matrix as a dataset on PyBran?

description: Use a Matrix as a dataset on PyBran


code:
from fabric.api import run, roles

env.roledefs = {
    'db': ['db1'],
    'web': ['web1', 'web2', 'web3'],
}

@roles('db')
def migrate():
    # Database stuff here.
    pass

@roles('web')
def update():
    # Code updates here.
    pass

rawDescription: Migrate django app to multiple servers

description: Migrate django app to multiple servers


rawDescription: numpy.loadtxt unix timestamp converter

description: Numpy.loadtxt unix timestamp converter


code:
from collections import defaultdict
import random

wordsByLength = defaultdict( list )
for word in allWords:
    wordsByLength[ len(word) ].append( word )

rawDescription: Index by word length

description: Index by word length


code:
def classify(request, pk):
    record = EventRecord.objects.filter(pk=pk).select_related()

    # the above returns queryset hence you have to extract the record manually
    if not len(record):
        raise Http404()
    else:
        record = record[0]

    # now use record as usual and no extra queries will be executed
    title = record.article.article_title
    ...

rawDescription: Get Foreign Key parent of object - Django


code:
rdd_1 = yourRdd.groupByKey()
rdd_2 = rdd1.mapValues(mapFunction).flatMapValues()

rawDescription: Combinations And Mass Set Intersections With Apache Spark (Pyspark)


rawDescription: How can I create the following data type in Python?

description: Create the following data type in Python


code:
MAXLEN = 15
def title_limit(title, limit):
    if len(title) > limit:
        title = title[:limit-3] + "..."
    return title

blah = "blah blah blah blah blah"
title_limit(blah) # returns 'blah blah bla...'

rawDescription: Truncate a string in mako template

description: Truncate a string in mako template


code:
def run(cmd, other_stuff, silent=False):
   ...

rawDescription: Wrap a function in python supplying an additional boolean


rawDescription: Apostrophe within Python lookbehind assertion


code:
def singleton_with_args(*args, **kwargs):
    def wrapper(cls):
        return cls(*args, **kwargs)
    return wrapper

@singleton_with_args(0)
class EventManager:
    def __init__(self, first_event):
        self.events = [first_event]
    def add_event(self, event):
        self.events.append(event)
    def print_events(self):
        print("Events : {}".format(self.events))

EventManager.add_event(1)
EventManager.add_event(2)
EventManager.add_event(3)
EventManager.print_events()

rawDescription: Python: use the same class instance in multiple modules


code:
A
B
A[~np.in1d(A,B).reshape(A.shape)]

rawDescription: Remove numbers from a numpy array

description: Remove numbers from a numpy array


code:
import lxml.etree as et

xml = et.parse("feed.xml")
ns = {"ns": 'http://www.w3.org/2005/Atom'}
for n in xml.xpath("//ns:category", namespaces=ns):
    t  = n.xpath("./../ns:summary", namespaces=ns)[0]
    print(t.xpath("normalize-space(.)"))

rawDescription: remove newline and whitespace parse XML with python Xpath

description: Remove newline and whitespace parse XML with python Xpath


code:
df = pd.DataFrame([['urn:dew_point', 1]], columns=['properties', 'id'])
df['properties'].str.contains('urn:dew_point')
df[df['properties'].str.contains('urn:dew_point')]

rawDescription: Select Pandas rows based on list value

description: Select Pandas rows based on list value


code: from lib.Transform import fft

rawDescription: Mixing functions and subpackages in Python packages


code:
place = Place.objects.get(pk=1)
restaurant = Restaurant.objects.get(pk=1)
fake_restaurant = FakeRestaurant.objects.get(pk=1)
fake_restaurant.delete()

rawDescription: Django model inheritance: Delete subclass keep superclass


code: [('David Meredith', 'Financial Director', 'sold post-exercise', '15,000', '1044.00p'), ('Mark Brookes', 'Non Executive Director', 'bought', '811', '76.75p'), ('Albert Ellis', 'CEO', 'bought', '262', '52.00p')]

rawDescription: Python regex to parse financial data

description: Python regex to parse financial data


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, NumericProperty

kv = '''
[MyLabel@Label]:
    text: ctx.text if hasattr(ctx, 'text') else ''
    font_size: 24
    markup: True

<MyWidget>:
    id: f_wid
    BoxLayout:
        size: f_wid.size
        orientation: 'vertical'
        MyLabel:
            text: "Hello world 1"
        MyLabel:
            text: "Hello world 2"
        MyLabel:
            text: "Hello world 3"
        MyLabel:
            text: "Hello world 4"
        MyLabel:
            text: "Hello world 1"
        MyLabel:
            text: "Hello world 2"
        MyLabel:
            text: "Hello world 3"
        MyLabel:
            text: "Hello world 4"
'''
Builder.load_string(kv)

import kivy
kivy.require('1.7.1') # replace with your current kivy version !

from kivy.app import App
from kivy.uix.widget import Widget

class MyWidget(Widget):
    pass

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

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

rawDescription: Setting global font size in kivy

description: Setting global font size in kivy


rawDescription: extracting string before specific mark

description: Extracting string before specific mark


code:
import subprocess
import shlex
subprocess.call(shlex.split("/bin/bash -c 'grep -w 1 pattern <(tail -f mylogfile.log)'"))

rawDescription: python 2.3 how to run a piped command

description: Python 2.3 how to run a piped command


code:
np.maximum.accumulate(x["scores"], axis=1)
x["scores"] = np.maximum.accumulate(x["scores"], axis=1)
x

rawDescription: replacing numpy array values in-place for arrays with custom dtype

description: Replacing numpy array values in-place for arrays with custom dtype


code:
Data = {
"weight_factors" : {
    "parameter1" : 10,
    "parameter2" : 30,
    "parameter3" : 30
    },
"other_info" : {
    }
}
sum(Data["weight_factors"].values())

rawDescription: Accessing the values of a key

description: Accessing the values of a key


code:
highest, row, total = 0, 0, 0
filtered_results = [[i for i in b if isinstance(i, (int, float))] for b in results]
for a, b in enumerate(filtered_results):
    for i in b:
        if i > highest:
            highest = i
            row = a
            total = sum(b)

rawDescription: Ignore str in sum()

description: Ignore str in sum()


code:
import contextlib
import sys

class DummyFile(object):
    def write(self, x): pass

@contextlib.contextmanager
def nostdout():
    save_stdout = sys.stdout
    sys.stdout = DummyFile()
    yield
    sys.stdout = save_stdout

rawDescription: Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call


code:
myclassinstance = MyClass()
myclassinstance.x = 'foo'  #translates to MyClass.__setattr__(myclassinstance,'x','foo')
bar = myclassinstance.x    #translates to bar=MyClass.__getattr__(myclassinstance,'x')

rawDescription: What is the difference between __set__ and __setattr__ in Python and when should which be used?


code:
forward = { "messageid": 1,
         "message": "First message"
       }
backward = { "messageid": 2,
         "message": "Second message"
       }

rawDescription: Sending websocket message to client with parameter


code: result = users_df.where(users_df._id == chosen_user).select("gender")

rawDescription: Getting specific field from chosen Row in Pyspark DataFrame


code:
if file not in word_count_dict[word]:
    word_count_dict[word][file] = 0
    word_count_dict[word][file] += 1
    word_count_dict[word]["total"] += 1

rawDescription: how to iterate over all keys in dictionary python?

description: Iterate over all keys in dictionary python


code: connect(label_widget, SIGNAL(move(QPoint)), this, move_label(QPoint));

rawDescription: How to move QLabel?

description: Move QLabel


code:
my_list_of_columns = [[45,25,48],[67,22,54],["Row","Abe","Abe"],["Fine","Real","Noon"]]
import operator
sorted_list_of_rows = sorted(zip(*my_list_of_columns), key = operator.itemgetter(2,3))
list_of_columns = list(zip(*sorted_list_of_rows))
list_of_columns

rawDescription: Python 3: sort rows in 2D matrix, where columns are lists


code: len(a)

rawDescription: How many elements may python dictionary hold?


code:
import logging
import requests
import time

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)

def fetch_url(i, q):
    while True:
        url = q.get()
        response = requests.get(url)
        logging.info("{}: {}".format(response.status_code, url))
        time.sleep(i + 2)
        q.task_done()

rawDescription: Disable logging for a python module in one context but not another


code:
def left(tree):
    if tree.isLeaf:
        raise ArgumentError ("tree is leaf")
    else:
        return tree.value[0]

def right(tree):
    if tree.isLeaf:
        raise ArgumentError ("tree is leaf")
    else:
        return tree.value[1]

def value(tree):
    if not tree.isLeaf:
        raise ArgumentError ("tree is branch")
    else:
        return tree.value

rawDescription: Haskell equivalent of data constructors in Python?


code:
r
circulant(r).T

rawDescription: Building a matrix of 'rolled' rows efficiently in Numpy


code:
import numpy
from matplotlib import pyplot as plt
if __name__ == '__main__':
    x = [1, 2, 3]
    plt.ion() # turn on interactive mode, non-blocking `show`
    for loop in range(0,3):
        y = numpy.dot(x, loop)
        plt.figure()   # create a new figure
        plt.plot(x,y)  # plot the figure
        plt.show()     # show the figure, non-blocking
        _ = raw_input("Press [enter] to continue.") # wait for input from the user
        plt.close()    # close the figure to show the next one.

rawDescription: Can I generate and show a different image during each loop with Matplotlib?

description: Generate and show a different image during each loop with Matplotlib


rawDescription: Comparing values from a multidimentional array using Python


code:
import re

with open('test.txt') as f:
    text = f.read()

reobj = re.compile("(.+),", re.MULTILINE)
dic = {}
for match in reobj.finditer(text):
    surname = match.group()
    if surname in dic:
        dic[surname] += 1
    else:
        dic[surname] = 1

rawDescription: How to parse txtfile and export into dictionary?

description: Parse txtfile and export into dictionary


code:
with open('highscores.txt', 'rb') as f:
    reader = csv.reader(f)
    scores = [row[-1] for row in reader]

rawDescription: How to display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)

description: Display top 10 highscores from a comma separated value (.txt) file in Python (Pygame)


code:
# colorbar
axes = plt.subplot2grid((4, 2), (0, 1), rowspan=3)
plt.colorbar(pc, cax=axes)

rawDescription: How to plot pcolor colorbar in a different subplot - matplotlib

description: Plot pcolor colorbar in a different subplot - matplotlib


rawDescription: Inserting a variable in MongoDB specifying _id field


code:
import numpy as np
from scipy import sparse

s = sparse.csr_matrix(np.array([[4, 0, 3, 5],
         [0, 2, 6, 0],
         [7, 0, 1, 0]]))

print(s)
# <3x4 sparse matrix of type '<type 'numpy.int64'>'
#   with 7 stored elements in Compressed Sparse Row format>

s[s > 2] = 0
s[s != 0] = 1

print(s.todense())

rawDescription: binarize a sparse matrix in python in a different way

description: Binarize a sparse matrix in python in a different way


code:
class Course(ndb.Model):
    # all the stuff already there

    @property
    def members(self):
        return CourseInscription.query(CourseInscription.course == self.key)

rawDescription: Efficient way to store relation values in NDB


code:
import random, string

def randomword(length):
   return ''.join(random.choice(string.lowercase) for i in range(length))

rawDescription: Random strings in Python

description: Random strings in Python


code: transposed_mult(x.T, y)

rawDescription: Elementwise multiply 1D-numpy arrays (shapes (k,1) or (k,)) and have result have the shape of the first


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

description: Dynamically update a plot in a loop


code:
df = pd.DataFrame(data={'rank': np.random.randint(low=1, high=100, size=500),
                        'SKU': np.random.choice(list('ABCDE'), replace=True, size=500),
                        'date': np.array([d for d in repeat(pd.date_range(start=date(2016,1,1), freq='D', periods=20), 25)]).flatten()})

df['median'] = df.groupby(['date','SKU'])['rank'].transform('median')

rawDescription: Find median of values based on multiple identifiers and add to row


code:
class Author(models.Model):
    created_by = models.ForeignKey(User)

class FindReplace(models.Model):
    author = models.ForeignKey(Author)

    find = models.CharField(max_length=256)
    replace = models.CharField(max_length=5000)

class Sentence(models.Model):
    account = models.ForeignKey(Account)  #Is account related to user? The you can query it by user.
    # Or add an FK relation to Author.

    text = models.CharField(
        max_length=500,
        blank=False,
        null=False,
        )

rawDescription: Many-to-many relationship children exclusive to parent model. How?


rawDescription: Using pygame.time.set_timer

description: Using pygame.time.set_timer


code:
x1 = np.empty(unqA.shape, dtype=x.dtype)
x1['recod'] = unqA
x1['count'] = cnt
x1

rawDescription: Merging records in a Numpy structured array


code:
def my_view(request):
    if not request.user.is_superuser:
         return HttpResponse(status=403)  # HTTP 403 Forbidden
    ...

rawDescription: We have @login_required, wheres @admin_required


code:
method_map = {'==': '__eq__', '!=': '__ne__'}
comparison = getattr(Product.manufacturer, method_map[op])   # Here, 'op' is the operator (!=)
sqlalchemy.or_(comparison('foo'), comparison('bar'))         # Equivalent to: Product.manufacturer != 'foo' || Product.manufacturer != 'bar'

rawDescription: Store comparison in variable (or execute comparison when it's given as an string)


code:
numpy.array(some_list)[numpy.rollaxis(
    numpy.indices((len(some_list),) * some_length), 0, some_length + 1)
    .reshape(-1, some_length)]

rawDescription: itertools product speed up

description: Itertools product speed up


code: timeline = filter(lambda status: not any(re.findall(r"\S*"+word+r"\S*",status.text) for word in wordBlacklist), timeline)

rawDescription: Check if string (or split string) contains any words from list


code: f = open(self.fn, 'rb')

rawDescription: Python bytearray isn't as long as it should be


code: dict_class_copy = deepcopy(dict_class)

rawDescription: Best way to partially deep copy a dictionary in Python?

description: Partially deep copy a dictionary in Python


code: bar = lambda: None

rawDescription: Definition of a function that does nothing


code: Factor.empty = something_else

rawDescription: Define a constant object in python

description: Define a constant object in python


rawDescription: python, add lists to csv by columns, with list extracted dynamically from other data

description: Python, add lists to csv by columns, with list extracted dynamically from other data


code: lst = list(generator_object)

rawDescription: How to convert generator object into list?

description: Convert generator object into list


code:
regexpHandler = re.compile('
(.*?)
')

rawDescription: Python and web-tags regex

description: Python and web-tags regex


code:
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

rawDescription: Match multiple strings containing lines from file python


code:
def find_unique_ids(df,daysback):

    # We need both Date and ID to both be either fields or index fields -- no mix/match.
    df = df.reset_index()

    # Calculate DateComp by adding our daysback value as a timedelta
    df['DateComp'] = df['Date'].apply(lambda dc: dc + timedelta(days=daysback))

    # Join df back on to itself, SQL style LEFT OUTER.
    df2 = pd.merge(df,df, left_on=['DateComp','ID'], right_on=['Date','ID'], how='left')

    # Create series of missing_id values from the right table
    missing_ids = (df2['Date_y'].isnull())

    # Create series of valid DateComp values.
    # DateComp is the "future" date that we're comparing against. Without this
    # step, all records on the last Date value will be flagged as unique IDs.
    valid_dates = df2['DateComp_x'].isin(df['Date'].unique())

    # Use those to find missing IDs and valid dates. Create a new output DataFrame.
    output = df2[(valid_dates) & (missing_ids)][['DateComp_x','ID']]

    # Rename columns of output and return
    output.columns = ['Date','ID']
    return output

rawDescription: Pandas Dataframe Groupby Determine Values in 1 group vs. another group


code:
class NumberParser:
    def __init__(self, parse_type=None):
        try:
            self.parse = self._parse_types[parse_type]
        except KeyError:
            raise ValueError("invalid parse_type '{}'".format(parse_type))

    @staticmethod
    def _parse_int(str_i):
        """
        Parse `str_i` as an integer
        """
        return 1

    @staticmethod
    def _parse_float(str_f):
        """
        Parse `str_f` as a float
        """
        return 1.

    @staticmethod
    def _parse_auto(str_a):
        """
        Parse `str_a` as int if possible, else as float
        """
        if "point" in str_a:
            return NumberParser._parse_float(str_a)
        else:
            return NumberParser._parse_int(str_a)

    # needs .__func__ on each to work around
    #   static method's need for a calling class
    _parse_types = {
        int:     _parse_int.__func__,
        "int":   _parse_int.__func__,
        float:   _parse_float.__func__,
        "float": _parse_float.__func__,
        None:    _parse_auto.__func__
    }

rawDescription: Design pattern - two different return types


code:
from io import BytesIO
from struct import pack
import psycopg2

# Two rows of data; "id" is not in the upstream data source
# Columns: node, ts, val1, val2
data = [(23253, 342, -15.336734, 2494627.949375),
        (23256, 348, 43.23524, 2494827.949375)]

conn = psycopg2.connect("dbname=mydb user=postgres")
curs = conn.cursor()

# Determine starting value for sequence
curs.execute("SELECT nextval('num_data_id_seq')")
id_seq = curs.fetchone()[0]

# Make a binary file object for COPY FROM
cpy = BytesIO()
# 11-byte signature, no flags, no header extension
cpy.write(pack('!11sii', b'PGCOPY\n\377\r\n\0', 0, 0))

# Columns: id, node, ts, val1, val2
# Zip: (column position, format, size)
row_format = list(zip(range(-1, 4),
                      ('i', 'i', 'h', 'f', 'd'),
                      ( 4,   4,   2,   4,   8 )))
for row in data:
    # Number of columns/fields (always 5)
    cpy.write(pack('!h', 5))
    for col, fmt, size in row_format:
        value = (id_seq if col == -1 else row[col])
        cpy.write(pack('!i' + fmt, size, value))
    id_seq += 1  # manually increment sequence outside of database

# File trailer
cpy.write(pack('!h', -1))

# Copy data to database
cpy.seek(0)
curs.copy_expert("COPY num_data FROM STDIN WITH BINARY", cpy)

# Update sequence on database
curs.execute("SELECT setval('num_data_id_seq', %s, false)", (id_seq,))
conn.commit()

rawDescription: Use binary COPY table FROM with psycopg2


rawDescription: Representing Coordinates in GeoAlchemy2

description: Representing Coordinates in GeoAlchemy2


code:
import urllib
import urllib2

url = 'http://www.example.com'
values = {'var' : 500}

data = urllib.urlencode(values)
response = urllib2.urlopen(url, data)
page = response.read()

rawDescription: POSTing a form using Python and Curl

description: POSTing a form using Python and Curl


code:
p = Player(shape='circle', velocity=0.0, acceleration=1.0, image='player.png')
p.shape
p.velocity
p.acceleration

rawDescription: Pythonic way to have code-reuse in game Entity classes


code:
def sample(population, k, prob = None):
    import random
    from bisect import bisect
    from operator import itemgetter
    def cdf(population, k, prob):
        population = map(itemgetter(1), sorted(zip(prob, population)))
        _cumm = [prob[0]]
        for i in range(1, len(P)):
            _cumm.append(_cumm[-1] + P[i])
        return [population[bisect(_cumm, random.random())] for i in range(k)]
    if prob == None:
        return  random.sample(population, k)
    else:
        return cdf(population, k, prob)

rawDescription: Selecting corresponding k rows from matrix and vector


code: direction = input('which direction?')

rawDescription: Displaying a moveable character inside of a grid


code: randomStrings = [str(x) for x in randomInts]

rawDescription: Python random and int to string question


rawDescription: Writing/parsing a fixed width file using Python


code:
for i, _ in enumerate(s): #i here is the index, equal to "i in range(len(s))"
    if s[i:i+3] == 'bob': #Check the current char + the next three chars.
        bob += 1
print('Number of times bob occurs is: ' + str(bob))

rawDescription: Python Slicing 'bob' in s

description: Python Slicing 'bob' in s


code:
path_effects = [patheffects.withSimplePatchShadow(shadow_rgbFace=(1,1,1))]

for i, j in product(range(m), range(n)):
    _ = ax.text(j, i, '{0:.2f}'.format(df.iloc[i, j]),
                size='medium', ha='center', va='center',
                path_effects=path_effects)

rawDescription: Create heatmap using pandas TimeSeries

description: Create heatmap using pandas TimeSeries


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

class Blog(models.Model):
    user = models.ForeignKey(User)

    @property
    def username(self):
        return self.user.username

rawDescription: ForeignKey to a Model field?

description: ForeignKey to a Model field


rawDescription: apply a regex to retrieve a string

description: Apply a regex to retrieve a string


code:
class Child (Base) :
    def __init__ (self) :
        super(Child, self).__init__()

    def go (self) :
        self.A = self.A * 2
        super(Child, self).go()

rawDescription: Methods of the same name and inheritance, Python


code:
class MyClass:
    def say_hello(self):
       print('Hello!')

class MyException(Exception):
    def __init__(self, instance, *args, **kwargs):
        instance.say_hello()
        super(MyException, self).__init__(*args, **kwargs)

exc = MyException(MyClass(), ...)

rawDescription: Python3 - call method from parent class

description: Python3 - call method from parent class


rawDescription: Beautiful Soup - Class contains 'a' and not contains 'b'


code:
from pprint import pprint as pp

pp(d)

{ ('128k', '0'): [ 'C:\\Test3\\ARRAY05-2NODE-RAID1-12disk-128k-0-segmented.xlsxC:\\Test1\\ARRAY05-2NODE-RAID1-17disk-128k-0-segmented.xlsx',
                   'C:\\Test4\\ARRAY05-2NODE-RAID1-25disk-128k-0-segmented.xlsx',
                   'C:\\Test2\\ARRAY05-2NODE-RAID1-18disk-128k-0-segmented.xlsx'],
  ('32k', '0'): [ 'C:\\Test1\\ARRAY05-2NODE-RAID1-12disk-32k-0-segmented.xlsx',
                  'C:\\Test6\\ARRAY05-2NODE-RAID1-25disk-32k-0-segmented.xlsx'],
  ('64k', '0'): ['C:\\Test2\\ARRAY05-2NODE-RAID1-12disk-64k-0-segmented.xlsx'],
  ('64k', '100'): [ 'C:\\Test5\\ARRAY05-2NODE-RAID1-12disk-64k-100-segmented.xlsx']}

rawDescription: Sorting and Matching a Python list

description: Sorting and Matching a Python list


rawDescription: Different integration results using Monte Carlo vs scipy.integrate.nquad


code:
import logging, logging.handlers
from django.conf import settings

LOGGING_INITIATED = False
LOGGER_NAME = 'project_logger'

def init_logging():
    logger = logging.getLogger(LOGGER_NAME)
    logger.setLevel(logging.INFO)
    handler = logging.handlers.TimedRotatingFileHandler(settings.LOG_FILENAME, when = 'midnight')
    formatter = logging.Formatter(LOG_MSG_FORMAT)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

if not LOGGING_INITIATED:
    LOGGING_INITIATED = True
    init_logging()

rawDescription: What is the DRY way to configure different log file locations for different settings?


rawDescription: How do I extract a sub-array from a numpy 2d array?

description: Extract a sub-array from a numpy 2d array


rawDescription: Connect IPython Console to an kernel on the internet


code:
class Field(object):

    def __init__(self, value):
        self.value = value
        self.valid = True

    def unspace(self):
        self.value = self.value.replace(' ', '')
        return self

    def len_valid(self, length):
        if len(self.value) < length:
            self.valid = False
        return self

rawDescription: Python way for object method chaining for class instance variables


code:
coltypes = [ i[2] for i in cur.fetchall() ]
for index, item in enumerate(coltypes):
    if (item == 'char'):
        coltypes[index] = str
    elif (item == 'integer'):
        coltypes[index] = int

rawDescription: pySQLite integration to pyGtk treeview

description: PySQLite integration to pyGtk treeview


code:
import operator
# ...
condition = reduce(operator.and_, [Q(full_name__icontains=s) for s in strings])
queryset = Profile.objects.filter(condition)

rawDescription: Filter Django database for field containing any value in an array


rawDescription: Extracting a table from web with different hierarchical tags


code:
a  # <-- not changed by `sorted` function.
a.sort(key=lambda x: x[1])
a

rawDescription: Sorting list of lists based on number in inner list


code:
evens = []
odds = []

for i in xrange(10):
   if i % 2 == 0: evens.append(i)
   else: odds.append(i)

rawDescription: Complement of list comprehension in python


code:
grade_elements = driver.find_elements_by_css_selector(".grid tr a[href$='fg=S2']")
grades = [g.text.split('\n') for g in grade_elements]

rawDescription: Splitting a String and Assigning it Variables


code:
def encrypt(plaintext, password):
    salt = Crypto.Random.get_random_bytes(SALT_SIZE)

    key = generate_key(password, salt, NUMBER_OF_ITERATIONS)

    cipher = AES.new(key, AES.MODE_ECB)

    padded_plaintext = pad_text(plaintext, AES_MULTIPLE)

    ciphertext = cipher.encrypt(padded_plaintext)

    ciphertext_with_salt = salt + ciphertext

    return ciphertext_with_salt

rawDescription: Encrypt / decrypt data in python with salt


code: [random.randint(1,60) for _ in range(6)]

rawDescription: Python code that needs some overview

description: Python code that needs some overview


code:
bg1 = cv2.BackgroundSubtractorMOG()
cap = cv2.VideoCapture('video.mp4')
frame = cap.read()[1]

rawDescription: OpenCV Python cv2.BackgroundSubtractor parameters


code:
HSHELL_REDRAW=6
WM_SHELL=10

def my_callback(nCode, wParam, lParam):
    if nCode == HSHELL_REDRAW and lParam:
        got_flashing_window_with_hwnd(wParam)

hook = user32.SetWindowsHookEx(WM_SHELL, my_callback, None, 0)

rawDescription: Python. Get flashing/blinking windows of a chat


code: 'abc' in myObject

rawDescription: 'in' operator with boost::python

description: 'in' operator with boost::python


code:
def set_list(l, i, v):
      try:
          l[i] = v
      except IndexError:
          for _ in range(i-len(l)+1):
              l.append(None)
          l[i] = v

rawDescription: Python list set value at index if index does not exist


code:
import ast

data1 = [(u'BAR_0', [1.0, 2.0, 3.0]), (u'FOO_1', [4.0, 5.0, 6.0])]
rdd = sc.parallelize(data1)
rdd.saveAsTextFile("foobar_text")

data2 = sc.textFile("foobar_text").map(ast.literal_eval).collect()
assert sorted(data1) == sorted(data2)

rawDescription: How to restore RDD of (key,value) pairs after it has been stored/read from a text file

description: Restore RDD of (key,value) pairs after it has been stored/read from a text file


code:
def _start_queue_management_thread(self):
    # When the executor gets lost, the weakref callback will wake up
    # the queue management thread.
    def weakref_cb(_, q=self._result_queue):
        q.put(None)
    if self._queue_management_thread is None:
        # Start the processes so that their sentinels are known.
        self._adjust_process_count()
        self._queue_management_thread = threading.Thread(
                target=_queue_management_worker,
                args=(weakref.ref(self, weakref_cb),
                      self._processes,
                      self._pending_work_items,
                      self._work_ids,
                      self._call_queue,
                      self._result_queue))
        self._queue_management_thread.daemon = True
        self._queue_management_thread.start()

rawDescription: Do any of python's built in modules use threads?


code:
for i, offers in enumerate(root.findall('.//{http://url}Offers'), start=1):
    value_found = False
    for amount in offers.findall('.//{http://url}Amount'):
        if amount.text == name:
            value_found = True
            break
    if value_found:
        tree = ET.ElementTree(offers)
        tree.write("offers%d.xml" % i,
           xml_declaration=True, encoding='utf-8',
           method="xml", default_namespace='http://url')

rawDescription: Python extract nodes containing tag using ElementTree


rawDescription: Numpy search for elements of an array in a subset


code:
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    driver = db.relationship('Driver', uselist=False, back_populates='user')
    manager = db.relationship('Manager', uselist=False, back_populates='user')

class Driver(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    driving_license = db.Column(db.String)
    user_id = db.Column(db.Integer, ForeignKey('user.id'))
    user = db.relationship('User', back_populates='driver')

class Manager(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    designation = db.Column(db.String)
    user_id = db.Column(db.Integer, ForeignKey('user.id'))
    user = db.relationship('User', back_populates='manager')

rawDescription: Inheritance in Flask-SqlAlchemy

description: Inheritance in Flask-SqlAlchemy


code:
THRESHOLD = 1000

class Switcher(object):
    def __new__(cls, n):
        if n < THRESHOLD:
            new_cls = Small
        else:
            new_cls = Big
        instance = super(Switcher, new_cls).__new__(new_cls, n)
        if new_cls != cls:
            instance.__init__(n)
        return instance

class Small(Switcher):
    def __init__(self, n):
        self.n = n

class Big(Switcher):
    def __init__(self, n):
        self.n = n

rawDescription: Changing the class type of a class after inserted data


code:
a = conn.create_topic(topicname)
a_arn = a['CreateTopicResponse']['CreateTopicResult']['TopicArn']

rawDescription: Boto - AWS SNS how to extract topic's ARN number


code: data = data.translate(None, ',.l?asd')

rawDescription: How to remove certain characters from a variable? (Python)

description: Remove certain characters from a variable? (Python)


rawDescription: create new column based on other column but stripping

description: Create new column based on other column but stripping


code:
df2 = pd.read_table('dummy.csv', header=None)
from collections import defaultdict
cols = []
df2.columns = cols
df2
df2.T.drop_duplicates().T

rawDescription: python pandas remove duplicate columns

description: Python pandas remove duplicate columns


code:
lst = [
    {'Title1': {'Link': 'ZbELsW_tyWA', 'Episode': 'Episode Name'}},
    {'Title2': {'Link': 'ZbELsW_tyWA', 'Episode': 'Episode Name2'}},
]
searchtitle = 'Title1'
[d[searchtitle] for d in lst if searchtitle in d]
next((d[searchtitle] for d in lst if searchtitle in d), None)

rawDescription: How to find dict value by Key in list

description: Find dict value by Key in list


code:
class TransUpdateView(UpdateView):
    #...

    def get_form_kwargs(self):
        kwargs = super(YourView, self).get_form_kwargs()
        kwargs.update({'user': self.request.user})
        return kwargs

rawDescription: Django: Filter ModelChoiceField by user

description: Django: Filter ModelChoiceField by user


code:
import pandas as pd

df = pd.read_csv('test/AnonymizedData.txt', sep='\t')

rawDescription: Pandas read_table error

description: Pandas read_table error


rawDescription: What is the difference between a function, an unbound method and a bound method?


code:
def grouper(n, iterable, fillvalue=None):
    # Source: http://docs.python.org/library/itertools.html#recipes
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    return itertools.izip_longest(*[iter(iterable)]*n,fillvalue=fillvalue)

def bits2str(bits):
    for b in grouper(8,bits):
        yield chr(int(''.join(map(str,b)),2))

rawDescription: Is there a better way to convert from decimal to binary in python?


code:
self.filelocation = []
for i in range(6):
    #CREATE A TEXTBOX
    self.filelocation.append(Entry(self.master))
    self.filelocation[i]["width"] = 60
    self.filelocation[i].focus_set()
    self.filelocation[i].grid(row=r,column=1)

rawDescription: Tkinter set value of Button's corresponding Entry box


code:
def wrapper (sign):
    def makeQuadrant (x, y):
        return (sign [0] * x, sign [1] * y)
    return makeQuadrant

quadrant = [wrapper (sign) for sign in ((1, -1), (1, 1), (-1, 1), (-1, -1))]

rawDescription: For Python 3.3, how can I make a list of functions using one lambda statement?


rawDescription: For Loop efficiency when using enumerate or other functions


rawDescription: Combine and compare two sets of stacked data in pygal


code:
import re

consequitivedots = re.compile(r'\.{3,}')
consequitivedots.sub('', inputstring)

rawDescription: Remove consecutive dots(periods) from a string?


code:
class GroupWriteRotatingFileHandler(handlers.RotatingFileHandler):

    def doRollover(self):
        """
        Override base class method to make the new log file group writable.
        """
        # Rotate the file first.
        handlers.RotatingFileHandler.doRollover(self)

        # Add group write to the current permissions.
        currMode = os.stat(self.baseFilename).st_mode
        os.chmod(self.baseFilename, currMode | stat.S_IWGRP)

rawDescription: Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file?


code:
import dumbdbm as dbm

g = dbm.open('store.db')
g.update([(str(i),pickle.dumps(j)) for i,j in enumerate(d)])
g.close()

rawDescription: Pickling a list consisting of 'n' 2-tuple values


code:
a = A()
a.thing
a.thing()

rawDescription: __getattr__ equivalent for methods

description: __getattr__ equivalent for methods


rawDescription: pandas dataframe groupby summation

description: Pandas dataframe groupby summation


code:
def overview(request):
    selection = None
    if request.GET:
        form = ManageFeedsForms(request.GET)
        if form.is_valid():
            selection = form.cleaned_data['active_feed']
    else:
        # Empty ManageFeedsForms
        form = ManageFeedsForms()

    return render_to_response('feed_management/home.html',
                              {'header_title': 'Feeds',
                               'feed_form' : form,
                               'selection' : selection,
                              },
                             context_instance=RequestContext(request))

rawDescription: Django Forms: Get selected item from ModelChoiceField?


code:
stemmed_list = []
for str in [word for word in data0 if word not in (stopwords.words('english'))]:
    stemmed_list.append(ps.stem(str))

rawDescription: Stemming process not working in Python

description: Stemming process not working in Python


rawDescription: Pythonic way to test if a row is in an array


code:
from bitstring import Bits
a = [3,1,2,6,4,10]  # some unsigned integers to encode
p = 5               # number of bits of precision to use

rawDescription: Writing a numpy array to binary file with variable integer precision


code:
import pandas as pd
import numpy as np
# Setup your dataframe
df = pd.DataFrame(columns=["Head", "Chr", "Start", "End", "Trans", "Num"])
df["Head"] = ["A", "A", "A", "B", "B", "B", "B", "B"]
df["Chr"] = [1]*8
df["Start"] = [29554, 30564, 30976, 36091, 35491, 35184, 36083, 35491]
df["End"] = [30039, 30667, 31097, 35267, 34544, 35711, 35235, 120765]
df["Trans"] = ["ENST473358", "ENST473358", "ENST473358",
               "ENST417324", "ENST417324", "ENST417324",
               "ENST461467","ENST461467"]
df["Num"] = [1, 2, 3, 1, 2, 3, 1, 2]

# Change how we index the frame
df.set_index(["Trans", "Num"], inplace=True)

# Get only unique indexes
unique_trans = list(set(df.index.get_level_values('Trans')))

# Access each index
for trans in unique_trans:
    max_num = max(df.ix[trans].index.values)

    start = df.ix[trans]["Start"].copy()
    df.loc[trans, "Start"] = np.array(df.ix[trans]["End"]) + 10
    df.loc[trans, "End"] = np.array(start.shift(-1) - 10)
    df.loc[(trans, max_num), "End"] = np.nan

print(df)

rawDescription: Changing the columns in DataFrame with respect to values in other columns


code:
from types import ModuleType, FunctionType

import foo as _foo

SANITIZE = "value 2"

def rebuild_function(func, glob):
    """Rebinds the globals in the given functions to globals in
    this module  by default"""
    new_func = FunctionType(func.func_code,
                            glob,
                            func.func_name,
                            func.func_defaults,
                            func.func_closure)
    return new_func

def rebuild_class(cls, glob):
    metatype = type(cls)
    dct = cls.__dict__.copy()
    for key, value in dct.items():
        if isinstance(value, FunctionType):
            dct[key] = rebuild_function(value, glob)
    return metatype(cls.__name__, cls.__bases__, dct)

def rebuild_module(mod,glob):
    new_module = ModuleType(mod.__name__)
    for key, value in mod.__dict__.items():
        if isinstance(value, FunctionType):
            value = rebuild_function(value, glob)
        elif isinstance(value, type):
            value = rebuild_class(value, glob)
        setattr(new_module, key, value)
    return new_module

foo = rebuild_module(_foo, globals())

__all__ = ["foo", "SANITIZE"]

rawDescription: Alter module variables in one module while it doesn't change in the original


code:
class URLOpener():
    def opener(self,user_agent):
        cj=cookielib.CookieJar()
        #Process Hadlers
        opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
        opener.addheaders=[
                        ('User-Agent', user_agent),
                        ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
                        ('Accept-Language', 'en-gb,en;q=0.5'),
                        ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'),
                        ('Keep-Alive', '115'),
                        ('Connection', 'keep-alive'),
                        ('Cache-Control', 'max-age=0'),
                    ]
        return opener

    #Openers with different User-Agents
    def opener_list(self,f_path):
        #f_path is a path to the file that contains browsers
        f=open(f_path, 'r+')
        count=0
        user_agent_list=list()
        for line in f.xreadlines():
            count+=1
            user_agent_list.append(line[:-1])
        openers=[self.opener(user_agent) for user_agent in user_agent_list]
        return openers

rawDescription: Mechanize random User-Agent

description: Mechanize random User-Agent


code:
#in case it is not multipart
import email

mail = email.message_from_string(raw_message)
payload = mail.get_payload(decode=True)

mail_dico = { elt.split(":",1)[0].strip():elt.split(":", 1)[1].strip() for elt in payload.split("\n") if ":" in elt and " " not in elt.split(':')[0].strip()}

rawDescription: Python email parse non multipart

description: Python email parse non multipart


rawDescription: Face Recognition - How to return the correct image?


code:
import datetime
import dateutil.relativedelta as relativedelta

def next_month(date):
    weekday=relativedelta.weekday(date.isoweekday()-1)
    weeknum=(date.day-1)//7+1
    weeknum=weeknum if weeknum<=4 else 4
    next_date=date+relativedelta.relativedelta(
        months=1,day=1,weekday=weekday(weeknum))
    return next_date

start=datetime.date(2011,8,1)
for i in range(31):
    date=start+datetime.timedelta(days=i)
    next_date=next_month(date)
    print('{d} --> {n}'.format(d=date,n=next_date))

rawDescription: Python: Know the second wednesday of the next month with a given date


code: {k:[e if e is not None else 'None' for e in v] for k,v in di.items()}

rawDescription: Replacing items in a dictionary of lists in Python


code:
from peak.rules import abstract, when

@abstract
def serialize_object(object, target):
    pass

@when(serialize_object, (MyStuff, BinaryStream))
def serialize_object(object, target):
    target.writeUInt32(object.identifier)
    target.writeString(object.payload)

@when(serialize_object, (MyStuff, XMLStream))
def serialize_object(object, target):
    target.openElement("my-stuff")
    target.writeAttribute("id", str(object.identifier))
    target.writeText(object.payload)
    target.closeElement()

rawDescription: What is the best-maintained generic functions implementation for Python?


code:
generator = cycle([[0, 3], [1, 0], [3, 1]], 0, Ellipsis)
generator.next()
0
generator.next()
3
generator.next()
1
generator.next()
0
generator.next()
3
generator.next()
1
generator.next()
0
generator.next()
3

rawDescription: How to join links in Python to get a cycle?

description: Join links in Python to get a cycle


code:
def main(data):
    p = Pool(len(data)) #number of processes = number of CPUs
    keys, values= zip(*data.items()) #ordered keys and values
    start = time.time()
    processed_values= p.map( f, values )
    result= dict( zip(keys, processed_values ) )
    print("multi: {}".format(time.time() - start))
    p.close() # no more tasks
    p.join()  # wrap up current tasks

    start = time.time()
    processed_values = map(f, values)
    result2 = dict( zip(keys, processed_values ) )
    print("non-multi: {}".format(time.time() - start))
    assert(result == result2)

rawDescription: python - multiprocessing is slower than sequential

description: Python - multiprocessing is slower than sequential


rawDescription: Removing the first part of a concatenated string with Python


rawDescription: Numpy: change max in each row to 1, all other numbers to 0


code: getattr(syslog, "LOG_LOCAL0") # syslog.LOG_LOCAL0 for all intents and purposes

rawDescription: Getting value of a functions attribute from a string


code:
dictionary = {'name': 'Scott', 'title': 'esquire'}
list_ = ['name', 'age', 'title']

def members(dictionary, list_):
    # Define counter
    cant = 0
    # Iter over all list items and check if appear in  dictionaty.keys().
    for elem in list_:
        # Check if elem in dictionay.keys()
        if elem in dictionary.keys():
            # If true increment counter
            cant = cant + 1

    # Finally return cant
    return cant

print(members(dictionary, list_))

rawDescription: Using a function to return a count of keys within a dictionary


rawDescription: How do I union a list of lists based on a common string in the lists, Python

description: Union a list of lists based on a common string in the lists, Python


code:
# idiom to get path of project
import os
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
# url prefix for user uploaded files, stuff that django has to serve directly
MEDIA_URL = '/media/'
# url prefix for static files like css, js, images
STATIC_URL = '/static/'
# url prefix for *static* /admin media
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
# path to django-served media
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
# path used for collectstatic, *where the webserver not django will expect to find files*
STATIC_ROOT = '/home/user/public_html/static'
# path to directories containing static files for django project, apps, etc, css/js
STATICFILES_DIRS = (
    os.path.join(PROJECT_PATH, 'static'),
)
# List of finder classes that know how to find static files in various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
# Required for all the magic
INSTALLED_APPS = (
    'django.contrib.staticfiles',
)

rawDescription: What is the most common way to configure static files in debug and production for Django


rawDescription: How to build an xml template with variable attributes from scratch

description: Build an xml template with variable attributes from scratch


code: return render(request, 'polls/productpage.html', {'product': product}, {'image':image})

rawDescription: Django multiple contexts within a single view


code: cursor.execute("SELECT * FROM hiking WHERE name = '%s'"% name)

rawDescription: Python cursor.fetchall() returns empty tuple


code:
DA, DB, DC = range(3)
a.sum(DA)

rawDescription: Naming dimensions in python?

description: Naming dimensions in python


code:
import subprocess
params = ['convert', 'pdf_file', 'thumb.jpg']
subprocess.check_call(params)

rawDescription: Python PDF thumbnail preview generation

description: Python PDF thumbnail preview generation


code:
D = {}
def P(n,s,x):
    if n > s*x or x <= 0: return 0
    if n == s*x: return 1
    if (n,s,x) not in D:
        D[(n,s,x)] = sum(P(n-i*x, s-i, x-1) for i in xrange(s))
    return D[(n,s,x)]

rawDescription: An algorithm for randomly generating integer partitions of a particular length, in Python?


code:
class Entity(object):
    """Base class that should not be instantiated on its own -- only
       exists to be inherited from. Use Player() and Computer() instead"""
    def __init__(self,name=None):
        if name is None:
            name = input("What's your name? ")
        self.name = name
        self.myturn = False
    def __str__(self):
        # this magic function means calling str(self) returns str(self.name)
        # included so I can do print(player)
        return self.name

    def makemove(self,choice):
        """finds the global s and subtracts a given choice from it,
           printing the choice and the result to the user."""
        global s
        s -= choice
        print("{} chooses {}, leaving {}".format(self,choice,s))
        return choice
    def activate(self):
        self.myturn = True
        return self
    def deactivate(self):
        """does exactly self.myturn = False"""
        self.myturn = False

class Player(Entity):
    """A player-controlled Entity"""
    def getchoice(self):
        """Prompts the user for a choice, ensuring it's between 1 and 6, then
           calls Entity's makemove() with that as an argument"""
        choice = None
        while choice not in range(1,7):
            choice = int(input("Pick a number between 1 and 6: "))
        return super().makemove(choice)

class Computer(Entity):
    def __init__(self):
        super().__init__(name="Computer Player")
        #overrides to ensure every Computer object has the name Computer Player

    def getchoice(self):
        """grabs a number for the computer, and makes its move"""
        global s
        choice = s%7
        if choice == 0: #edge case where computer goes first on an s where s%7==0
            choice = random.randint(1,6)
        return super().makemove(choice)

class Game(object):
    """Class defining an instance of the Game

FUNCTIONS:
 Game.start() <-- use this to start the game"""

    def __init__(self,playerArray=[]):
        """defines s as a global, ensures the players array is built
           correctly, and gives s a random int value between 1-100"""
        global s
        if type(playerArray) is Player:
            playerArray = [playerArray]
        while len(playerArray) < 2:
            playerArray.append(Computer())
        self.players = playerArray
        s = random.randint(1,100)

    def start(self):
        """Let's play!"""

        global s
        print ("""
====================================
 THE GAME BEGINS NOW!!!
 We will begin with a value of: {:3}
====================================""".format(s).lstrip())
        turn = random.randint(1,len(self.players))-1

        while True:
            try:active_player = self.players[turn].activate()
            except IndexError: print(turn)
            choice = active_player.getchoice()
            if s <= 0: break
            active_player.deactivate() # is active_player.myturn = False
            turn += 1
            if turn == len(self.players): turn = 0 #wrap the list
        for player in self.players:
            #this will execute the turn s becomes zero
            if player.myturn:
                winner = player
                break
        print("Winner: {}".format(winner))

import random

game = Game()
game.start()

rawDescription: Need help writing algorithm in Python/Sage


rawDescription: Fast and pythonic way to find out if a string is a palindrome


code:
import multiprocessing as mp
import time
import logging

logger = mp.log_to_stderr(logging.INFO)

hostlist = ['h1', 'h2', 'h3', 'h4']*3
poolsize = 2

class HClass:
    def __init__(self, hostname="default"):
        self.hostname = hostname

    def go(self):
        logger.info('processing {h}'.format(h = self.hostname))
        time.sleep(1)
        return self.hostname

def worker(host):
    h = HClass(hostname = host)
    return h.go()

result = []
def on_return(retval):
    result.append(retval)

if __name__ == "__main__":
    pool = mp.Pool(poolsize)
    for host in hostlist:
        pool.apply_async(worker, args = (host,), callback = on_return)
    pool.close()
    pool.join()
    logger.info(result)

rawDescription: Python multiprocessing pool - iterating over objects methods?


code:
class NestedArray(object):
    def __init__(self, x, y, defaultValue=0):
        self.x = x
        self.y = y
        self.array = [[defaultValue]*y for a in xrange(x)]

    def __len__(self):
        return self.x * self.y

    def __getitem__(self, key):
            return self.array[key]

    def __setitem__(self, key, value):
            self.array[key] = value

rawDescription: how to get the length of a 2-d counter

description: Get the length of a 2-d counter


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

df = pd.DataFrame(np.random.poisson(5, size=(100, 5)))

fig, ax = plt.subplots()
box = df.boxplot(ax=ax, sym='')
ax.margins(y=0.05)
plt.show()

rawDescription: Matplotlib - How do I set ylim() for a series of plots?


code:
def passMethod(obj, method):
    return getattr(obj, method)()

passMethod('Hi', 'lower')

rawDescription: Passing a method in python

description: Passing a method in python


code:
colLabels=("Structure", "Energy", "Density")
nrows, ncols = len(clust_data)+1, len(colLables)
hcell, wcell = 0.3, 1.
hpad, wpad = 0, 0

fig=plt.figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad))
ax = fig.add_subplot(111)
#remove axis ticks and labels
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
#hide the spines
for sp in ax.spines.itervalues():
    sp.set_color('w')
    sp.set_zorder(0)
#do the table
the_table = ax.table(cellText=clust_data,
          colLabels=colLabels,
          loc='center')
#put the table in front of the axes spines
#for some reason zorder is not a keyword in ax.table
the_table.set_zorder(10)
plt.savefig("table.png")

rawDescription: Creating tables in matplotlib

description: Creating tables in matplotlib


code:
a = ['a', 'b', 'c']
b = ['b', 'c']

pos = index(a, b)
if pos >= 0:
    c = list(a)
    del c[pos:pos + len(b)]

# c = ['a']

rawDescription: Check if list of strings contains string sequence


code:
def objwalk(obj, path=(), memo=None):
    if memo is None:
        memo = set()
    iterator = None
    if isinstance(obj, dict):
        iterator = iteritems
    elif isinstance(obj, (list, set)) and not isinstance(obj, string_types):
        iterator = enumerate
    if iterator:
        if id(obj) not in memo:
            memo.add(id(obj))
            for path_component, value in iterator(obj):
                if isinstance(value, tuple):
                    obj[path_component] = value = list(value)
                for result in objwalk(value, path + (path_component,), memo):
                    yield result
            memo.remove(id(obj))
    else:
        yield path, obj

rawDescription: Iterate over nested lists, tuples and dictionaries


code:
Color.red.func = str.lower
Color.red("LOWERCASE")  # "lowercase"

rawDescription: Make IntEnum members callable while keeping their comparison behavior


code:
[('Name', 'some filename.mp3'),
 ('Encoder', 'Gogo (after 3.0)'),
 ('Bitrate', '131'),
 ('Name', 'another filename.mp3'),
 ('Encoder', 'iTunes'),
 ('Bitrate', '128')]

rawDescription: Parse XML file into Python object

description: Parse XML file into Python object


code:
import pandas as pd
import numpy as np
from pandas import DataFrame
import datetime
# Create a year's worth of data
base = datetime.date.today() - datetime.timedelta(365)
Datelist = [base + datetime.timedelta(days = x) for x in range(365)]
DF = DataFrame(np.random.rand(365), index = Datelist)

# Create a Seasonal Dictionary that will map months to seasons
SeasonDict = {11: 'Winter', 12: 'Winter', 1: 'Winter', 2: 'Spring', 3: 'Spring', 4: 'Spring', 5: 'Summer', 6: 'Summer', 7: 'Summer', \
8: 'Autumn', 9: 'Autumn', 10: 'Autumn'}

# Write a function that will be used to group the data
def GroupFunc(x):
    return SeasonDict[x.month]

# Call the function with the groupby operation.
Grouped = DF.groupby(GroupFunc)
Grouped.sum()

rawDescription: Pandas, groupby and summing over specific months


rawDescription: Reading Table Contet In Header And Footer In MS-Word File Using Python


code: minsub('this is a test string', 'tist')

rawDescription: Finding shortest substring containing certain characters in linear time


rawDescription: numpy - how to outer join arrays

description: Numpy - how to outer join arrays


code:
class Rectangle:

    def __init__(self, length, width): # this initializes the object with the given parameters
        self.__length = length # assign length
        self.__width = width # assign width

    def set_length(self, length): # this method allows us pass the Rectangle object a value and set the object's length to the given value
        self.__length = length # assign length

    def set_width(self, width): # had 'model' here # same thing, for width
        self.__width = width # assign width

    def get_length(self): # this method does one thing...
        return self.__length # return the Rectangle object's length

    def get_width(self): # and same for width
        return self.__width

    def get_area(self): # this actually does something: multiplies width by height and returns that value
        return self.get_width() * self.get_length() # underscores were wrong

    def get_perimeter(self): # similarly, this adds double the length to double the width and returns that value
        return self.get_width() * 2 + self.get_length() * 2 # underscores were wrong, missing self

def main(): # our main program, which will test our Rectangle class
    length = float(input('Length? ')) # request a length and turn that string into a float
    width = float(input('Width? ')) # request a width and turn that string into a float
    rectangle = Rectangle(length, width) # create a new Rectangle object with the given length and width
    print(rectangle.get_length(), rectangle.get_width()) # print the object's length and width, using the getters
    print(round(rectangle.get_area(), 2)) # round the area to 2 places and print it
    print(round(rectangle.get_perimeter(), 2)) # round the perimeter to 2 places and print it
    rectangle.set_length(22.345) # calls the Rectangle object's length setter and passes it a new value, which will set the object's length to the given value
    rectangle.set_width(15.789) # same for width
    print(round(rectangle.get_area(), 2)) # print the area again to see the new value
    print(round(rectangle.get_perimeter(), 2)) # print the perimeter again to see the new value

main() # call our main method - without this, nothing happens

rawDescription: Rectangle OOP/classes

description: Rectangle OOP/classes


code:
item_details = {}
for key, value in json_file['document']:
    item_details[key] = value['itemDetails']

rawDescription: Parsing json file with changeable structure in Python


code: a.dtype.type is np.string_

rawDescription: Numpy: Check array for string data type

description: Numpy: Check array for string data type


code:
import os
import sys
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
APPS_ROOT = os.path.join(SITE_ROOT, 'apps')
sys.path.append(APPS_ROOT)

rawDescription: How do I use Django South when my app is inside another directory?

description: Use Django South when my app is inside another directory


code:
for i in count(1):
     res = lookup(i)
     if res is None: break
     yield res

rawDescription: for(i=0;True;i++) in python?

description: For(i=0;True;i++) in python


code:
fh = open("arduino.txt")
for line in fh:
    pass
last = line

rawDescription: Python specific item from last line

description: Python specific item from last line


code:
import re
regex = re.compile("^(?P<numbers>\d*)(?P<letters>\w*)$")

def myFunction(entry):
  (numbers, letters) = regex.search(entry).groups()
  return (numbers or None, letters or None)

map(myFunction, ['01123absd', 'bsdf', '02454'])

rawDescription: How to split a Python string with numbers and letters?

description: Split a Python string with numbers and letters


rawDescription: python regex word repeat time

description: Python regex word repeat time


rawDescription: How to reverse tree-like linkages in a set?

description: Reverse tree-like linkages in a set


code:
read_a[0] = random.randint(500,1000)
read_a[1] = a[0] + read_a[0] - a[1]
# nota bene: read_a[0] is in fact read_b[len(a)-1]

rawDescription: How to index and automate processing of list using input csv file

description: Index and automate processing of list using input csv file


code:
pygame.draw.circle(self.surface, pygame.Color("black"),
                           (int(self.surface.get_width()/2),
                            int(self.surface.get_height()/2)),
                           self.r)

rawDescription: why I'm getting a square instead of a circle in pygame?

description: Why I'm getting a square instead of a circle in pygame


code: #python2.5 setup.py

rawDescription: In Linux, how do I compile and install code for different versions of Python?


code:
def absolute(request):
    urls = {
        'ABSOLUTE_ROOT': request.build_absolute_uri('/')[:-1].strip("/"),
        'ABSOLUTE_ROOT_URL': request.build_absolute_uri('/').strip("/"),
    }

    return urls

rawDescription: How to get full url from django request

description: Get full url from django request


rawDescription: Python miminum length/max value in dictionary of lists


code:
import math

def sieve(n):
    nums = [True] * (n+1)
    nums[:2] = [False]*2
    nums[4::2] = [False] * math.ceil((n-3)/2)
    for i in range(3, int((n+1)**.5)+1, 2):
        if nums[i]:
            for j in range(i*i, n+1, 2*i):
                nums[j] = False
    return [i for i,k in enumerate(nums) if k]

rawDescription: Find the number of divisors of (N!)^2

description: Find the number of divisors of (N!)^2


code:
import scipy.stats as stats
x = stats.norm.rvs(size = 100)
stats.normaltest(x)

rawDescription: Scipy Normaltest how is it used?

description: Scipy Normaltest how is it used


code:
def all(list, condition):
  for a in list:
    if not condition(a):
      return false
  return true

rawDescription: How does all() in python work on empty lists


code:
import itertools

def parse_ranges(ranges):
    for chunk in ranges.split(', '):
        if '-' not in chunk:
            chunk = chunk + '-' + chunk  # Turns 7 into 7-7

        start, end = chunk.split('-')

        if end:
            yield from range(int(start), int(end) + 1)
        else:
            yield from itertools.count(int(start))

rawDescription: How to represent a dynamic list of ranges?

description: Represent a dynamic list of ranges


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

w = next(n for n,v in filter(lambda t: isinstance(t[1],list), globals().items()) if value in v)
print(w)

rawDescription: Find if value exists in multiple lists

description: Find if value exists in multiple lists


rawDescription: How to Read Reg_Binary type values in string format from Registry in python


code:
class SecondFrame(Tkinter.Frame):

    def __init__(self, *args, **kwargs):
        Tkinter.Frame.__init__(self, *args, **kwargs)
        self.l = Tkinter.Label(self, text="Selected date")
        self.l.pack()
        self.pack()

    def update_lable(self, x):
        self.l['text'] = x;

def test2():
    import sys
    root = Tkinter.Tk()
    root.title('Ttk Calendar')

    ttkcal = Calendar2(firstweekday=calendar.SUNDAY)
    ttkcal.pack(expand=1, fill='both')

    if 'win' not in sys.platform:
        style = ttk.Style()
        style.theme_use('clam')

    sf = SecondFrame(Tkinter.Toplevel())

    ttkcal.set_selection_callbeck(sf.update_lable)

    root.mainloop()

rawDescription: python calendar widget - return the user-selected date

description: Python calendar widget - return the user-selected date


code: df

rawDescription: How to convert list into set in pandas?

description: Convert list into set in pandas


rawDescription: Ignore minimum size when resizing QWidget


code:
# add the handler (where you create the control)
myRichTextCtrl.GetBuffer().AddHandler(wx.richtext.RichTextXMLHandler())

rawDescription: WxRichTextCtrl python retrieving entries from file


code:
from sklearn.preprocessing import LabelBinarizer
import numpy as np

class MyLabelBinarizer(LabelBinarizer):
    def transform(self, y):
        Y = super().transform(y)
        if self.y_type_ == 'binary':
            return np.hstack((Y, 1-Y))
        else:
            return Y

    def inverse_transform(self, Y, threshold=None):
        if self.y_type_ == 'binary':
            return super().inverse_transform(Y[:, 0], threshold)
        else:
            return super().inverse_transform(Y, threshold)

rawDescription: sklearn LabelBinarizer returns vector when there are 2 classes

description: Sklearn LabelBinarizer returns vector when there are 2 classes


code:
def __copy__(self):
    return MyClass(self.a, self.b)

rawDescription: how to make copies of Cython objects?

description: Make copies of Cython objects


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

plt.close('all')

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)

x = 10 * np.outer(np.cos(u), np.sin(v))
y = 10 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))

# When creating `c` from data, `c` needs to be normalized to {0-1}
c = np.zeros_like(z)
c[30:40,30:40] = 1

ax.plot_surface(x, y, z, rstride=2, cstride=2, facecolors=plt.cm.PuBu(c))

rawDescription: How to coloring specific region (or grid) on 3d object (i.e. sphere) in matplotlib3d

description: Coloring specific region (or grid) on 3d object (i.e. sphere) in matplotlib3d


code:
db.coll.aggregate([
    { "$group" : {
           "_id" : "$name",
           "memory": { "$addToSet": "$memory" }
    }}
]);

rawDescription: union of two mongoDB documents

description: Union of two mongoDB documents


code:
def bubbleSort(alist):
    for passnum in range(len(alist)-1, 0, -1):
        for i in range(passnum):
            if alist[i] > alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp
    return alist

def main():
    lines = []
    print("Enter names (hit enter twice to bubble-sort):")
    while True:
        line = input("%3i: " % (len(lines)+1))
        if not line:
            break
        lines.append(line)
    print("Sorted names:")
    for i, name in enumerate(bubbleSort(lines), 1):
        print("%3i. %s" % (i, name))

main()

rawDescription: How to specify number of inputs and how to get each input in a new line?

description: Specify number of inputs and how to get each input in a new line


rawDescription: Python Efficiency / Optimization Project Euler #5 example


rawDescription: Selecting a column on a multi-index pandas DataFrame


code:
import re

oldtext = """\
This would keep paragraphs separated.
This would keep paragraphs separated.

This would keep paragraphs separated.
\tThis would keep paragraphs separated.

\rWhen, in the course
of human events,
it becomes necessary
\rfor one people
"""

newtext = re.sub(r'(?<!\n)\n(?![\n\t])', ' ', oldtext.replace('\r', ''))

rawDescription: Most efficient way to delete needless newlines in Python


code:
updated = Votes.objects(pizza=Spicy,
                        vote=FiveStar,
                        nin__voters=Rozza).update(push__voters=Rozza)

rawDescription: MongoDB, MongoEngine: unique list items

description: MongoDB, MongoEngine: unique list items


code: ES["some_other_key"] = {"some_other_sub_key" : "whatever"}

rawDescription: Unable to store or print json data in exact same format


code:
(None, 'phase', '1')
(None, 'apartment', '2')
('block baz', None, None)

rawDescription: Conditioning on Regex

description: Conditioning on Regex


code:
import re
from htmlentitydefs import codepoint2name

def convert_match_to_named(match):
    num = int(match.group(1))
    if num in codepoint2name:
        return "&%s;" % codepoint2name[num]
    else:
        return match.group(0)

def defang_named(string):
    return re.sub('&#(\d+);', convert_match_to_named, defang(string))

rawDescription: Some Basic Python Questions

description: Some Basic Python Questions


code: my_fields = {u'question': {'name': 'CharField', 'attrs': {'max_length': 512} }}

rawDescription: Python : convert unicode string to raw object/text


code:
with sqlite3.connect("studentscores.db") as db:
            cursor=db.cursor()
            sql = "insert into tbl_scores (StudentID, DateOfScore, Score) values (?,?, ?)"
            cursor.execute(sql,(StudentID,nDateOfScore,nScore))
            db.commit()

rawDescription: Is it possible to write a python program that will enable you to sort the content of a text file in python


code:
x = y = [1, 1]
x = 2 # `x` now points to a new object, number of references to [1, 1] decreased by 1
x, y

rawDescription: Updating elements in nested list using 'for' won't work in python list


code:
#models.py
class MovieImage(models.Model):
    movie = models.ForeignKey(Movie,null=True,blank=True)
    src   = models.URLField(max_length=255, null=True)

rawDescription: Django get the foreign key object value

description: Django get the foreign key object value


code: lambda_function = lambda height, width, src, mask: [[src[h][w] if mask[h][w] > 0 else mask[h][w] for w in range(width)] for h in range(height)]

rawDescription: Python lambda with double loops

description: Python lambda with double loops


code: stdout, stderr = p.communicate()

rawDescription: Python: Hide sub-process print out on the terminal and continue the script while sub is running


code: df.groupby(['p1', 'p2']).mean()

rawDescription: Pandas: Calculate average for all entries that only differ in two columns


rawDescription: XPath: Assessing an Error in this Line of Code?


code:
# Import the things you need
import numpy as np
import matplotlib.pyplot as plt

# Create a matplotlib figure
fig, ax = plt.subplots()

# Create values for the x axis from -pi to pi
x = np.linspace(-np.pi, np.pi, 100)

# Calculate the values on the y axis (just a raised sin function)
y = np.sin(x) + 1

# Plot it
ax.plot(x, y)

# Select the numeric values on the y-axis where you would
# you like your labels to be placed
ax.set_yticks([0, 0.5, 1, 1.5, 2])

# Set your label values (string). Number of label values
# sould be the same as the number of ticks you created in
# the previous step. See @nordev's comment
ax.set_yticklabels(['foo', 'bar', 'baz', 'boo', 'bam'])

rawDescription: words as y-values in pyplot/matplotlib

description: Words as y-values in pyplot/matplotlib


code:
def build_authentication_redirect(self):
            args = {}
            args["client_id"]=self.app_id
            args["redirect_uri"]=self.redirect_uri
            args["scope"]=",".join(self.req_perms)
            redirect_url = "https://www.facebook.com/dialog/oauth?"+urllib.urlencode(args)
            redirect_code = """
                    <script type="text/javascript">
                    top.location.href='%s';
                    </script>
            """ % redirect_url;
            return HttpResponse(redirect_code,mimetype="text/html")

rawDescription: How to redirect the url after logging into Facebook?

description: Redirect the url after logging into Facebook


code:
import lxml.etree as ET

data = """<note>
    <col1>Tove</col1>
    <col2>J</col2>
    <test2>
        <a> a </a>
        <b> b </b>
        <c> c </c>
        <d> d </d>
    </test2>
    <code
        a="1"
        b="2"
        c="3"
    />
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>
"""

tree = ET.fromstring(data)

for note in tree.xpath("//note"):
    test2_values = [value.strip() for value in note.xpath(".//test2/*/text()")]
    code_attrs = note.find("code").attrib

    print(test2_values)
    print(code_attrs)

rawDescription: extracting value from xml node

description: Extracting value from xml node


rawDescription: How to store lists over criteria in Python?

description: Store lists over criteria in Python


code: ''.join([i for i in contentjoined if i in aminoacids])

rawDescription: Remove character from string if its not in a list...?


code:
def active_users():
    return User.select(lambda user: not user.disabled)

def name_starts_with(query, prefix):
    return query.filter(lambda user: user.name.startswith('prefix'))

rawDescription: Writing select functions for customized Pony


code:
import numpy as np
import pandas as pd
import io

data = '''\
                      val
2007-08-07 18:00:00    1
2007-08-08 00:00:00    2
2007-08-08 06:00:00    3
2007-08-08 12:00:00    4
2007-08-08 18:00:00    5
2007-11-02 18:00:00    6
2007-11-03 00:00:00    7
2007-11-03 06:00:00    8
2007-11-03 12:00:00    9
2007-11-03 18:00:00   10'''

df = pd.read_table(io.BytesIO(data), sep='\s{2,}', parse_dates=True)

chunksize = 5
chunks = len(df)//chunksize

df['Date'] = np.repeat(df.index.date[::chunksize], chunksize)[:len(df)]
index = df.index.time[:chunksize]
df['Time'] = np.tile(np.arange(chunksize), chunks)
df = df.set_index(['Date', 'Time'], append=False)

df = df['val'].unstack('Date')
df.index = index
print(df)

rawDescription: How to properly pivot or reshape a timeseries dataframe in Pandas?

description: Properly pivot or reshape a timeseries dataframe in Pandas


rawDescription: How to write to a specific line in a text file

description: Write to a specific line in a text file


code:
outdeg = G.out_degree()
to_remove = [n for n in outdeg if outdeg[n] == 1]

rawDescription: How to only keep nodes in networkx-graph with 2+ outgoing edges or 0 outgoing edges?

description: Only keep nodes in networkx-graph with 2+ outgoing edges or 0 outgoing edges


code: myNewDict = {"entry": "word1", "count": 12, "entry": "word2", "count": 18, "entry": "word3", "count": 4, "entry": "word4", "count": 45}

rawDescription: Converting a python dictionary to a JSON - like object


code:
mask = mask.repeat(4, axis=0).repeat(4, axis=1)
# Then you apply the mask using
values = data[mask]

rawDescription: Slicing array in regions - Python

description: Slicing array in regions - Python


code:
def setModelData(self, editor, model, index):
    cbIndex = editor.currentIndex()
    model.setData(index, cbIndex, Qt.UserRole+1)
    # we want a nice displayable though
    model.setData(index, countryIndexToDisplayable(cbIndex), Qt.DisplayRole)

rawDescription: Displaying QComboBox text rather than index value in QStyledItemDelegate


code:
result = df.groupby("c3")[["c1","c2"]].apply(lambda x: dict(x.values)).to_dict()
pprint.pprint(result)

rawDescription: Pandas: Most efficient way to make dictionary of dictionaries from DataFrame columns


rawDescription: Python: Concatenate (or clone) a numpy array N times


code:
if user_input == "some_command":
    do_something(appropriate, variables)

rawDescription: How do I automatically pass arguments to a function on certain objects

description: Automatically pass arguments to a function on certain objects


code:
def firstlast(iterator):
    """ Returns the first and last value of an iterator"""
    first = last = iterator.next()
    for value in iterator:
        last = value
    return first, last

maxlen = max(len(x) for x in ranges) + 1
test_range = ('%0*d' % (maxlen, i) for i in xrange(10 ** maxlen))
result = dict((firstlast(gr), id)
              for id, gr in itertools.groupby(test_range, key=id_for_value))

rawDescription: Building a "complete" number range w/out overlaps


code:
letter = 'x'
result = [a for a in a_lst if letter in a]
if result:
    print('yes', letter)
else:
    print('no', letter)

rawDescription: Checking charcters in a string and outputing a Single message


code:
- Epytext / Javadoc
"""
@param param1: Description of param1
@type param1: type of param1

@return: description of returned value
@rtype: type of returned value
"""

rawDescription: Python: Standard way to denote return and parameter types


code:
qs = dict( (k, v if len(v)>1 else v[0] )
           for k, v in urlparse.parse_qs(postVars).iteritems() )

rawDescription: BaseHTTPServer, extracting variable from POST single value


code:
enable()
import package
disable()

rawDescription: Python: Setting the metaclass for all files in a folder


code:
library(iterators)
abc <- iter(c('a','b','c'))
nextElem(abc)
## [1] "a"
nextElem(abc)
## [1] "b"
nextElem(abc)
## [1] "c"

rawDescription: Generator functions in R

description: Generator functions in R


code: approved = dom.getAttribute('approved')

rawDescription: How to get sub attribute value in Python

description: Get sub attribute value in Python


code:
def read_config(section, location):
    config = configparser.ConfigParser()
    config.read(location)
    apple = config.get(section, 'apple',
                       vars=DefaultOption(config, section, apple=None))
    pear = config.get(section, 'pear',
                      vars=DefaultOption(config, section, pear=None))
    banana = config.get(section, 'banana',
                        vars=DefaultOption(config, section, banana=None))
    return apple, pear, banana

def save_to_config(section, location, apple, pear, banana):
    config = configparser.ConfigParser()

    config.read(location)
    if section not in config.sections():
        config.add_section(section)

    config.set(section, 'apple', apple)
    config.set(section, 'pear', pear)
    with open(location, 'wb') as cf:
        config.write(cf)

rawDescription: Python configparser getting and setting without exceptions


code:
#accepts class name (c) and attribute (attr)
def get(c,attr):
    #returns the attribute
    return getattr(c,attr)

rawDescription: Getting property named `foo`

description: Getting property named `foo`


code:
Implementation
class MostCommon(object):
    """Keep track the top-k key-value pairs.

    Attributes:
        top: Integer representing the top-k items to keep track of.
        store: Dictionary of the top-k items.
        min: The current minimum of any top-k item.
        min_set: Set where keys are counts, and values are the set of
            keys with that count.
    """
    def __init__(self, top):
        """Create a new MostCommon object to track key-value paris.

        Args:
            top: Integer representing the top-k values to keep track of.
        """
        self.top = top
        self.store = dict()
        self.min = None
        self.min_set = defaultdict(set)

    def _update_existing(self, key, value):
        """Update an item that is already one of the top-k values."""
        # Currently handle values that are non-decreasing.
        assert value > self.store[key]
        self.min_set[self.store[key]].remove(key)
        if self.store[key] == self.min:  # Previously was the minimum.
            if not self.min_set[self.store[key]]:  # No more minimums.
                del self.min_set[self.store[key]]
                self.min_set[value].add(key)
                self.min = min(self.min_set.keys())
        self.min_set[value].add(key)
        self.store[key] = value

    def __contains__(self, key):
        """Boolean if the key is one of the top-k items."""
        return key in self.store

    def __setitem__(self, key, value):
        """Assign a value to a key.

        The item won't be stored if it is less than the minimum (and
        the store is already full). If the item is already in the store,
        the value will be updated along with the `min` if necessary.
        """
        # Store it if we aren't full yet.
        if len(self.store) < self.top:
            if key in self.store:  # We already have this item.
                self._update_existing(key, value)
            else:  # Brand new item.
                self.store[key] = value
                self.min_set[value].add(key)
                if value < self.min or self.min is None:
                    self.min = value
        else:  # We're full. The value must be greater minimum to be added.
            if value > self.min:  # New item must be larger than current min.
                if key in self.store:  # We already have this item.
                    self._update_existing(key, value)
                else:  # Brand new item.
                    # Make room by removing one of the current minimums.
                    old = self.min_set[self.min].pop()
                    del self.store[old]
                    # Delete the set if there are no old minimums left.
                    if not self.min_set[self.min]:
                        del self.min_set[self.min]
                    # Add the new item.
                    self.min_set[value].add(key)
                    self.store[key] = value
                    self.min = min(self.min_set.keys())

    def __repr__(self):
        if len(self.store) < 10:
            store = repr(self.store)
        else:
            length = len(self.store)
            largest = max(self.store.itervalues())
            store = '<len={length}, max={largest}>'.format(length=length,
                                                           largest=largest)
        return ('{self.__class__.__name__}(top={self.top}, min={self.min}, '
                'store={store})'.format(self=self, store=store))

rawDescription: Efficiently keeping track of the top-k keys of a dictionary based on value


code:
longs = (np.random.rand(60, 1) + np.linspace(-np.pi, np.pi, 80000)).reshape(-1)
lats = np.sin(longs) + np.random.rand(len(longs)) * 0.1

bad_index = (longs>0) & (longs<1)
bad_longs = longs[bad_index]
bad_lats = lats[bad_index]

rawDescription: 3g coverage map - visualise lat, long, ping data


code:
import json
with open('outf.json', 'w') as f:
    json.dump(page, f)

rawDescription: Get information for Facebook page in Facebook API graph


code:
def all_perms(elements):
    if len(elements) <=1:
        return elements
    else:
        tmp = []
        for perm in all_perms(elements[1:]):
            for i in range(len(elements)):
                tmp.append(perm[:i] + elements[0:1] + perm[i:])
        return tmp

rawDescription: producing all the anagrams from a string python

description: Producing all the anagrams from a string python


code:
list(all_remainders(34, 5))
list(all_remainders(34, 17))
_

rawDescription: How do i get Python to show all possible remainders instead of just the one that occurs with the largest multiple of the number?

description: Get Python to show all possible remainders instead of just the one that occurs with the largest multiple of the number


code: re.findall( r"(?<=-arch )([^ ]+)", r"'-foo 23 -bar -arch ppc -arch i386 -isysroot -fno-strict-aliasing -fPIC'" )

rawDescription: Positionally matching substrings in Python


code:
def my_view(request):
    city_name = request.GET.get('place')
    sellers = Supplier.objects.filter(supplied_cities__cities=city_name)
    context = {'sellers' : sellers }
    return render_to_response('results.html', context, context_instance=RequestContext(request))

rawDescription: Filtering in Many to Many relationship in django


code:
class EventManager(models.Manager):
    def get_query_set(self):
     # Quick check to see what dates we should search within
     return super(EventManager, self).get_query_set().filter(event_date__range=(start_date, end_date))

class Event(models.Model):
    this_year = EventManager()
    ...

rawDescription: How to define date range that spans years, months in Django?

description: Define date range that spans years, months in Django


code: type(np.float32(1) / 2)

rawDescription: cython function output slightly different from python function output

description: Cython function output slightly different from python function output


rawDescription: call functions from a shared fortran library in python

description: Call functions from a shared fortran library in python


code:
parser = argparse.ArgumentParser()
parser.add_argument('--example', type=int, default=0)

rawDescription: Create arg string from ArgumentParser parsed args in Python


code: text = text.replace('\r', '').replace('\x1b[A', '')

rawDescription: How do I remove all non-standard characters from a file?

description: Remove all non-standard characters from a file


code:
mapping = collections.defaultdict(list)
for key, value in relations:
    mapping[key].append(value)

rawDescription: Python Detect if one-to-one onto mapping exists


code: counts = pd.DataFrame(counts, columns=['count'])

rawDescription: Plot number of occurrences from Pandas DataFrame


code:
a, b = func1()
print(a, b)
func2(a, b)

rawDescription: Python, simple example of multiple variables passed to another function


code:
with open("oniwa.dat") as fp:
    for line in fp:
        print(repr(line))

rawDescription: pandas shifts column names and fills last column with NAN

description: Pandas shifts column names and fills last column with NAN


code:
import itertools
items = [1, 2, 3]
itertools.combinations(items, 2)  # 2 -> yields tuples with 2 items
list(itertools.combinations(items, 2))

rawDescription: How can I compare each object with each?

description: Compare each object with each


code:
from django.core.cache import caches
cache = caches['bla_stats']
cache.get_where("b_%")
{"b_key1":"val1", "b_key2":"val2"}

rawDescription: Enumerating keys in Django Database Cache


code:
df['group1'].fillna(method='ffill', inplace=True)
df[df['group1'] == 'a']

rawDescription: Filter Pandas DataFrame by group with tag values


code:
for dir, dirs, files in os.walk(src):
    if any(f.endswith('.txt') for f in files):
        continue  # ignore this directory

    # do something with the files here, there are no .txt files.
    files = [os.path.join(dir, f) for f in files]

rawDescription: How to exclude files extension from os.walk

description: Exclude files extension from os.walk


code:
custom_dict = {
    'nand' : lambda x, y: not (x and y)
}

func_dict.update(custom_dict)

rawDescription: Python: Pass inequality as string in dict for evaluation


code:
template_globals = {}
render_partial = template.render(template_dir, globals=template_globals)
render = template.render(template_dir, globals=template_globals,
                         base='layout')
template_globals.update(render=render_partial)

rawDescription: Having multiple templates nested within each other using weby


code:
for h, v, conv in zip(headers, row, converters):
  column[h].append(conv(v))

rawDescription: How to import a csv file using python with headers intact, where first column is a non-numerical

description: Import a csv file using python with headers intact, where first column is a non-numerical


code:
# File b.py

from a import Klass

def somemethod(foo):
    pass

somemethod(Klass)

rawDescription: alias for python class in another module

description: Alias for python class in another module


code: variables == stuff

rawDescription: Looking for a special PEP for IF Python statement


code:
import re

function_name = re.compile(r'^(?:\w+ +)*(?:\w+::)*(\w+)', re.MULTILINE)
matches = function_name.findall(your_txt)

# -> ['function_name1', 'function_name2', 'function_name3', 'function_name4']

rawDescription: Python Regex - non-greedy match does not work


code:
my_dictionary = open(path_to_stored_dictionary, 'r').read()
my_dictionary = eval(my_dictionary)

rawDescription: Make dictionary from dictionary string

description: Make dictionary from dictionary string


code:
from Tkinter import *

root = Tk()
root.title("Test")

def _quit(event):
    root.destroy()

m = Menu(root)
root.config(menu=m)

fm = Menu(m, tearoff=0)
m.add_cascade(label="File", menu=fm)
fm.add_command(label="Quit", command=lambda: _quit(None), accelerator='Ctrl+Q')

root.bind('<Control-Q>', _quit)
root.bind('<Control-q>', _quit)

root.mainloop()

rawDescription: Tkinter bind problem

description: Tkinter bind problem


code: import copy

rawDescription: Numpy matrix doesn't update value

description: Numpy matrix doesn't update value


code:
def ELFHash(key):
    hash, x = 0, 0
    for i in range(len(key)):
        hash = (hash << 4) + ord(key[i])
        x = hash & 0xF0000000
        if x != 0:
            hash ^= (x >> 24)
            hash &= ~x
    hashstr = '%08X' % hash
    return "".join(reversed([hashstr[i:i+2] for i in range(0, len(hashstr), 2)]))

rawDescription: Convert Delphi BufferToHex function to Python


code: min(l, key=operator.attrgetter('foo'))

rawDescription: min/max based on property (not attribute) of class object in python

description: Min/max based on property (not attribute) of class object in python


code:
from PIL import Image
def is_jpg(filename):
    try:
        i=Image.open(filename)
        return i.format =='JPEG'
    except IOError:
        return False

rawDescription: Python: Check if uploaded file is jpg

description: Python: Check if uploaded file is jpg


rawDescription: Distinguishing large integers from near integers in python


code: make_upper("hello world")

rawDescription: Proper way of handling char * returning data in swig/python


code: result = [sum(b) for b in a]

rawDescription: python sum the values of lists of list

description: Python sum the values of lists of list


code:
df_win2 = df.groupby(level=0).apply(pd.rolling_mean, 2).groupby(level=0).shift()
df_win1 = df.groupby(level=0).apply(pd.rolling_mean, 1).groupby(level=0).shift()

rawDescription: Python - Pandas, Rolling Mean, and difficult Groupby common ID with a few select parameters


rawDescription: Regular expression find and replace multiple


rawDescription: Assigning multiple variable values to a single variable in Python


code:
namespace(cmd='open', filename='some.txt')
namespace(cmd='new', filename='another.txt')
namespace(cmd='edit', filename='some.txt')

rawDescription: Create parser with subcommands in argparse, customize positional argument(s)


rawDescription: Understanding a line of code

description: Understanding a line of code


code:
b = input("Enter: ")
b = int(b)
result = Dialog().show(b)
print("result:", result)

rawDescription: Trying to produce function for a custom number of tkinter Entry fields.


code:
data['Dave']
data['Bill']

rawDescription: python - access list element by key

description: Python - access list element by key


code:
class UserModelSerializer(serializers.ModelSerializer):

    class Meta:
         model = get_user_model()

class ChatsSerializer(serializers.ModelSerializer):
    # some code...

    sender = UserModelSerializer()
    recipient = UserModelSerializer()

    class Meta:
         fields = ('sender_name', 'id', 'sender', 'recipient','thread','subject','moderation_reason','body')

rawDescription: How to include in queryset details fields of a foreign key (django and rest_api)

description: Include in queryset details fields of a foreign key (django and rest_api)


code:
filter = ("/This/is/an/example", "/Another/example")
to_check = ["/This/is/an/example/of/what/I/mean", "/Another/example/this/is/", "/This/example", "/Another/freaking/example"]
[s for s in to_check if s.startswith(filter)]

rawDescription: Check if the beginning of a string matches something from a list of strings (python)


code:
Setup
df = pd.DataFrame(['StartGame', 'TutorialEnded',  'FBConnect',
  'StartGame', 'Sale', 'FBConnect', 'InviteSent',
  'StartGame', 'Finish_1', 'Sale', 'Bought',
  'Finish_22',  'FBConnect', 'Finish_2',
  'TutorialEnded', 'Finish_18'], columns=['Value'])
df.index.name = 'position'
df.reset_index(inplace=True)

rawDescription: Mapping/plotting distance of values in 1 dimensional array/ series


rawDescription: Dividing Python properties to categories


code:
import timeit
def timeit_auto(stmt="pass", setup="pass", repeat=3):
    """
    http://stackoverflow.com/q/19062202/190597 (endolith)
    Imitate default behavior when timeit is run as a script.

    Runs enough loops so that total execution time is greater than 0.2 sec,
    and then repeats that 3 times and keeps the lowest value.

    Returns the number of loops and the time for each loop in microseconds
    """
    t = timeit.Timer(stmt, setup)

    # determine number so that 0.2 <= total time < 2.0
    for i in range(1, 10):
        number = 10**i
        x = t.timeit(number) # seconds
        if x >= 0.2:
            break
    r = t.repeat(repeat, number)
    best = min(r)
    usec = best * 1e6 / number
    return number, usec

rawDescription: Use Python's `timeit` from a program but functioning the same way as the command line?


code: neighbors = [elem for nlist in neighbors for elem in nlist]

rawDescription: python find all neighbours of a given node in a list of lists

description: Python find all neighbours of a given node in a list of lists


code: [x * (2 - x % 2) for x in a_list]

rawDescription: Python list comprehension - simple

description: Python list comprehension - simple


code:
res = []
tmp = []

for i, line in enumerate(open('file.txt')):
    if i % 4 == 0:
        res.append(tmp)
        tmp = []
        continue
    tmp.append(line.strip())

print(res)

rawDescription: Python - Importing strings into a list, into another list :)


code:
import datetime
import functools
import resource
import sys

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        r0 = resource.getrusage(resource.RUSAGE_SELF)
        t0 = datetime.datetime.now()
        retval = func(*args, **kwargs)
        r = resource.getrusage(resource.RUSAGE_SELF)
        t = datetime.datetime.now()
        sys.stderr.write('{}: utime {} stime {} wall: {}\n'.format(
            func.__name__,
            datetime.timedelta(seconds=r.ru_utime-r0.ru_utime),
            datetime.timedelta(seconds=r.ru_stime-r0.ru_stime),
            t-t0))
        return retval
    return wrapper

@timed
def myfunc(i):
    for _ in range(100000000):
        pass
    return i*2

print(myfunc(2))

rawDescription: How to use the resource module to measure the running time of a function?

description: Use the resource module to measure the running time of a function


code: fcntl(5, F_SETFL, O_RDWR|O_NONBLOCK)

rawDescription: What could I grep for in strace output from a gevent app to test whether it's using blocking network IO?


code:
a = {1:[0, 1], 2:[21], 3:[]}
max_length = max(len(item) for item in a.values())
t = [[0] * (max_length - len(item)) + item for item in a.values()]

rawDescription: How to convert a python dictionary to an 2D array and pad wherever there is mismatch in length?

description: Convert a python dictionary to an 2D array and pad wherever there is mismatch in length


rawDescription: What is :: (double colon) in numpy like in myarray[0::3]?


code:
class QueryHandler(object):
    def __init__(self, u):
        self.ok = parse_qsl(urlparse(u).query, keep_blank_values=True)

    def newNetwork(self):
         queue = j.queue(self.hName)
         r = queue.add_subscribers(subscriber1a)

    def newChannel(self):
          queue = j.queue(self.cName)
          r = queue.add_subscribers(
              subscriberCreateChanTable,
              subscriberSortScenes,
              self.hname
              )
          rd = self.time

    def loginError(self):
        pass

    @property
    def time(self):
        return whatever_time_is_supposed_to_be

    @property
    def hName(self):
        return self.ok[11][1]

    @property
    def cName(self):
        return self.ok[12][1]

    @property
    def nName(self):
        return self.ok[10][1]

    @property
    def eventType(self):
        return self.ok[9][1]

    actions = {
        'newChannel': newChannel,
        'newNetwork': newNetwork,
        'loginError': loginError,
        }

    def dispatch(self):
        handler  = self.actions.get(self.eventType)
        handler(self)

rawDescription: passing multiple parameters to dispatcher

description: Passing multiple parameters to dispatcher


rawDescription: Python, Sort List

description: Python, Sort List


code: ','.join("%.6f" % f for f in C1pos)

rawDescription: How do I limit the number of digits in a list?

description: Limit the number of digits in a list


code:
for name in files:
    items.append(os.path.join(root, name))

rawDescription: List with all the files in directories &subdirectories with path (Python)


code:
first_word_is_first = [word_flip(l, flip=False) for l in g.readlines()]
first_word_is_second = [word_flip(l, flip=True) for l in g.readlines()]

rawDescription: Python "Map" with More Than One Parameter and iterating without "for"


rawDescription: Python string formatting - old `%` vs new `str.format`


code: dir("re") == dir("string")

rawDescription: Regarding dir()

description: Regarding dir()


code:
try:
    options, args = parser.parse_args()
except ConflictError as err:
    parser.error(err.message)

rawDescription: How do you handle options that can't be used together (using OptionParser)?

description: Handle options that can't be used together (using OptionParser)


rawDescription: Changing python indexes in a string

description: Changing python indexes in a string


code: [key for _, key in sorted((as_list(v), k) for k, v in times.items())]

rawDescription: How to sort a dictionary by a value passed through a function?

description: Sort a dictionary by a value passed through a function


code:
import os.path as path
path
from os import path
path

rawDescription: from ... import OR import ... as for modules

description: From ... import OR import ... as for modules


code:
for url in urls:
    onclick = lambda url=url[1]: urlOpen(url)
    labelurl = tk.Button(window, text=url[2], height = 2, command = onclick, width = 10)
    labelurl.grid(row = url[0] + 1, column = 1)

rawDescription: Python creating dynamic button

description: Python creating dynamic button


rawDescription: How to parse the header files of the pcap file?

description: Parse the header files of the pcap file


code:
def get_dicts(alist, key):
    return [dic for dic in alist if key in dic]

get_dicts(my_list, 'joe')

rawDescription: python list comprehension get dictionary by key

description: Python list comprehension get dictionary by key