code:
def newFunct(str, test):
    return (lambda x: str if eval(test, {"x": x}) else "")
is_even = newFunct("even", "x % 2 == 0")
is_even(4)
# "even"
is_even(10)
# "even"
is_even(13)
# ""

rawDescription: Add a variable test to a function

description: Add a variable test to a function


rawDescription: Is there an easy way to edit a json file with python


code:
class FlexItem(Item):
    def __setitem__(self, key, value):
        if key not in self.fields:
            self.fields[key] = Field()

        self._values[key] = value

rawDescription: Scraping data without having to explicitly define each field to be scraped


code: env.ZipBetter('foo.zip', 'foo/')

rawDescription: How to make SCons not include the base dir in zip files?

description: Make SCons not include the base dir in zip files


code:
class Collection():
    def __init__(self, db, collection_name):
        self.db = db
        self.collection_name = collection_name

    @property
    def client(self):
        if not hasattr(self.__class__, '_client'):
            self.__class__._client = MongoClient()

        return self.__class__._client

    @property
    def collection(self):
        if not hasattr(self, '_collection'):
            database = getattr(self.client, self.db)
            self._collection = getattr(database, self.collection_name)

        return self._collection

rawDescription: can I have a mongodb collection as a class attribute in python

description: Have a mongodb collection as a class attribute in python


code:
def parse_csv(filename, gr, ent, work):
  ...
  gr.append(123)
  work.append(row)
  ...

rawDescription: Python Access Variables Outside of Function


code: a = a.reshape((a.shape[0], -1, n))

rawDescription: Block mean of numpy 2D array

description: Block mean of numpy 2D array


code:
def get_shop_id(request):
    if "current_shop" in request.session:
        return request.session['current_shop']

    return 1 if request.user.is_superuser else 2

rawDescription: Django Global function and variable

description: Django Global function and variable


code:
from operator import itemgetter
sorted(A, key=itemgetter('name', 'age'))

rawDescription: Python: How to sort a list of dictionaries by several values?


code: [item for k in d for item in (k, d[k])]

rawDescription: How to convert a dictionary to a flat list?

description: Convert a dictionary to a flat list


rawDescription: Embedding public key as string in Paramiko Application


code: a = [hex(x) for x in xrange(0,pow(2, 16))]

rawDescription: Generate a list of hexadecimal numbers in python


code: xs = [LpVariable("x{}".format(i+1), cat="Binary") for i in range(len(objs))]

rawDescription: How do I generate PuLP variables and constrains without using exec?

description: Generate PuLP variables and constrains without using exec


code: L = L1

rawDescription: Filtering a list of strings in python

description: Filtering a list of strings in python


code: cmd = 'my_command' + ''.join(counters[:1])

rawDescription: Python: Combining string and lists

description: Python: Combining string and lists


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


rawDescription: Render equation to .png file using Python


code: exit

rawDescription: exit from ipython

description: Exit from ipython


rawDescription: Summing elements of string in Python

description: Summing elements of string in Python


code:
def save(self, commit=True):
    user = super(UserCreationForm, self).save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user

rawDescription: Extending UserCreationForm: password not saved


code:
DOG = Animal(4, ['Socks', 'Meat'])
CAT = Animal(4, ['Lasagna', 'Fish'])

rawDescription: Grouping constants in python

description: Grouping constants in python


code: global movies_list

rawDescription: Using name of strings in different functions


code:
def remap_port(port, port_data):
    result = {
        "state":  port_data["state"],
        "reason": port_data["reason"]
    }
    try:
        result["ssl_cert"] = port_data["script"]["ssl-cert"]
    except KeyError:
        pass
    return port, result

def remap_scanned_address(address, address_data):
    return {
        "address":  address,
        "hostname": address_data["hostname"],
        "ports":    dict(remap_port(port, port_data) for port,port_data in address_data["tcp"].items())
    }

def remap_scan_data(data_in):
    return [remap_scanned_address(address, address_data) for address, address_data in data_in["scan"].items()]

data_out = remap_scan_data(data_in)

rawDescription: Python - Iterating lists and dictionaries


code:
uid = re.compile(r"uid=(\d*)")
uids = []
for url in list_of_urls:
    match = uid.search(url)
    if match is not None:
         uids.append(match.group(1))

rawDescription: Python extract value beautifulsoup regex


code:
from operator import itemgetter

dates = map(itemgetter(1), E.itervalues())

rawDescription: Dictionary conversion to list in Python

description: Dictionary conversion to list in Python


code:
import re

with open('gutenberg.txt') as stream:
    oldtext = stream.read()

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

    print(newtext)

rawDescription: Most efficient way to delete needless newlines in Python


code:
from abc import xyz
from my_stuff import *

rawDescription: Globally loading classes or functions for any file in an application in Python


code:
# take the original value_counts, drop 'Random'
ts1 = df.category.value_counts()
rand_cnt = ts1.random
ts1.drop('Random', inplace=True)

# randomly choose from the other categories
ts2 = pd.Series(np.random.choice(ts1.index, rand_cnt)).value_counts()

# align the two series, and add them up
ts2 = ts2.reindex_like(ts1).fillna(0)
(ts1 + ts2).plot(kind='barh')

rawDescription: Distributing a pandas DataFrame feature at random


code:
indexes=['date','uid','artist','iid','tag']
data1 = pd.read_table(filename,header=None, nrows=1000000, names=('uid','iid','artist','tag','date'),index_col=indexes, parse_dates='date')
data['anno']=1
data2 = pd.read_table(filename,header=None, nrows=1000000, names=('uid','iid','artist','tag','date'), parse_dates='date')

rawDescription: Averaging over different levels in pandas


code:
import math
import pprint
def matrixH0(k):
    H0 = []
    for m in range(k):
        # create a new row
        row = []
        for n in range(k):
            if abs(m-n)==1:
                row.append(math.sqrt(n+m+1)/2.)
            else:
                row.append(0)
        H0.append(row)
    return H0
pprint.pprint(matrixH0(4))

rawDescription: Adding values to a matrix with a for loop in python


code:
block("foo bar 99 block baz")
block("sky line apartments block 2 chandra layout")

rawDescription: Conditioning on Regex

description: Conditioning on Regex


code:
import os
import subprocess
import sys

def untar(path, root):
    subprocess.call(['tar', '-C', root, '-xf', path])

def unzip(path, root):
    subprocess.call(['unzip', os.path.abspath(path)], cwd=root)

path = sys.argv[1]
dest = os.path.abspath(sys.argv[2])
if not os.path.exists(dest):
    os.makedirs(dest)
if path.endswith('.zip'):
    unzip(path, dest)
else:
    untar(path, dest)

rawDescription: Move required files where they need to go


rawDescription: Some Basic Python Questions

description: Some Basic Python Questions


code:
with sqlite3.connect("studentscores.db") as db:
            cursor=db.cursor()
            sql = "insert into tbl_Students (FirstName, Lastname) values (?,?)"
            cursor.execute(sql,(firstname,lastname))
            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:
def list_partylines(request):
    """
    List all `Partyline`s that we own.
    """
    partylines = Partylines.objects.for_user(request.user).sort_for_request(request)

rawDescription: Does Django Have a Way to Auto-Sort Model Fields?


code:
def all_subclasses(klass):
    for sub in klass.__subclasses__():
        yield sub
        yield from all_subclasses(sub)

list(all_subclasses(A))

rawDescription: Calling class method as part of initialization


code: 100 * np.round(newdf3.pivot_table(rows=['Quradate'], aggfunc=np.mean), 2)

rawDescription: Rounding entries in a Pandas DafaFrame

description: Rounding entries in a Pandas DafaFrame


code:
# change the figure size
fig2 = plt.figure(figsize = (5,5)) # create a 5 x 5 figure
ax3 = fig2.add_subplot(111)
ax3.imshow(im1, interpolation='none')
ax3.set_title('larger figure')

plt.show()

rawDescription: Change resolution of imshow in ipython

description: Change resolution of imshow in ipython


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


code:
dat2 = np.array([1, 2, 1, 2])
old_val = [1, 2]
new_val = [33, 66]
z=np.array((old_val,new_val)).T
for i,j in z:
   np.place(dat2,dat2==i,j)

dat2

rawDescription: Replace elements in numpy array using list of old and new values


code: np.savetxt('test.csv',data, fmt='%10s')

rawDescription: Numpy: use dtype from genfromtxt() when exporting with savetxt()


rawDescription: Python: Suppress exponential format (i.e. 9e-10) in float to string conversion?


code:
processed_set = set() #initialize set outside of loop
for filename in filenames: #loop over some collection of filenames
    if filename not in processed_set: #check for non-membership
        processed_set.add(filename) #add to set since filename wasn't in the set
        create_folder(filename) #repositioned based on implied semantics of the name
        createdata(filename)

rawDescription: Using set to avoid duplicate processing

description: Using set to avoid duplicate processing


code:
abcde

fghij

klmno

pqrst

uvwxy

z

rawDescription: Print 5 items in a row on separate lines for a list?


rawDescription: Django Group By relation's data

description: Django Group By relation's data


code:
def random_person(request):
    return HttpResponseRedirect(
        reverse('home.views.film_chart_view') + \
        "?q=" + get_person.short + \
        "&is_random=1"
    )

def film_chart_view(request):
    is_random = 'is_random 'in request.GET

rawDescription: Django optional view parameter with HttpResponseRedirect


code:
def users_with_at_least_n_friends(n=1):
    return active_users().filter(lambda u: count(u.friends) >= n)

def online_users():
    return User.select(lambda u: u.online)

def online_users_with_at_least_n_online_friends(n=1):
    return online_users().filter(lambda u: count(f for f in u.friends if f.online) >= n)

users = online_users_with_at_least_n_online_friends(n=10) \
            .order_by(User.name)[:10]

rawDescription: Writing select functions for customized Pony


rawDescription: How to renumber reverse-sorted list of integers?

description: Renumber reverse-sorted list of integers


code:
row['id']
row['movie']

rawDescription: Keep CSV commas inside fields with Python


code:
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
from nav_msgs.msg import Odometry
def callback(data):
    rospy.loginfo(rospy.get_caller_id()+"I heard %s",data)

def listener():
    rospy.init_node('listener', anonymous=True)
    rospy.Subscriber("odom", Odometry, callback)
    rospy.spin()

if __name__ == '__main__':
    listener()

rawDescription: How to get data in python from ROS in real-time?

description: Get data in python from ROS in real-time


code:
lst = [...]
sorted(lst, key=lambda x: x['name'])

rawDescription: Sort dictionary elements in list

description: Sort dictionary elements in list


code:
selection = [L for L in lists
             if x1 in L and x2 in L and L.index(x1) < L.index(x2)]

rawDescription: Fast way to find lists contains two particular items?


code:
from operator import attrgetter

map(attrgetter('a'), X)

rawDescription: Selecting all objects in the list of objects (in Python)


code:
def greet(sender):
    Window.alert("Hello, AJAX!")

rawDescription: Are there viable alternatives for Web 2.0 apps besides lots of Javascript?


code: dis.dis(lambda: i)

rawDescription: Python: lambda function behavior with and without keyword arguments?


code:
from itertools import izip_longest, islice, combinations

def sextuplets(seq, _fillvalue=object()):
    if len(seq) < 6:
        yield [tuple(seq)]
        return
    it = iter(seq)
    pairs = izip_longest(it, it, fillvalue=_fillvalue)
    sextuplets = (a + b + c for a, b, c in combinations(pairs, 3))
    for st in sextuplets:
        if st[-1] == _fillvalue:
            # replace fill value with valid item not in sextuplet
            # while maintaining original order
            for i, (x, y) in enumerate(zip(st, seq)):
                if x != y:
                    st = st[0:i] + (y,) + st[i:-1]
                    break
        yield st

rawDescription: All triplet combinations, 6 values at a time


code:
lst = ['a', 'ab', 'abc', 'bac']
res = [k for k in lst if 'ab' in k]
res

rawDescription: Filtering a list of strings based on contents


code:
for k,v in mydict.iteritems():
    print(k, v)

rawDescription: How to print dictionary keys and values in python

description: Print dictionary keys and values in python


rawDescription: Python: Arguments to sorting function

description: Python: Arguments to sorting function


code:
c0=sparse.coo_matrix((S,(i,j)))
c0.data

rawDescription: Python: Cumulative insertion of values in a sparse matrix (lil_matrix) due to repeated indices


code:
def dict_to_args(d, prefix=()):
    for k, v in d.iteritems():
        if isinstance(v, dict):
            for x in dict_to_args(v, prefix + (k,)):
                yield x
        else:
            yield ".".join(prefix + (k,)) + ":" + v

rawDescription: From a python dictionary to list of settings


code:
from bs4 import BeautifulSoup
import html

xml='<title>Photo of iceberg that is believed to have sunk Titanic sold at auction for £21,000 alongside &#039;world&#039;s most valuable biscuit&#039;</title>'
soup = BeautifulSoup(xml, 'lxml')
print(html.unescape(soup.get_text()))

rawDescription: Despite utf8 encoding some characters fail to be recognized


code:
from globalvarDB import goblinLv1, banditLv1, elementalLv1

Lv1MonsterList = [goblinlv1, banditLv1, elementalLv1]
trueMonster = random.choice(Lv1MonsterList)

rawDescription: Getting a list from a different module using a string?


code:
settings.overrides['FEED_FORMAT'] = 'json'
settings.overrides['FEED_URI'] = 'result.json'

rawDescription: scrapy from script output in json

description: Scrapy from script output in json


code:
for name in map(str.rstrip, sys.stdin):
    ...

rawDescription: Python iterate over stdin line by line using input()


code: add_letter_to_vowels("hello", "X")

rawDescription: insert letter before vowel in word

description: Insert letter before vowel in word


code:
with open('.htaccess') as fin, open('.htaccess-new', 'w') as fout:
    for line in fin:
        if line.strip() == '</IfModule>':
            fout.write('some stuff before the line\n')
        fout.write(line)

rawDescription: Python: How to add a line just before my matched pattern


code:
while lst:
  x = lst.pop()
  # do something with the element

rawDescription: What is the most pythonic way to pop a random element from a list?


code:
def concatenations(target_string, fragments, concat_path=()):
    if not target_string:
        yield concat_path
    else:
        for frag in fragments:
            if target_string.startswith(frag):
                new_target = target_string[len(frag):]
                new_path = concat_path + (frag,)
                for c in concatenations(new_target, fragments, new_path):
                    yield c

rawDescription: Recursion - how do you extract from specific traversals


rawDescription: Multidimensional List/Dict/whatever?

description: Multidimensional List/Dict/whatever


code:
out_points = points[mask]
out_colors = colors[mask]

rawDescription: Understanding the OpenCV Sample stereo_match.py code


code:
import os

psqldir = 'C:/Program Files/PostgreSQL/9.2/bin'
os.environ['PATH'] = '%s;%s' % (os.environ['PATH'], psqldir)
os.system('foo')

rawDescription: Setting path in Python

description: Setting path in Python


code: myset = {tuple(sorted(d.items())) for d in mylist}

rawDescription: How to form a set of dictionaries

description: Form a set of dictionaries


rawDescription: Opposite of melt in python pandas

description: Opposite of melt in python pandas


code:
from dateutil.rrule import *

def add_weekday_seconds(start, x):
    rr = rrule(SECONDLY, byweekday=(MO, TU, WE, TH, FR), dtstart=start, interval=x)
    return rr.after(start)

rawDescription: Add seconds to python datetime excluding weekends


code:
from pandas.io.data import DataReader
from datetime import datetime
df_1=DataReader("AAPL",  "yahoo", datetime(1970,1,1), datetime(2013,10,1))
df_1

rawDescription: How to get ALL historical data from Yahoo without specifying a start date in pandas?

description: Get ALL historical data from Yahoo without specifying a start date in pandas


code:
carIndex = next((index for index, name in enumerate(car.name for car in
cars if "VW" in car.name or "Poodle" in car.name)),-1)

rawDescription: Python: How to re-use list comprehensions after they are created in an expression


code:
def run_logistic(xn,r,iterates):
    iteration = 1
    while iteration <= iterates:
        xn1 = logistic_map(xn,r)
        iteration = iteration + 1
        xn = xn1
    return xn # Put return outside while-loop to get final value

rawDescription: While loop executes once during return, runs fine during print [python]


code:
result = [None]*len(positions)
for record in Record.objects.filter(id__in=ids):
    result[positions[record.id]] = record

rawDescription: Python how to sort list of objects based on their attribute according to another list


code:
from bisect import bisect_left
with open("test.txt") as f:
    keys = [0.1, 0.2]
    d = dict.fromkeys(keys, 0)
    for line in f:
        ind = bisect_left(keys, float(line))
        d[keys[ind]] += 1
print(d)
{0.1: 4, 0.2: 6}

rawDescription: to clustter the floating point data into suitable buckets in python

description: To clustter the floating point data into suitable buckets in python


code:
lines = []
for line in enumerate(open("solution.txt", "r")):
    lines.append(line)

rawDescription: How to read multiple specific lines from a txt file (python)

description: Read multiple specific lines from a txt file (python)


code: "Hello (John) this is (Phil)"

rawDescription: Going through very long strings, moving characters around


code:
function1(response, max_loc)
function2(response, max_loc)

rawDescription: cython function output slightly different from python function output

description: Cython function output slightly different from python function output


code:
import re

def parse_line(line):
    values = re.findall(r'\[[^\]]*\]|\S+', line)
    values = [v.strip("[]") for v in values]
    return values

rawDescription: Space delimited, except inside braces in a log file - Python


rawDescription: BeautifulSoup 4: Dealing with urls containing <br />


code:
rows
out

rawDescription: How to get rows from numpy 2d where column value is maximum from group by other column?

description: Get rows from numpy 2d where column value is maximum from group by other column


rawDescription: Longest prefix of array equal to a value


code:
duplicated = sc.broadcast(set(
    counts.filter(lambda x: x[1] > 1).keys().collect()
))

a.filter(lambda x: x[0] not in duplicated.value)

rawDescription: Spark RDD remove records with multiple keys


code: True or ('future' in string)   # bool('FUTURE') --> True

rawDescription: For loop python multiple checks

description: For loop python multiple checks


code:
class Collidable(object):
    def handle_collision(other, incident_vector):
        pass

    def __init__(self, shape, **kwargs):
        self.shape = shape
        super(Collidable, self).__init__(**kwargs)

class Movable(object):
    def update_position(self):
        self.velocity += self.acceleration
        self.position += self.velocity

    def __init__(self, velocity, acceleration, **kwargs):
        self.velocity, self.acceleration = velocity, acceleration
        super(Movable, self).__init__(**kwargs)

class Drawable(object):
    def draw(self):
        pass

    def __init__(self, image, **kwargs):
        self.image = image
        super(Drawable, self).__init__(**kwargs)

class Controllable(object):
    def key_down(self, key):
        pass

    def __init__(self, **kwargs):
        super(Controllable, self).__init__(**kwargs)

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


code:
try:
    import sqlite3  # included library
except ImportError:
    from pysqlite2 import dbapi2 as sqlite3  # use pysqlite2 instead

rawDescription: How to tell whether an update statement is successful in pysqlite 2.6.3

description: Tell whether an update statement is successful in pysqlite 2.6.3


code:
from itertools import izip_longest

seen = set()
with open('seen.txt', 'r') as seen_file:
    for lines in izip_longest(*[seen_file]*4):
        name = lines[1].strip()
        seen.add(name)

members = set()
with open('members.txt', 'r') as members_file:
    for lines in izip_longest(*[members_file]*4):
        name = lines[0].strip()
        members.add(name)

rawDescription: Finding out matches between two dictionaries in Python


code:
with codecs.open(r'test5.txt', 'w', 'utf-8') as outfile1:
    for row in reader:
        unicode_row = [x.decode('utf-8') for x in row]
        item = unicode_row[csv_col_index]
        outfile1.write(row[1] + "," + item + "," + multiple_replace(item) + "\n")

rawDescription: Writing python regex that recognizes all unicode letters


code:
a = []
length = 20
current = 0
maximum = 100
factor = 1.3
while current < maximum:
    new = min(maximum, current + length)
    a.append([current, new])
    current = new
    length = int(max(length / factor, 1))

rawDescription: Logarithmic list range construction

description: Logarithmic list range construction


code:
if self.children == []:
    self.children.append(node)
    return

rawDescription: How to add a grandchild to a python tree?

description: Add a grandchild to a python tree


rawDescription: gettext usage for 2 strings that are the same

description: Gettext usage for 2 strings that are the same


code:
from scipy.signal import butter, lfilter, freqz
b, a = butter(3, 0.2)
step_response = lfilter(b, a, np.ones(50))
plot(step_response)

rawDescription: Filter gain issue when using scipy.signal in Python


code: selectedFont = textBox.tag_cget("tagName", 'font')

rawDescription: How do I get tag info from text?

description: Get tag info from text


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: print(re.sub("Start.*$", '', v1, re.DOTALL).strip())

rawDescription: Python regex replace sentence with starting word


code:
import requests

url = 'http://localhost:8080/***/***/concerts/008'
files = {'file': open('/home/tester/Desktop/memo.txt','rb')}
data = {'name': 'memo.txt'}
params = {'access_token': 'YWMtraI2DF21EeWx_Rm4tdnmrwAAAVACjcyGG8TpdXJBXdjnRJ2SeqIAZI1T8Xk'}
r = requests.post(url, data=data, files=files, params=params)

rawDescription: unable to post file on usergrid using requests

description: Unable to post file on usergrid using requests


code:
from matplotlib.legend_handler import HandlerPatch
import matplotlib.patches as mpatches

def make_legend_arrow(legend, orig_handle,
                      xdescent, ydescent,
                      width, height, fontsize):
    p = mpatches.FancyArrow(0, 0.5*height, width, 0, length_includes_head=True, head_width=0.75*height )
    return p

f = plt.figure(figsize=(10,6))
arrow = plt.arrow(0,0, 0.5, 0.6, 'dummy', label='My label', )
plt.legend([arrow], ['My label'], handler_map={mpatches.FancyArrow : HandlerPatch(patch_func=make_legend_arrow),
                    })

rawDescription: Matplotlib legend for an arrow

description: Matplotlib legend for an arrow


code:
class point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return "point(%d, %d)" % (self.x, self.y)
x = point(3, 4)
x

rawDescription: Python object names and the interactive interpreter


code:
from scipy import stats

counts = df.category.value_counts()
dist = stats.rv_discrete(values=(counts.index, counts/counts.sum()))
fill_values = dist.rvs(size=df.shape[0] - df.category.count())
df.loc[df.category.isnull(), "category"] = fill_values

rawDescription: Fill multiple nulls for categorical data


code: subprocess.call('curl https://api.smartsheet.com/1.1/sheet/7846568935090052 -H "Authorization: Bearer 4ziycpnqjvto49oah6t6urd4un" -H "Accept: application/vnd.ms-excel" -o output.xls')

rawDescription: How can i execute this code in python?

description: Execute this code in python


code:
mydict = dict(zip(range(100), range(100)))
timeit.timeit('cPickle.dumps(mydict, 0)', 'from __main__ import cPickle, mydict')
timeit.timeit('cPickle.dumps(mydict, 1)', 'from __main__ import cPickle, mydict')
timeit.timeit('cPickle.dumps(mydict, 2)', 'from __main__ import cPickle, mydict')

rawDescription: Why does it take longer to dump and load with pickle.HIGHEST_PROTOCOL?


code:
class NQ:

    def __init__(self,n, callback): # added callback
        self.size = n
        self.columns = []
        self.places = 0
        self.backtracks = 0
        self.callback = callback # added callback

    def place(self, startRow=0):

        self.callback(self.columns) # added callback

        if len(self.columns) == self.size:

            return self.columns

        else:
            for row in range(startRow, self.size):
                if self.isSafe(len(self.columns), row) is True:
                    self.columns.append(row)
                    self.places += 1
                    return self.place()

            else:
                lastRow = self.columns.pop()
                self.backtracks += 1
                return self.place(startRow=lastRow + 1)

    def isSafe(self, col, row):
        for threatRow in self.columns:
            threatCol = self.columns.index(threatRow)
            if row == threatRow or col == self.columns.index(threatRow):
                return False
            elif threatRow + threatCol == row + col or threatRow - threatCol == row - col:
                return False
        return True

rawDescription: How to pass python list dynamically to another python file

description: Pass python list dynamically to another python file


code:
def rematcher(re_str, iterable):

    matcher= re.compile(re_str)
    in_match= 0
    for item in iterable:
        if matcher.match(item):
            if in_match == 0:
                yield item
            in_match+= 1
        else:
            if in_match > 1:
                yield "%s repeats %d more times\n" % (re_str, in_match-1)
            in_match= 0
            yield item
    if in_match > 1:
        yield "%s repeats %d more times\n" % (re_str, in_match-1)

import sys, re

for line in rematcher(".*Dog.*", sys.stdin):
    sys.stdout.write(line)

rawDescription: What is best way to remove duplicate lines matching regex from string using Python?


code:
from itertools import permutations

def permute_some(seq, indices_to_permute):
    for perm in permutations(indices_to_permute):
        newseq = seq[:]
        for i, p in zip(indices_to_permute, perm):
            newseq[i] = seq[p]
        yield newseq

rawDescription: Python - Narrowing down itertools permutations results with "if" statements. How to with repeated element?


code: self.Coffee = self.fontType.render('Some really long dialogue that might make me want this on two lines', 0, (0,0,0))

rawDescription: Pygame - Is There A Way To Get The String From fontType.render?


code: sample_html_string.replace('\n', '')

rawDescription: Replace paragraph mark in string

description: Replace paragraph mark in string


code:
styles = Widget.objects.all().values_list('style', flat=True).distinct()
for group in WidgetGroup.objects.prefetch_related('widget_set').all():
    for style in styles:
        group_style_widgets = group.widget_set.filter(style=style)
        # Do something with group_style_widgets

rawDescription: Django: Iterate over QuerySet by content of a field


code:
Client
2
Line1ofrecord1
Line2ofrecord1
Line3ofrecord1
Line4ofrecord1
Line1ofrecord2
Line2ofrecord2
Line3ofrecord2
Line4ofrecord2
End

rawDescription: string formatting issue within an iterative loop

description: String formatting issue within an iterative loop


code: Foo()

rawDescription: Can one modify the default repr behavior through a metaclass?


code:
class MyClass(object):
    def __init__(self, name):
        self.Name = name

rawDescription: (Usage of Class Variables) Pythonic - or nasty habit learnt from java?


code:
for k, v in l1:
    v[:] = sorted_triples(v)

rawDescription: Sorting list nested in tuples

description: Sorting list nested in tuples


code:
from werkzeug.wsgi import DispatcherMiddleware
from app1 import app as path_one
from app2 import app as path_two

application = DispatcherMiddleware(path_one, {
    '/path2': path_two
})

rawDescription: Flask + Gunicon + Nginx + Supervisor Non Default Port Numbers


code:
url = """http://phx01.companyA.com:8000/?query=kindle+fire&country_id=1&lang_id=1&linkin_id=8073631&sbh_id=120555,1&weight_group_id=80&request_id=p20.b6894b85df2f81d54003"""
params = urlparse.urlparse(url).query
params = urlparse.parse_qsl(params)
params
params = dict(params)
urllib.urlencode(params)
params['query'] = 'iphone'
urllib.urlencode(params)

rawDescription: URL call with string keyword substitution


code:
import numpy as np
# examples using a.item()
type(np.float32(0).item()) # <type 'float'>
type(np.float64(0).item()) # <type 'float'>
type(np.uint32(0).item())  # <type 'long'>
# examples using np.asscalar(a)
type(np.asscalar(np.int16(0)))   # <type 'int'>
type(np.asscalar(np.cfloat(0)))  # <type 'complex'>
type(np.asscalar(np.datetime64(0)))  # <type 'datetime.datetime'>
type(np.asscalar(np.timedelta64(0))) # <type 'datetime.timedelta'>
...

rawDescription: Converting numpy dtypes to native python types


rawDescription: Understanding a line of code

description: Understanding a line of code


code:
lists = [['hello'], ['world', 'foo', 'bar']]
combined = [item for sublist in lists for item in sublist]

rawDescription: Python list comprehension to join list of lists


code: dict(i.strip().split('\n') for i in text.split('\n\n') if len(i.strip().split('\n')) == 2)

rawDescription: Getting crawled information in dictionary format


code:
# foo.py
import logging
import bar

logger = logging.getLogger('foo')

def foo():
    logger.info('hello from foo')

if __name__ == '__main__':
    # Trivial logging setup.
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s %(name)-20s %(levelname)-8s %(message)s',
        datefmt='%m-%d %H:%M')
    for handler in logging.root.handlers:
        handler.addFilter(logging.Filter('foo'))

    foo()
    bar.bar()

rawDescription: What is a correct way to filter different loggers using python logging?


rawDescription: Preserve whitespaces when using split() and join() in python


code:
"{: <10}{}".format(*bob.split())
# output: 'Bob       1'

rawDescription: Replace integer with number of spaces

description: Replace integer with number of spaces


rawDescription: Constructing a 3D cube of points from a list


code: cursor = FollowDotCursor(ax, x, y)

rawDescription: Possible to make labels appear when hovering over a point in matplotlib in stem plot?


code: x[mask]=y

rawDescription: Replacing column values in an array using putmask and preserving order


code:
import timeit
import utils_timeit as UT

def foo():
    total = 0
    for i in range(10000):
        total += i**3
    return total

num, timing = UT.timeit_auto(setup='from __main__ import foo', stmt='foo()')
print(num, timing)

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


code:
from subprocess import Popen, PIPE

cat_proc = '/usr/bin/cat'

consumers = (Popen([cat_proc], stdin = PIPE, stdout = open('consumer1', 'w')),
             Popen([cat_proc], stdin = PIPE, stdout = open('consumer2', 'w')),
             Popen([cat_proc], stdin = PIPE, stdout = open('consumer3', 'w'))
)

with open('inputfile', 'r') as infile:
   for byte in infile:
       for consumer in consumers:
           consumer.stdin.write(byte)

rawDescription: Multiple processes reading from the same pipe asynchronously


code: pat = Literal('if') + nestedExpr("{", "}")

rawDescription: Using regular expressions to denote the opener of nestedExpr


code: re.findall('-[a-zA-Z]', 'ls -A -H -B -b .')

rawDescription: Regular Expressions: Print last in group


code:
class A(object):
    def some_method(self):
        pass
    some_other_method = some_method

rawDescription: Python class has method "set", how to reference builtin set type?


code:
def first_true2():
    di={}
    for i in range(len(a)):
        idx=np.argmax(a[i])
        if idx>0:
            di[i]=idx
        else:
            di[i]=None

    return di
    # same dict is returned...

rawDescription: Finding first non-zero value along axis of a sorted two dimensional numpy array


code:
import numpy as np
from numpy.polynomial import polynomial as poly
from scipy import interpolate as interp

import matplotlib.pyplot as plt

n = 20
x = np.linspace(0, 2*np.pi, n)
a = np.sin(x) + np.random.uniform(-.2, .2, n)

s = interp.UnivariateSpline(x, a)
p = poly.polyfit(x, a, 3)
p = poly.Polynomial(p)

plt.figure()
plt.plot(x, np.sin(x), '-', x, a, 'o', x, s(x), '--', x, p(x), '.-')

rawDescription: python cross section curve fitting

description: Python cross section curve fitting


code:
astro_date = json_str['daily']['data_date']
sunsign, created = Sign.objects.get_or_create(signtype=index+1, astro_date=astro_date,
                        defaults={
                                  'headline': json_str['daily']['headline'],
                                  'headcontent':json_str['daily']['content'],
                                  'rating':json_str['daily']['rating'],
                                  'love_rate':json_str['daily']['love'],
                        })

rawDescription: django - get_or_create() is not saving to sqlite db

description: Django - get_or_create() is not saving to sqlite db


code:
def merge_max_frequency(*iterables):
    return reduce(operator.or_, map(collections.Counter, iterables)).elements()

rawDescription: python - merge two lists but keep same number of occurrences

description: Python - merge two lists but keep same number of occurrences


code:
class HeaderViewFilter(QObject):
    # ...
    def eventFilter(self, object, event):
        if event.type() == QEvent.HoverEvent:
            pass # do something useful
            # you could emit a signal here if you wanted

self. filter = HeaderViewFilter()
horizontalHeader().installEventFilter(self.filter)

rawDescription: PyQt: How to catch mouse-over-event of QTableWidget-headers?


rawDescription: How to make a table from lists of data?

description: Make a table from lists of data


code: [i[i.rindex('r')+1:] for i in lst]

rawDescription: Pythonic way to select characters after specific character sequence in string


code:
[('verb', 'to read a book with the intent of learning'),
 ('verb', 'second definition of study'),

 ('noun', 'the object of ones study'),
 ('noun', 'second definition of study')]

rawDescription: how to make regex go line by line to match two strings at the same time?

description: Make regex go line by line to match two strings at the same time


code:
def count_different_values(k_v1s, k_v2s):
    """kv1s and kv2s should be dictionaries mapping keys to
    values.  count_different_values() returns the number of keys in
    k_v1s and k_v2s that don't have the same value"""
    ks = set(k_v1s.iterkeys()) | set(k_v2s.iterkeys())
    return sum(1 for k in ks if k_v1s.get(k) != k_v2s.get(k))

def sum_square_diffs(x0s, x1s):
    """x1s and x2s should be equal-lengthed sequences of numbers.
    sum_square_differences() returns the sum of the squared differences
    of x1s and x2s."""
    sum((pow(x1-x2,2) for x1,x2 in zip(x1s,x2s)))

def incr(x_c, x, inc=1):
    """increments the value associated with key x in dictionary x_c
    by inc, or sets it to inc if key x is not in dictionary x_c."""
    x_c[x] = x_c.get(x, 0) + inc

def count_items(xs, x_c=None):
    """returns a dictionary x_c whose keys are the items in xs, and
    whose values are the number of times each item occurs in xs."""
    if x_c == None:
        x_c = {}
    for x in xs:
        incr(x_c, x)
    return x_c

def second(xy):
    """returns the second element in a sequence"""
    return xy[1]

def most_frequent(xs):
    """returns the most frequent item in xs"""
    x_c = count_items(xs)
    return sorted(x_c.iteritems(), key=second, reverse=True)[0][0]

class kNN_classifier:
    """This is a k-nearest-neighbour classifer."""
    def __init__(self, train_data, k, distf):
        self.train_data = train_data
        self.k = min(k, len(train_data))
        self.distf = distf

    def classify(self, x):
        Ns = sorted(self.train_data,
                    key=lambda xy: self.distf(xy[0], x))
        return most_frequent((y for x,y in Ns[:self.k]))

    def batch_classify(self, xs):
        return [self.classify(x) for x in xs]

def train(train_data, k=1, distf=count_different_values):
    """Returns a kNN_classifer that contains the data, the number of
    nearest neighbours k and the distance function"""
    return kNN_classifier(train_data, k, distf)

rawDescription: Finding k-nearest neighbors for a given vector?


code:
urlpatterns = patterns('stock_app.views',
   url(r'^goc/(\w+)/(\d+)/$', 'goc'),
   url(r'^goc_range/(\w+)/(\d+)/(\d+)/$', 'goc_range'),
)

rawDescription: How to restrict one url to only one view in django urls

description: Restrict one url to only one view in django urls


code:
args = {}
args['command'] = 'command'
args['nonce'] = 10000
list(args)

rawDescription: Go and Python HMAC libraries give different results


code:
f = tables.open_file(filename, mode='a')
f.root.data.append(x)

rawDescription: save numpy array in append mode

description: Save numpy array in append mode


code:
from functools import wraps

def cut_data(func):
    @wraps(func)
    def wrapper(*args, **kw):
        month = request.args.get('month', None)
        if month is None:
            # redirect to same endpoint with new query parameter
            return redirect(request.endpoint, month='some month', **request.view_args)

        # cut data
        data = some_magic(csv_mod.data, month)
        # call actual view function
        return func(data=data, *args, **kw)

    return wrapper

rawDescription: handle events in flask before they propagate to more specific approutes

description: Handle events in flask before they propagate to more specific approutes


rawDescription: Timestamp url with function

description: Timestamp url with function


code: next_obj = objects.first()

rawDescription: How can i find next highest value in django query

description: Find next highest value in django query


rawDescription: Python3 how is mro defined in object?

description: Python3 how is mro defined in object


code:
NO_dict = {x[0]: x[1] for x in ISO3166_CountryCodes_NO}
EN_dict = {x[0]: x[1] for x in ISO3166_CountryCodes_EN}

rawDescription: Python: Compare lists and combine in common fields


rawDescription: How can I capture a value from a string and then remove it?

description: Capture a value from a string and then remove it


rawDescription: Convert a standard python key value dictionary list to pyspark data frame


code:
block_list.draw()
block_list.update()

rawDescription: How do you make an image move through the screen and then make it disappear in python?

description: Make an image move through the screen and then make it disappear in python


code:
proc = subprocess.Popen(['echo'] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = proc.communicate()
print(output)

rawDescription: Problems capturing Python subprocess output on Mac OS X


code: dict(zip("abc","cda"))

rawDescription: String translate using dict

description: String translate using dict


code:
def simplified(array, idxs):
    return array[idxs.T, np.arange(idxs.shape[0])]

rawDescription: Numpy advanced indexing using a 2D array of row indices without broadcasting the output


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

rawDescription: Nested List of Lists to Single List of tuples


code: #!/usr/bin/env python3

rawDescription: how to run scripts with multiple python versions installed?

description: Run scripts with multiple python versions installed


code:
input_list = [(1, 2), (1, 3), (1, 4), (2, 8), (2, 10)]
elimination_set = {(1, 2), (2, 8)}
result_list = [t for t in input_list if t not in elimination_set]

rawDescription: Simple way to delete nested (list of 2 elements) from a list?


code:
conn.authenticate(url, consumer, token)
header = 'To:testing.oauth.1@gmail.com\n' + 'From: testing.oauth.1@gmail.com\n' + 'Subject:testing \n'
msg = header + '\n this is test msg from me \n\n'
conn.sendmail('testing.oauth.1@gmail.com', 'testing.oauth.1@gmail.com', msg)

rawDescription: python & smtplib: Is sending mail via gmail using oauth2 possible?

description: Python & smtplib: Is sending mail via gmail using oauth2 possible


code: 事業

rawDescription: Python UTF-8 conversion

description: Python UTF-8 conversion


code:
exclusionlist=[...]
displaycolumns=[]
for col in tree["columns"]:
    if not "%s"%col in exclusionlist:
        displaycolumns.append(col)
tree["displaycolumns"]=displaycolumns

rawDescription: Hiding TreeView Columns In Tkinter

description: Hiding TreeView Columns In Tkinter


code: all(c[i, j] == a[i, j, b[i, j]] for i in range(10) for j in range(10))

rawDescription: Index numpy nd array along last dimension


rawDescription: Why is 2**100 so much faster than math.pow(2,100)?


code:
def getblocks(L):
    # The list of good blocks (as lists of lines.) You can also make this
    # a flat list if you prefer.
    data = []
    # The list of good lines encountered in the current block
    # (but the block may still become bad.)
    block = []
    # Whether the current block is bad.
    bad = 1
    for line in L:
        # Not in a 'good' block, and encountering the block separator.
        if bad and not line.rstrip():
            bad = 0
            block = []
            continue
        # In a 'good' block and encountering the block separator.
        if not bad and not line.rstrip():
            # Save 'good' data. Or, if you want a flat list of lines,
            # use 'extend' instead of 'append' (also below.)
            data.append(block)
            block = []
            continue
        if not bad and line.startswith('- '):
            # A good line in a 'good' (not 'bad' yet) block; save the line,
            # minus
            # '- ' prefix and trailing whitespace.
            block.append(line[2:].rstrip())
            continue
        else:
            # A 'bad' line, invalidating the current block.
            bad = 1
    # Don't forget to handle the last block, if it's good
    # (and if you want to handle the last block.)
    if not bad and block:
        data.append(block)
    return data

rawDescription: multi-line pattern matching in python

description: Multi-line pattern matching in python


rawDescription: Find a dictionary in a list of dictionaries


code:
import random
import math
import operator as op

def test():
    num1 = random.randint(1, 10)
    num2 = random.randint(1, num1)

    ops = {
        '+': op.add,
        '-': op.sub,
        '*': op.mul,
    }

    keys = list(ops.keys()) ##=> ['+', '*', '-']
    rand_key = random.choice(keys)  #e.g. '+'
    operation = ops[rand_key]  #e.g. op.add

    correct_result = operation(num1, num2)

    print ("What is {} {} {}?".format(num1, rand_key, num2))
    user_answer= int(input("Your answer: "))

    if user_answer != correct_result:
        print ("Incorrect. The right answer is {}".format(correct_result))
        return False
    else:
        print("Correct!")
        return True

username = input("What is your name? ")
print("Hi {}! Welcome to the Arithmetic quiz...".format(username))

correct_answers = 0
num_questions = 3

for i in range(num_questions):
    if test():
        correct_answers +=1

print("{}: You got {}/{} questions correct.".format(
    username,
    correct_answers,
    num_questions,
    #'question' if (correct_answers==1) else 'questions'
))

rawDescription: python: Primary school Arithmetic quiz- saving results to a .txt file

description: Python: Primary school Arithmetic quiz- saving results to a .txt file


code: itemIDs, itemNames = GetItems()

rawDescription: How to use a .NET method which modifies in place in Python?

description: Use a .NET method which modifies in place in Python


code:
import threading

class ArgLocker:
    def __init__(self):
        self.xs = dict() # maps x to (lock, count) pair
        self.lock = threading.Lock()

    def __call__(self, x):
        return AllMine(self.xs, self.lock, x)

class AllMine:
    def __init__(self, xs, lock, x):
        self.xs = xs
        self.lock = lock
        self.x = x

    def __enter__(self):
        x = self.x
        with self.lock:
            xlock = self.xs.get(x)
            if xlock is None:
                xlock = threading.Lock()
                xlock.acquire()
                count = 0
            else:
                xlock, count = xlock
            self.xs[x] = xlock, count + 1

        if count: # x was already known - wait for it
            xlock.acquire()
        assert xlock.locked

    def __exit__(self, *args):
        x = self.x
        with self.lock:
            xlock, count = self.xs[x]
            assert xlock.locked
            assert count > 0
            count -= 1
            if count:
                self.xs[x] = xlock, count
            else:
                del self.xs[x]
            xlock.release()

rawDescription: Garbage-collect a lock once no threads are asking for it


code:
def anagram(str1,str2):
    if sorted(str1) == sorted(str2):
        return True
    else:
        return False

rawDescription: Comparing a string with a list of strings to find anagrams in Python


code: [m(False) for m in lambdas]

rawDescription: Python closures, default argument isn't equal solution as using functools.partial?


code:
from sympy import symbols
from sympy import plot

t = symbols('t')
x = 0.05*t + 0.2/((t - 5)**2 + 2)

plot(x, (t, 0, 10), ylabel='Speed')

rawDescription: Python - Using Sympy Equations for Plotting


code:
valid_forms = filter(lambda fm: fm.is_valid(),
                     map(ArticleForm, some_list_of_dictionaries))

rawDescription: Django: validating forms declared on client side with angularjs


code:
id_order = { v: k for k, v in enumerate(user_ids) }
users = sorted(users, key=lambda u: id_order.get(u.id))

rawDescription: Sqlalchemy get results in the same order


rawDescription: efficient expanding linregress

description: Efficient expanding linregress


code:
from collections import Counter
l = [1, 1, 2, 2, 2, 2, 2, 3, 4, 10, 10, 10, 10, 10]
[(i, Counter(l)[i] / float(len(l)) * 100.0) for i in Counter(l)]

rawDescription: How do i find the percentage of the most common element in a list?

description: Find the percentage of the most common element in a list


code:
SuperMan = character();

SuperMan.name = "Super Man"
SuperMan.health = 250
SuperMan.morale = 25

rawDescription: Why can't I store a number in a list and use that number to lead to a "choice"?


code:
#!/usr/bin/python

import sys

if (sys.argv[0] == "./funA.py"):
    print("Calling A")
    # ...
    sys.exit(0)

if (sys.argv[0] == "./funB.py"):
    print("Calling B")
    # ...
    sys.exit(0)

print(sys.argv[0])

rawDescription: Creating Python Executables for *nix

description: Creating Python Executables for *nix


code: [[s for s in z.split("\\t")] for z in testInput.split('\\n') if z]

rawDescription: Python List Comprehension for a list with lists


rawDescription: check_call and command line arguments on Windows

description: Check_call and command line arguments on Windows


code: hp = list(filter(lambda x: x[0] > cutoff, depth_tuples))

rawDescription: Python 3.4 nested loop using lambda filter working weirdly


code:
result = db.collection.aggregate([
    { "$match": {
        "impressions.service": "furniture"
    }},
    { "$redact": {
       "$cond": {
           "if": {
               "$eq": [
                   { "$ifNull": [ "$service", "furniture" ] },
                   "furniture"
               ]
           },
           "then": "$$DESCEND",
           "else": "$$PRUNE"
       }
    }},
    { "$unwind": "$impressions" },
    { "$group": {
        "_id": "$impressions.id"
    }}
])

rawDescription: Conditions in Find, Mongo

description: Conditions in Find, Mongo


code:
def httpdate(dt):
    """Return a string representation of a date according to RFC 1123
    (HTTP/1.1).

    The supplied date must be in UTC.

    """
    weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
    month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
             "Oct", "Nov", "Dec"][dt.month - 1]
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
        dt.year, dt.hour, dt.minute, dt.second)

rawDescription: RFC 1123 Date Representation in Python?

description: RFC 1123 Date Representation in Python


code:
def set_fonts(axis):
    plt.setp(axis.title, **titleFont)
    plt.setp(axis.xaxis.label, **axesFont)
    plt.setp(axis.yaxis.label, **axesFont)
    return axis

rawDescription: Matplotlib: set label font without setting label


code:
df_loc.loc_x_bin = df_loc.loc_x_bin.astype('category')
df_loc.loc_y_bin = df_loc.loc_y_bin.astype('category')

rawDescription: Are values in one dataframe in bins of another dataframe?


rawDescription: Business days in Python

description: Business days in Python


code:
class ImageGallery(models.Model):
    ...
    count = models.PositiveIntegerField(default=0)

    def update_counter(self):
        self.count = self.count + 1

rawDescription: Django: DetailView, Where to update a counter?


rawDescription: Is there a way to write a Python script that creates and executes code?


code:
import requests
r = requests.get('https://tabs.ultimate-guitar.com/tabs/download?id=904610')
r.headers['Content-Disposition']
cgi.parse_header(r.headers['Content-Disposition'])[-1]['filename']

rawDescription: Downloading File in Python (With Requests?)


rawDescription: How to search & replace in Python?

description: Search & replace in Python


rawDescription: Code for determining number of 15 minute periods


code:
coords=np.ogrid[0:w,0:h]
idx=(coords[0]+coords[1])%2 == 1
print(idx)
print(idx.shape)
# [[False  True False  True]
#  [ True False  True False]
#  [False  True False  True]
#  [ True False  True False]
#  [False  True False  True]
#  [ True False  True False]]
# (6, 4)

rawDescription: getting pixels value in a checkerboard pattern in python

description: Getting pixels value in a checkerboard pattern in python


code:
def activity(t, tickets):
    tickets.sort(key=lambda x:x[0]) #sort by start time
    gamma = 0
    for point, duration in tickets:
        if point < t and t < point + duration:
              gamma += 1
        elif point > t:
              break ; #we can quit looking
    return gamma

rawDescription: Numpy : find number of active tickets at time t given a list of start and duration


code: i = np.random.choice(np.arange(m.shape[0]), N, replace=False)

rawDescription: How should I go about subsampling from a scipy.sparse.csr.csr_matrix and a list


code:
from itertools import chain, repeat
list(chain(repeat(0, 4), repeat(1, 4), repeat(2, 4)))

rawDescription: python - make a list with repetitive elements

description: Python - make a list with repetitive elements


code: output = sample.lstrip('[').rstrip(']').split(', ')

rawDescription: Python string to list conversion

description: Python string to list conversion


code:
from operator import itemgetter
map(itemgetter(2), alist)

rawDescription: Iterate over a list of list, not returning all item from sub-list


code:
def IsInRange(n, r=("8X5000", "8X5099")):
    (minr, maxr) = [[int(i) for i in l.split('X')] for l in r]
    p = len(r[0]) - r[0].find('X')

    nl = (n // 10**p, n % 10**(p-1))
    fInRange = all([minr[i] <= nl[i] <= maxr[i] for i in range(2)])
    return fInRange

rawDescription: How to check if a number is within a group of non-consecutive ranges?

description: Check if a number is within a group of non-consecutive ranges


code:
from functools import wraps

def make_monitored(func):
    class wrapper:
        def __init__(self, f):
            self.func = f
            self.counter = 0
        def __call__(self, *args, **kwargs):
            self.counter += 1
            return self.func(*args, **kwargs)
    return wraps(func)(wrapper(func))

rawDescription: Tracking number of function calls + closures (à la SICP) in Python


code:
import matplotlib.pyplot as plt
import matplotlib.dates as md
import numpy as np
import datetime as dt
import scipy.interpolate as interpolate

dates = [dt.date(year, 9, 1) for year in range(2003, 2009)]
t = map(md.date2num, dates)
jec = (100, 70, 125, 150, 300, 250)
plt.plot(dates, jec, 'k.', markersize = 20)
new_t = np.linspace(min(t), max(t), 80)
new_dates = map(md.num2date, new_t)
kinds = ('cubic', 'quadratic', 'slinear', 'nearest', 'linear', 'zero', 4, 5)
colors = plt.get_cmap('jet')(np.linspace(0, 1.0, len(kinds)))
for kind, color in zip(kinds, colors):
    new_jec = interpolate.interp1d(t, jec, kind=kind)(new_t)
    plt.plot(new_t, new_jec, '-', label=str(kind), color=color)
plt.legend(loc = 'best')
plt.show()

rawDescription: matplotlib large set of colors for plots

description: Matplotlib large set of colors for plots


code: data = ifile.readlines()[0].split()

rawDescription: Trouble sorting a list with python

description: Trouble sorting a list with python


code: mapping = dict(zip(lookup[:,0], range(len(lookup))))

rawDescription: Using Numpy arrays as lookup tables

description: Using Numpy arrays as lookup tables


code:
import re
inputtext = '09824747 18 n 02 archer 0 bowman 0 003 @ 09640897 n 0000'
re.findall(r'\b\d{3}\b', inputtext)
inputtext = 'exact: 444, short: 12, long: 1234, at the end of the line: 456'
re.findall(r'\b\d{3}\b', inputtext)

rawDescription: Searching for a 3 digit number in a text line in python


code: state = 1 if state == 4 else state + 1

rawDescription: Python one line if-else with different operators


code:
df['Period'] = df['Date'].map(lambda d: d.strftime('%Y-%m'))
df
grouped = df[['Period', 'PictureID']].groupby('Period')
grouped['PictureID'].value_counts().unstack(0).fillna(0)

rawDescription: Dataframe Wrangling with Dates and Periods in Pandas


code: ret = yield userMethods.get_all_users()

rawDescription: Get result from MotorEngine async query

description: Get result from MotorEngine async query


code: { k:v for k,v in my_dict.items() if k[0] == 'Peter' }

rawDescription: Extracting key/value pair from dictionary


code:
new_dict = {}
for road_id in road_dict:
    homes_on_road = [home for home in homes if home['road_id'] == road_id]
    ordered_homes = sorted(homes_on_road, key=lambda h: h['distance'])
    new_dict[road_id] = ordered_homes

pprint(new_dict)

rawDescription: Sorting and re-numbering values in Python dictionary


code:
import numbers
isinstance(1, numbers.Number)
isinstance(1.0, numbers.Number)
isinstance(1j, numbers.Number)

rawDescription: How to determine that a Python object is numeric?

description: Determine that a Python object is numeric


code:
# X is row-major
print(X.flags.c_contiguous)
# True

# Y is just a transposed view of X
Y = X.T

# the indices of the elements in Y are transposed, but their layout in memory
# is the same as in X, therefore Y is column-major rather than row-major
print(Y.flags.c_contiguous)
# False

rawDescription: Numpy: transpose result of advanced indexing


code:
def tosource(url):
    # example input
    # posts/2014/01/26/python-unittest-structure/index.html
    # posts/2014/01/26/ocaml-vs-java/index.html
    # posts/2014/01/25/why-ocaml-comparison-with-python/index.html

    if url.startswith("posts"):
        (posts, year, month, day, name) = url.split('/')[:-1]
        res = "%s/%s/%s-%s-%s-%s.md" % (year, month, year, month, day, name)
    else:
        res = "/" # implement later
    return res

rawDescription: With Pelican, how to set or access variables between Python code and themes?


code:
def f1(x):
    spl = x.rsplit(None, 1)[1].strip("Xx")
    if spl.isdigit():
        return "+" + spl + "00"
    return "+100"

def f2(x):
    spl = x.rsplit(None, 1)[1].strip("Xx")
    if spl.isdigit():
        return "-" + spl + "00"
    return "-100"

df = pd.DataFrame(["BULL APPLE X2", "BEAR APPLE X3", "BULL GOOG 2X", "BEAR GOOG 3X", "BULL TSLA", "BEAR TSLA","FOO BAR"],
              columns=["A"])

df["B"] = df["A"].map(lambda x: f1(x)
                  if "BULL" in x else f2(x) if "BEAR" in x else "+100")

print(df)

rawDescription: Pandas: Conditionally append substrings "y"+"z" to column B if column A contains "x"


code:
class Connector(Database):
    def __init__(self,type):
        #describe all types in this dict
        types = {"sqlite":"?",
                 "postgre":"%s"}

        #Database.__init__(self) as necessary
        self.sql_search = "SELECT ID FROM TAG WHERE DATA = %s" % types[type]

    def _get_tag(self, tagcipher):
        #replace the sql search string with the wildcard.
        self._cur.execute(self.sql_search, ([tagcipher]))
        rv = self._cur.fetchone()
        return rv

rawDescription: Design a connection to multiple databases in Python


code:
mapping = {}
for i, node in enumerate(nodes):
    mapping[node] = i

rawDescription: Heat Map Python

description: Heat Map Python


rawDescription: sum of squares in a list in one line?

description: Sum of squares in a list in one line


code:
d = {('class1','name1'):3,('class1','name2'):3,('class2','name1'):1,('class2','name2'):2}
dict1 = {k:v for k,v in d.items() if k[0] == "class1"}
dict2 = {k:v for k,v in d.items() if k[1] == "class2"}
difference = dict(Counter(dict1) - Counter(dict2))
difference

rawDescription: Python tuple key in dictionary not able to fetch


rawDescription: How to change the location of the pointer in python?

description: Change the location of the pointer in python


code:
import re

invalid_tail = re.compile(r'[^a-zA-Z0-9+/=\n\r].*$')

def remove_tail(base64_value):
    return invalid_tail.sub('', base64_value)

rawDescription: How to extract valid string from beginning to the first no base64 valid character?

description: Extract valid string from beginning to the first no base64 valid character


code:
def clicked(iv, ev):
    p = iv.get_path_at_pos(int(ev.x), int(ev.y))
    if not p is None:
        if iv.path_is_selected(p):
            iv.unselect_path(p)
        else:
            iv.select_path(p)
    return True # make the IconView ignore this click
iconview.connect('button-press-event', clicked)

rawDescription: Gtk IconView select multiple without Ctrl?


rawDescription: finding duplicates in a list of lists

description: Finding duplicates in a list of lists


code:
from requests.packages.urllib3.fields import RequestField
from requests.packages.urllib3.filepost import encode_multipart_formdata

fields = []
for name, (filename, contents, mimetype) in files.items():
    rf = RequestField(name=name, data=contents,
                      filename=filename)
    rf.make_multipart(content_disposition='attachment', content_type=mimetype)
    fields.append(rf)

post_body, content_type = encode_multipart_formdata(fields)
content_type = ''.join(('multipart/mixed',) + content_type.partition(';')[1:])

headers = {'Content-Type': content_type}
requests.post('http://example.com', data=post_body, headers=headers, params=params)

rawDescription: how to POST multipart list of JSON/xml files using python requests


code:
add(
    age, subtract(
        height, multiply(
            weight, divide(
                iq, 2
            )
        )
    )
)

rawDescription: Learn Python The Hard Way Exercise 21 Extra Credit


code:
# step-1: add some raw addresses
add_test_data(['Paris', 'somewhere in Nevada'])
print("-"*80)

# step-2: get those raw which do not have geo
add_geo_info()
print("-"*80)

# step-1: again with 1 new, 1 same
add_test_data(['Paris', 'somewhere in Chicago'])
print("-"*80)

# step-2: get those raw which do not have geo
add_geo_info()
print("-"*80)

# check: print all data for Paris geo:
gp = session.query(GeocodedAddress).filter(GeocodedAddress.full_address == 'Paris').one()
assert 2 == len(gp.raw_addresses)
print(gp.raw_addresses)

rawDescription: SQL alchemy - specifying relationships when foreign key may not exist


code:
query = "AAAAA-AAACAAA-AAAAAA"
ref = "AA-AATAAAAAAATAAAAAA"
fixed = ''.join(r if q == '-' else '' if r == '-' else q
    for q,r in zip(query, ref))

fixed

rawDescription: Repair one string relative to another in Python


code:
def get_exact_match(model_class, m2m_field, ids):
    query = model_class.objects.annotate(count=Count(m2m_field))\
                .filter(count=len(ids))
    for _id in ids:
        query = query.filter(**{m2m_field: _id})
    return query

matches = get_exact_match(MyModel, 'my_m2m_field', [1, 2, 3, 4])

# matches is still an unevaluated queryset, so you could run more filters
# without hitting the database.

rawDescription: How to do many-to-many Django query to find book with 2 given authors?

description: Do many-to-many Django query to find book with 2 given authors


code:
@app.route('/test/<command>')
@app.route('/test/<command>/<arg1>')
@app.route('/test/<command>/<arg1>/<arg2>')
def test(command=None, arg1=None, arg2=None):
    a = [arg1, arg2]
    # Remove any args that are None
    args = [arg for arg in a if arg is not None]
    if command == "say":
        return ' '.join(args)
    else:
        return "Unknown Command"

rawDescription: Flask route rule as function args

description: Flask route rule as function args


code:
import MySQLdb

def readinput():
  db = MySQLdb.connect("localhost","testuser","123","database" )
  cur = db.cursor()
  cur.execute("""SELECT * FROM users""")
  # use fetchall to get all the return results which is a list object
  return cur.fetchall()

rawDescription: Python MySQL: How to read from database in a module and compare it to input() in main program?


rawDescription: How to efficiently sum the upper left coner of a matrix using numpy?

description: Efficiently sum the upper left coner of a matrix using numpy


code: np.concatenate(A[:,np.newaxis,:] + B)

rawDescription: Adding up all pairs of columns of two matrices


code:
"[mM]y name [Ii][sS] (\w*)"

"[Ii]n repertory (\w*) I [wW][aA][nN][tT] file (\w*)"

"[Ii] [wW][aA][nN][tT] to ([ \w]*)"

rawDescription: How to save a regular expression user input value (Python)

description: Save a regular expression user input value (Python)


code:
#!/usr/bin/env python
import csv

inputFileName = 'test.txt'
outputFileName = 'finished.csv'

with open(outputFileName, 'w') as outfile:
    w = csv.writer(outfile)

    # write the file header
    fieldnames = ['local time', 'GMT time', 'date', 'product id', 'manuf id',
            'case', 'pallet', 'id', 'code', 'company id', 'location', 'secondary code']
    writer.writerow(fieldnames)

    # process each line
    with open(inputFileName, 'r') as inFile:
        for line in inFile:
            str_list = line.rstrip().split()
            new_list = [str_list[0],
                        str_list[1],
                        ' '.join([item.strip('[]') for item in str_list[2:5]]), # '[15', 'August', '2015]'
                        str_list[6].split(':')[1],
                        str_list[7].split(':')[1],
                        str_list[8].split(':')[1],
                        str_list[9].split(':')[1],
                        str_list[10].split(':')[1],
                        str_list[12],
                        str_list[13]]

            w.writerow(new_list) # write to the file

rawDescription: Python 3.5 csv parsing with special characters


code:
class Foo:
    def __init__(self):
        self.active = False

    def doThing(self):
        if not self.active: return
        return self.doPrint()

    def doPrint(self):
        print("Just a Foo here, boss")

class Bar(Foo):
    def __init__(self):
        super().__init__()

    def doPrint(self):
        print("I shouldn't be showing unless I'm active!")

rawDescription: Python class method merge

description: Python class method merge


code:
def my_method(line):
    return [line.lower()] if line.startswith("a") else []

rawDescription: How can I return an empty (null?) item back from a map method in PySpark?

description: Return an empty (null?) item back from a map method in PySpark


rawDescription: How to re-arrange the order of saved objects in Django database

description: Re-arrange the order of saved objects in Django database


code:
def makelist(filename, keys):
    with open('%s.txt' % filename) as f:
        return [dict(zip(keys, line.split('|'))) for line in f]

rawDescription: How to make a list of dictionaries for unknown number of keys in dictionary?

description: Make a list of dictionaries for unknown number of keys in dictionary


code:
import collections
score = collections.Counter()
score['A'] += 1
score['A'] += 1
score['B'] += 1
score

rawDescription: Table tennis simulator

description: Table tennis simulator


code:
import configparser
sample_config = """
[mysqld]
  user = mysql
  pid-file = /var/run/mysqld/mysqld.pid
  skip-external-locking
  old_passwords = 1
  skip-bdb
  # we don't need ACID today
  skip-innodb
"""
config = configparser.ConfigParser(allow_no_value=True)
config.read_string(sample_config)
# Settings with values are treated as before:
config["mysqld"]["user"]
# Settings without values provide None:
config["mysqld"]["skip-bdb"]
# Settings which aren't specified still raise an error:
config["mysqld"]["does-not-exist"]

rawDescription: configparser: parsing error with ommited values

description: Configparser: parsing error with ommited values


code:
import re, scrapy
from urllib import urlretrieve

class YuiimageSpider(scrapy.Spider):
    name = "yuiimage"
    allowed_domains = ["yahoo.com"]
    start_urls = [
        "https://uk.eurosport.yahoo.com/football/players/hugo-lloris/"
    ]

    def parse(self, response):
        imageSrcs = response.xpath("//div[contains(@class, 'player-image') and contains(@class, 'soccer-jersey')]/img[@style and contains(@style, 'yimg.com') and contains(@class, 'photo')]/@style").extract()
        for src in imageSrcs:
            imgUrl = re.search('http\:.*', re.search('[^(].*\(\'(.*)\'\);', src).group(1)).group(0)
            urlretrieve(imgUrl, imgUrl.split("/").pop())

rawDescription: Python Scrape Images From CSS Class

description: Python Scrape Images From CSS Class


code:
# this is a namespace package
try:
    import pkg_resources
    pkg_resources.declare_namespace(__name__)
except ImportError:
    import pkgutil
    __path__ = pkgutil.extend_path(__path__, __name__)

rawDescription: How does the hurry package import work?

description: How does the hurry package import work


code:
def mega_calculator(fn, repeat=1000):
    def helper(*args):
        total = 0
        for _ in range(repeat):
            total += fn(*args)
        return total / repeat
    return helper

rawDescription: how to access *args input from parent function?

description: Access *args input from parent function


code:
def decode_direct(codes):
    number_of_cols = max(ceil(math.log(v, 100)) for v in codes)
    return [[floor(code/(100**index)) % 100
             for index in range(number_of_cols-1, -1, -1)]
            for code in codes]

rawDescription: Converting an array to a float, how to reverse the process?


code:
def main(dataReadEvent):
    ...
    form = ExampleApp(dataReadEvent)

rawDescription: Have textbox update every 5 seconds PyQt


code:
class BaseClass(object):
    def __init__(self, classtype):
        self._type = classtype

def ClassFactory(name, argnames, BaseClass=BaseClass):
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            # here, the argnames variable is the one passed to the
            # ClassFactory call
            if key not in argnames:
                raise TypeError("Argument %s not valid for %s"
                    % (key, self.__class__.__name__))
            setattr(self, key, value)
        BaseClass.__init__(self, name[:-len("Class")])
    newclass = type(name, (BaseClass,),{"__init__": __init__})
    return newclass

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

description: Dynamically create derived classes from a base class


code:
self._font = pygame.font.Font(None, self._size)
self._a = 0
surface = self._create_surface()

rawDescription: Changing font in a livewires message

description: Changing font in a livewires message


code:
def multi(n):
    return (5 + multi(n-1)) if n>0 else 0;

rawDescription: How do I create a recursive python function for 5n?

description: Create a recursive python function for 5n


code:
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        return super(DecimalEncoder, self).default(o)

rawDescription: Passing data to Google Charts with Django


code: urls = {span.a["href"] for span in soup.findAll('span') if span.a}

rawDescription: Search html using BeautifulSoup in Python


code:
import random
import matplotlib.pyplot as plt

xbins=range(0,len(l))
plt.hist(df.B, bins=20, color='blue')
plt.show()

rawDescription: Conditional probability density estimation in python


rawDescription: How to clear/update a plot in a children widget from a parent frame in tkinter?

description: Clear/update a plot in a children widget from a parent frame in tkinter


rawDescription: Mask One 2D Numpy Array By Argmax Along Axis Of Another Array


rawDescription: Python SeleniumExtract href containing specific strings


code:
queryset = Model.objects.all()
list = [] #create list
for row in queryset: #populate list
    list.append({'title':row.title, 'body': row.body, 'name': row.user.username})
recipe_list_json = json.dumps(list) #dump list as JSON
return HttpResponse(recipe_list_json, 'application/javascript')

rawDescription: django serialize foreign key objects

description: Django serialize foreign key objects


rawDescription: mapping in SD in python

description: Mapping in SD in python


code:
from bs4 import BeautifulSoup
import requests

url = "http://agec.de/index.asp?a=1&lg=de&macnum=46965"

response = requests.get(url)
soup = BeautifulSoup(response.content)

soup.select('section#main_section aside#machine_detail form > table > tr')[1].get_text()

rawDescription: Get Text outside of tags as well

description: Get Text outside of tags as well


code:
import re
from bs4 import BeautifulSoup as Soup

html = '''

This is a paragraph

'''

rawDescription: Python BeautifulSoup - Add Tags around found keyword


code:
for i, line in enumerate(c):
    line = ownShuffle(line)

rawDescription: Subtlety accessing and modifying a multidimensionnal list


rawDescription: Python Help: Creating a dict of {str:list of str} from csv file


rawDescription: python removing unwanted characters after scanning mp3 meta-data

description: Python removing unwanted characters after scanning mp3 meta-data


code:
bins = np.arange(np.floor(nearest.min()),np.ceil(nearest.max()))
values, base = np.histogram(nearest, bins=bins, density=1)

rawDescription: numpy histogram cumulative density does not sum to 1

description: Numpy histogram cumulative density does not sum to 1


code:
A
numpy_there(A,15)

rawDescription: Is there a numpy.there?

description: Is there a numpy.there


code:
def handleCommand(self, command, prefix, params):
    """Determine the function to call for the given command and call
    it with the given arguments.
    """
    method = getattr(self, "irc_%s" % command, None)
    try:
        if method is not None:
            method(prefix, params)
        else:
            self.irc_unknown(prefix, command, params)
    except:
        log.deferr()

rawDescription: 'METHODNAME' as Client method versus irc_'METHODNAME' in twisted


code:
from django.utils.functional import wraps

def beta(view):
    @wraps(view)
    def inner(request, *args, **kwargs):
        if request.user.user_profile.beta:
            return view(request, *args, **kwargs)
        # Up to you how you return failure...
    return inner

rawDescription: How can I call a function and form a return object for use within my settings file?

description: Call a function and form a return object for use within my settings file


code:
with open("groupA.txt","a+") as f:
    sores = f.readlines()[-2:] # get last two previous lines
    with open("groupA.txt","w") as f:
        # write previous 2
        f.writelines(scores)
        # write latest
        f.write("\n{}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))

rawDescription: Python: Only saving three latest scores

description: Python: Only saving three latest scores


code:
for arg_tuple in itertools.product(*indexes):
    dosomething(*arg_tuple)

rawDescription: How to combine multiple for loops into a single generator python

description: Combine multiple for loops into a single generator python


code:
def pegs_picker(figure,pegs,event):
    # Check that the pointer is not on holes
    if figure.holes.contains(event)[0]:
        return False, dict()
    else:
        return True, dict()

rawDescription: Matplotlib pick event order for overlapping artists


code:
# i would use a shelf (a persistent, dictionary-like object,
# included with python).
import shelve

# hashmap of clean users indexed by timestamp)
# { timestamp1: {uid1: (lat11, long11), uid12: (lat12, long12), ...},
#   timestamp2: {uid1: (lat21, long21), uid2: (lat22, long22), ...},
#   ...
# }
#
clean_users = shelve.open("clean_users.dat")

# load data in clean_users from csv (shelve use same syntax than
# hashmap). You will interpolate data (only data at a given timestamp
# will be in memory at the same time). Note: the timestamp must be a string

# hashmap of infected users indexed by timestamp (same format than clean_users)
infected_users = shelve.open("infected_users.dat")

# for each iteration
for iteration in range(1, N):

    # compute current timestamp because we interpolate each user has a location
    current_timestamp = timestamp_from_iteration(iteration)

    # get clean users for this iteration (in memory)
    current_clean_users = clean_user[current_timestamp]

    # get infected users for this iteration (in memory)
    current_infected_users = infected_user[current_timestamp]

    # new infected user for this iteration
    new_infected_users = dict()

    # compute new infected_users for this iteration from current_clean_users and
    # current_infected_users then store the result in new_infected_users

    # remove user in new_infected_users from clean_users

    # add user in new_infected_users to infected_users

# close the shelves
infected_users.close()
clean_users.close()

rawDescription: Contact Tracing in Python - working with timeseries


code:
import gtk
import locale
locale.setlocale(locale.LC_ALL, 'sv_SE.utf8')
dialog = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT,
        gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO, "Hello world")
response = dialog.run()
dialog.destroy()

rawDescription: Change gtk.BUTTONS_YES_NO in different language


code: df.groupby(['i', 'j']).size()

rawDescription: New column showing number of occurrences of unique rows


code:
Provider1 = Provider1.reset_index(drop=True)
Provider2 = Provider2.reset_index(drop=True)

rawDescription: Pandas two rows have the same index, how to change them


code:
def listconf():
 #first I browes to the correct folder then
    contents = StringIO.StringIO()
    get("MyFile",contents)
    contents.seek(0)
    s=Server(contents)

rawDescription: Python fabric calling scrip "remote path"


code:
with open('input.txt','r') as inFile, open('output.txt','w') as outFile:
    for line in inFile:
        print(''.join([word for word in line.lower().translate(None, string.punctuation).split()
              if len(word) >=4 and word not in stopwords.words('english')]), file=outFile)

rawDescription: Removing Stop words from NLTK

description: Removing Stop words from NLTK


code:
g.sum()
g.transform(lambda x: x - x.mean())
g.agg({'prices': np.mean, 'duty': len})

rawDescription: Restricting function to unique dates - Multi-Index


code:
df
df['new'] = df[['Recipe@123', 'Recipe@234', 'Recipe@456']].apply(lambda x: x.any(), axis=1)
df

rawDescription: Pandas Calculate Logical OR based on several columns


code:
if option == 0:
    return [element for element in nList if abs(element) > 5]
elif option == 1:
    return [element for element in nList if element % 2]
else:
    raise ValueError("I don't know option {}".format(option))

rawDescription: Trying to return numbers in a list

description: Trying to return numbers in a list


code: reduce(lambda x, y: x + [x[-1] + y], num_words, [1])[1:]

rawDescription: Do math of list - python

description: Do math of list - python


code:
uCheck = input('Unit? ')

if uCheck == 'nm':
    Wave = Wave
elif uCheck == 'cm':
    ...

rawDescription: My unit checking variable isn't reading the input properly, when I put cm in as input the program sends the boolean to the else


code:
import requests
url = 'http://bbs.duchang8.com/forum-29-1.html'
r = requests.get(url)
r
r.history
r.history[0].headers

rawDescription: Exceeded 30 redirects after add `host` to headers[python requests]


rawDescription: python: iterate using a class method

description: Python: iterate using a class method


code:
import timeit

setup = """
import re
patterns = [".*abc", "123.*", "ab.*", "foo.*bar", "11010.*", "1[^o]*"]*10
strings = ["asdabc", "123awd2", "abasdae23", "fooasdabar", "111", "11010100101", "xxxx", "eeeeee", "dddddddddddddd", "ffffff"]*10
compiled_patterns = list(map(re.compile, patterns))

def matches_pattern(str, patterns):
    for pattern in patterns:
        if pattern.match(str):
            return True
    return False

def test0():
    for s in strings:
        matches_pattern(s, compiled_patterns)

def test1():
    for s in strings:
        any(p.match(s) for p in compiled_patterns)

def test2():
    for s in strings:
        re.match('|'.join('(?:%s)' % p for p in patterns), s)

def test3():
    r = re.compile('|'.join('(?:%s)' % p for p in patterns))
    for s in strings:
        r.match(s)
"""

import sys
print(timeit.timeit("test0()", setup=setup, number=1000))
print(timeit.timeit("test1()", setup=setup, number=1000))
print(timeit.timeit("test2()", setup=setup, number=1000))
print(timeit.timeit("test3()", setup=setup, number=1000))

rawDescription: Python, fastest way to iterate over regular expressions but stop on first match


code:
from lxml import etree

data = [['SEC.12.0', '\\\\DATA\\LOC', '\\\\ftp\\location'], ['SEC.13.0', '\\\\DATA\\LOC2', '\\\\ftp\\location2']]

xml_string = '<combo>'
for line in data:
    xml_string += "<pro>{0}</pro>\n<dataloc>{1}</dataloc>\n<ftploc>{2}</ftploc>\n".format(*line)
xml_string += '</combo>'

parser = etree.XMLParser(remove_blank_text=True)
root = etree.fromstring(xml_string, parser)
with open('data.xml', 'w') as f:
    f.write(etree.tostring(root, pretty_print=True))

rawDescription: Creating xml file using ElementTree or lxml


code:
try:
    step = (i for i, attr in enumerate(_STEP_NAMES) if getattr(self, attr) is None).next()
except StopIteration:
    return "Done!"
return str(step) + ": " + self.STEPS[step].replace('<user_created>', user)

rawDescription: Redundant code in Django models.py. How do I improve it?


code: re.findall(r'"\w+=.*?"', vars)

rawDescription: Regex search doesn't find elements with content


code:
from django import template
register = template.Library()

@register.filter
def getitem(mylist, index):
    return mylist[index]

rawDescription: Python-Django: ifchanged template tag

description: Python-Django: ifchanged template tag


rawDescription: backward slash followed by a number in python strings

description: Backward slash followed by a number in python strings


code: total_count = tidysd.groupby(['index'])['Station'].nunique(); total_count

rawDescription: Pandas Create Columns From Rows in Other Data Frame with Criteria


code:
from prettytable import PrettyTable
x = PrettyTable(dat.dtype.names)
for row in dat:
    x.add_row(row)
# Change some column alignments; default was 'c'
x.align['column_one'] = 'r'
x.align['col_two'] = 'r'
x.align['column_3'] = 'l'

rawDescription: NumPy: Pretty print tabular data

description: NumPy: Pretty print tabular data


code:
ExcessList = ["{0} [{1}]".format(name, index) for index, name in enumerate(Excess,1)]
Name = raw_input("Please choose which number you wish to use: {} \n".format(', '.join(ExcessList)))

rawDescription: Can I give the user an option to chose an element from the list based on its position in the list using python?

description: Give the user an option to chose an element from the list based on its position in the list using python


code:
from collections import defaultdict

size_counts = defaultdict(int)
for size, cnt in zip(shoesizes, quantities):
    size_counts[size] += cnt

orderedsizes, totalquant = map(list, zip(*sorted(size_counts.items())))

rawDescription: sorting integers in lists into bins

description: Sorting integers in lists into bins


code:
class Article(models.Model):
    title = models.CharField(max_length=150, verbose_name=_("title"))
    # ... more
    pub_date = models.DateTimeField(verbose_name=_('publishing date'))
    pub_year = models.IntegerField()
    pub_month = models.IntegerField()

rawDescription: How to do this GROUP BY query in Django's ORM with annotate and aggregate

description: Do this GROUP BY query in Django's ORM with annotate and aggregate


rawDescription: Is there a way to NOT an arbitrary M x N matrix using numpy broadcasting?


code:
# It is possible to construct a key for an entity that does not yet exist.
keyname_a = 'abc'
keyname_b = 'def'
key_a = ndb.Key(A, keyname_a)
key_b = ndb.Key(A, keyname_a, B, keyname_b)

a = A(id=keyname_a)
a.key_of_b = key_b
b = B(id=keyname_b, parent=key_a)

a.put()
b.put()

rawDescription: referencing an entity by its key before it gets saved to the ndb

description: Referencing an entity by its key before it gets saved to the ndb


code:
with open('data.p', 'rb') as data:
    users = pickle.load(data)

rawDescription: Python extend matrix

description: Python extend matrix


code: match = [regex.match(str) for regex in episodeRegExes if regex.match(str)]

rawDescription: My first Python program! Anyone care to review it an help me improve?


rawDescription: Split a string on every third space

description: Split a string on every third space


code:
def row(seq):
    allsums = []
    total = 0
    for u in seq:
        total += u
        allsums.append(total)

    i = min((abs(2*u - total), i) for i, u in enumerate(allsums[:-1], 1))[1]
    return seq[:i], seq[i:]

rawDescription: How can i make a general coding from my function?

description: Make a general coding from my function


code:
Bundle('common/inheritance.js', 'portal/js/common.js',
   'portal/js/plot.js', 'portal/js/ticker.js',
   filters='jsmin',
   output='gen/packed.js')

rawDescription: Webassets - exclude file in bundle

description: Webassets - exclude file in bundle


code:
from random import randint

def corridorOptions():
    if not hasattr(corridorOptions, 'code'):
        corridorOptions.code = randint(30, 60)
    print("There is a number etched. It reads '{0:02d}'".format(corridorOptions.code))

corridorOptions()
corridorOptions()
corridorOptions()
corridorOptions()
corridorOptions()

rawDescription: How do I store a random integer in a local variable in Python?

description: Store a random integer in a local variable in Python


rawDescription: Conjoin function made in functional style


code: projects = Project.objects.prefetch_related('employee_set', 'task_set').all()

rawDescription: Selecting all columns from related model with django queryset


code:
# without CSV
with open('master.txt') as f_in, open('fin_index.csv', 'w') as f_out:
    for line in f_in:
        if '10-Q' in line or '10-K' in line:
            f_out.write(line)

# with CSV for both
with open('master.txt') as f_in, open('fin_index.csv', 'w') as f_out:
    reader = csv.reader(f_in, delimiter='|')
    writer = csv.writer(f_out, delimiter='|')
    for line in reader:
        if line[2] in ('10-Q', '10-K'): # assuming the number is in column 2
            writer.writerow(line)

rawDescription: Python 3.4 : create updated new file from existing file


code:
class SensorSerializer(serializers.HyperlinkedModelSerializer):
    location_obj = SensorLocationSerializer(source='location',read_only=True,required=False)
    class Meta:
        model = Sensor
        fields = ('url', 'id', 'name', 'serial_number', 'location',
            'location_obj', 'active')

rawDescription: DRF expose model field in two separate read-write fields on the REST API


code:
first_set = set(first_tuple_list)
secnd_set = set(secnd_tuple_list)

rawDescription: How to compare a list of lists/sets in python?

description: Compare a list of lists/sets in python


code:
import re

def clean(s):

   # Remove invalid characters
   s = re.sub('[^0-9a-zA-Z_]', '', s)

   # Remove leading characters until we find a letter or underscore
   s = re.sub('^[^a-zA-Z_]+', '', s)

   return s

rawDescription: how do I convert a string to a valid variable name in python?

description: Convert a string to a valid variable name in python


code:
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    weekOne = models.ForeignKey(WeekOne)

    def check_updates(self):
        check = WeekOne.object.get(id=self.weekOne)

        if check.skipStairs and \
           check.squats == 1000 and \
           check.lunges == 250 and \
           check.stairDaysCount == 3:

           check.weekOneComplete = True
           check.save()

rawDescription: Properly Defining Relationships in Django DB


code:
claw = ['Fizzbuzz' if x % 15 == 0 else 'Fizz' if x % 3 == 0 else 'Buzz' if x % 5 == 0 else x for x in alist]
claw

rawDescription: Nested if-else lambdas in python returning function object rather than value (passing variable through?)


rawDescription: Printing row and columns in reverse

description: Printing row and columns in reverse


code: import Test2

rawDescription: python: imported module is in a different context

description: Python: imported module is in a different context


code:
import xmltodict
data = xmltodict.parse(xmldata)

rawDescription: parsing XML in Python

description: Parsing XML in Python


code:
for row in ArrayMulti:
    for index in range(len(row)):
        row[index] = "a"

rawDescription: How to replace values in multidimensional array?

description: Replace values in multidimensional array


code: dates

rawDescription: Python pandas.read_csv split column into multiple new columns using comma to separate


code:
# get your log instance
my_log_instance = ToListLogger()
# populate its records list
# ...
# then serialize it
serialized = LogEncoder().encode(my_log_instance)

rawDescription: Serialize LogRecords in Python

description: Serialize LogRecords in Python


code:
# -*- coding: utf-8 -*-

import sys
import re

text = """
saú$_ß$¤×÷asd县阴őasdCharacters: \"县阴 asdsadsasd县阴
"""
text = unicode(text, "utf-8")
print("\nMethod 1\n")
reg = "Characters: \"[\xe4\xb8\x80-\xe9\xbf\xbf]+.*?"
reg = unicode(reg, "utf-8")
pattern = re.compile(reg, re.UNICODE | re.MULTILINE)
for m in re.findall(pattern, text):  # Number of occurrences in the 'k' line.
    print("Results: %s" % m.encode(sys.stdout.encoding, errors='replace'))

print("\nMethod 2\n")
reg = u"Characters: \"[\u4e00-\u9fff]+.*?"
pattern = re.compile(reg, re.UNICODE | re.MULTILINE)
for m in re.findall(pattern, text):  # Number of occurrences in the 'k' line.
    print("Results: %s" % m.encode(sys.stdout.encoding, errors='replace'))

rawDescription: Python regular expression with unicode

description: Python regular expression with unicode


code:
a, b, c, d, e = range(5)
arg_dict = lambda l: dict((k, globals()[k]) for k in l.split(', '))

rawDescription: Passing keyword arguments to a function when local variable names are same as function parameter names


rawDescription: Python Directory Display in Finder, Explorer, Dolphin, etc... (Cross-Platform)


code:
from collections import defaultdict
testDictionary = defaultdict(list)
testDictionary["192.168.0.1"] = ["10.10.10.1", 22, 8080, 0]
if testDictionary[sourceIP]:
    testDictionary[sourceIP][-1] += 1

rawDescription: Store and lookup IP Packet header fields in Python


code: groupings('ABCDE', 2)

rawDescription: How to get all combinations of list groupings of at least a certain size?

description: Get all combinations of list groupings of at least a certain size


code: tmp = (x == big_foobar for x in foobars)

rawDescription: python using any() and all() to check if a list contains one set of values or another

description: Python using any() and all() to check if a list contains one set of values or another


code:
class x(float):
    def __str__(self):
        return "{:e}".format(self)

print (float(101))  # 101.0
print (x(101))      # 1.010000e+02

rawDescription: in Python 3, how to create a number-like object?

description: In Python 3, how to create a number-like object


code:
class Device(models.Model):
    """A sensor"""
    name = models.CharField(max_length=20)
    ...

class DataPoint(models.Model):
    value = models.DecimalField(decimal_places=2, max_digits=10) # whatever is appropriate
    timestamp = models.DateTimeField()
    device = models.ForiegnKey(Device)

rawDescription: Django data logging front end - phidgets


code:
import os
os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=gpu,floatX=float32"

rawDescription: Theano config directly in script

description: Theano config directly in script


code:
class MyResource(ModelResource):
     class Meta:
         excludes = (field1, field2)

rawDescription: exclude some fields in tastypie post data

description: Exclude some fields in tastypie post data


rawDescription: Python cgi and stdin

description: Python cgi and stdin


code: import networkx

rawDescription: My A Star implementation won't return the list of steps to get to a destination


code: sum(int(tuple_list[i][0]) for i in range(3,5))

rawDescription: How do I sum the first value in a set of lists within a tuple?

description: Sum the first value in a set of lists within a tuple


rawDescription: Splitting a url into a list in python

description: Splitting a url into a list in python


code:
import example
s1 = example.Spam('abc')
type(s1)
example.fun(s1)
type(s1) # s1's type has not changed.
s2 = 'def'
type(s2)
example.fun(s2)
type(s2) # s2's type has changed.
example.fun('ghi')

rawDescription: Boost.python automatically convert parameter


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

data = np.random.random((5, 5))

fig, ax = plt.subplots()
cnt = ax.contour(data)
ax.clabel(cnt)
ax.axis('off')

fig.savefig('test.png', bbox_inches='tight', transparent=True)

rawDescription: Completely removing axes from contour plot


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

data = np.random.random_integers(-1, 1, (10, 10))
masked_data = np.ma.masked_where(data == 0, data)

plt.imshow(data, interpolation="nearest")
plt.show()

rawDescription: Spectrogram - Whitening out specific areas


rawDescription: How to cut a substring from a formated string in python?

description: Cut a substring from a formated string in python


code: fmt.count('%') - fmt.count('%%') * 2

rawDescription: count number of formats in a python string

description: Count number of formats in a python string


code:
pkt = Ether()/IP()/TCP()
ip = pkt.getlayer(IP)
ip
ip.remove_payload()
ip

rawDescription: How to read whole ip layer and tcp layer from a packet when using scapy?

description: Read whole ip layer and tcp layer from a packet when using scapy


code:
List1 = ["apple","peach","grapes","berries"]
List2 = [98,7,47,33]
zipped = sorted(zip(List2, List1)) + [(200,)]
FinalDict = dict((x[1], [x[0], y[0]]) for x, y in zip(zipped, zipped[1:]))

rawDescription: Python - Dictionary with Lists and tuples


code:
length = 500
df = pd.DataFrame({'id':np.arange(length), 'coordinates':tuple(zip(np.random.uniform(-90, 90, length), np.random.uniform(-180, 180, length)))})

rawDescription: Vectorizing Haversine distance calculation in Python


code:
num = 5270
pairs = [chr(num/100),chr(num%100)]
pairs

rawDescription: Best way to Convert pairs of base 10 integers to ascii characters in python


rawDescription: trouble appending lists to another list

description: Trouble appending lists to another list


code:
# if your data isn't too large
new_data = [lemmas.get(word, word) for word in data]

# if it's so large you don't want to make another copy,
# you can do it in-place
for idx, word in data:
    data[idx] = lemmas.get(word, word)

rawDescription: How to use lemas list on python

description: Use lemas list on python


code:
from jinja2.environment import Template as JinjaTemplate
from jinja2.runtime import Context as JinjaContext

class CustomContextWrapper(JinjaContext):

    def __init__(self, *args, **kwargs):
        super(CustomContextWrapper, self).__init__(*args, **kwargs)
        self.__custom_context = None

    def set_custom_context(self, custom_context):
        if not hasattr(custom_context, '__getitem__'):
            raise TypeError('custom context object must implement __getitem__()')
        self.__custom_context = custom_context

    # JinjaContext overrides

    def resolve(self, key):
        if self.__custom_context:
            try:
                return self.__custom_context[key]
            except KeyError:
                pass
        return super(CustomContextWrapper, self).resolve(key)

class CustomTemplate(JinjaTemplate):

    def set_custom_context(self, custom_context):
        self.__custom_context = custom_context

    # From jinja2.environment (2.7), modified
    def new_context(self, vars=None, shared=False, locals=None,
                    context_class=CustomContextWrapper):
        context = new_context(self.environment, self.name, self.blocks,
                              vars, shared, self.globals, locals,
                              context_class=context_class)
        context.set_custom_context(self.__custom_context)
        return context

# From jinja2.runtime (2.7), modified
def new_context(environment, template_name, blocks, vars=None,
                shared=None, globals=None, locals=None,
                context_class=CustomContextWrapper):
    """Internal helper to for context creation."""
    if vars is None:
        vars = {}
    if shared:
        parent = vars
    else:
        parent = dict(globals or (), **vars)
    if locals:
        # if the parent is shared a copy should be created because
        # we don't want to modify the dict passed
        if shared:
            parent = dict(parent)
        for key, value in iteritems(locals):
            if key[:2] == 'l_' and value is not missing:
                parent[key[2:]] = value
    return context_class(environment, parent, template_name, blocks)

rawDescription: Lazy variable lookup in Jinja templates

description: Lazy variable lookup in Jinja templates


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--print', dest='print_', action='store_true', help="print stuff")
args = parser.parse_args(['--print'])
args.print_

rawDescription: argparse argument named "print"

description: Argparse argument named "print"


code:
@staticmethod
def parse_results(response):
    item = response.meta['item']
    item['matches'] = []
    table = response.xpath('(//table[@class="standard_tabelle"])[1]')
    for sel in table.xpath("./tr[position() > 3]"):
        title = sel.xpath("./td/a/@title").extract_first()
        if title and "premier" not in title.lower():
            return
        matchDict = dict(zip((
            'round',
            'date',
            'place',
            'opponent',
            'results'),
            filter(None, map(unicode.strip, (sel.xpath("./td[normalize-space(.)]//text()").extract())))))
        item['matches'].append(matchDict)
    yield item

rawDescription: My scraper yields too many items instead of merging them all into only a small bunch


code:
class ProfileFormView(UpdateView):
    template_name = 'dashboard/account.html'
    form_class = ProfileForm
    success_url = '#'

    def get_object(self, queryset=None):
        return Profile.objects.get(self.kwargs['id'])

url(r'^update_profile/(?P<id>\d+)/$', ProfileFormView.as_view(), name="update_profile"),

rawDescription: How to properly create ModelForm in django?

description: Properly create ModelForm in django


rawDescription: convert elements of an array from scientific notation to decimal notation in python

description: Convert elements of an array from scientific notation to decimal notation in python


code:
def classify(self, featureset):
    return self.prob_classify(featureset).max()

rawDescription: python nltk naive bayes probabilities

description: Python nltk naive bayes probabilities


code:
def inv_sort(listIn):

    #somewhere in your code recursive call
    recursive_result, recursive_invcount = inv_sort(argument)

    # this_call_invcount includes recursive_invcount
    return this_call_result, this_call_invcount

rawDescription: Python - using a shared variable in a recursive function


code:
import re
[m.start() for m in re.finditer(target_string, full_string)]

rawDescription: find not just the first index of a substring in a string - python 2.7

description: Find not just the first index of a substring in a string - python 2.7


rawDescription: How can I get a steamid 64 from a steamID in python

description: Get a steamid 64 from a steamID in python


code:
def my_kernel(x,y):
    d = np.zeros((x.shape[0], y.shape[0]))
    for i, row_x in enumerate(x):
        for j, row_y in enumerate(y):
            d[i, j] = np.exp(-gamma * np.linalg.norm(row_x - row_y))

    return d

rawDescription: User defined SVM kernel with scikit-learn