code: set(['catamaran', 'boat', 'man'])

rawDescription: How to obtain a list of strings such that it represents all the strings in a given list?

description: Obtain a list of strings such that it represents all the strings in a given list


code:
long_string = 'this is a really long string I want '\
              'to wrap over multiple lines'

rawDescription: Python - Long string on multiple line

description: Python - Long string on multiple line


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

mytarfile.add(..., exclude=lambda x: x in EXCLUDE_FILES)

rawDescription: Python tarfile and excludes

description: Python tarfile and excludes


code:
mydict = {}
for line in myfile:
   items = line.split()          # split line on whitespace
   mydict[items[0]] = items[1:]  # first item: key, rest: values

rawDescription: from elements in a line to key and values

description: From elements in a line to key and values


code:
mins = DF.groupby('pid').timestamp.min()
maxs = DF.groupby('pid').timestamp.max()
ranges = maxs - mins

shortest_range = ranges.min()
longest_range = ranges.max()
average_range = ranges.mean()

print(shortest_range, longest_range, average_range)

# (90, 180, 135.0)

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


rawDescription: Python: apply slice values within a callable function


code:
import MyLib.Module

MyLib.Module._a()
MyLib.Module._b()

rawDescription: Import symbols starting with underscore

description: Import symbols starting with underscore


code:
for family,data in d.iteritems():
   print('{}'.format(family))
   for meal, total in data.iteritems():
       print('{} {}'.format(total, meal))

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


code:
import matplotlib.dates as mdates
xfmt = mdates.DateFormatter('%Y-%m-%d')
axes.xaxis.set_major_formatter(xfmt)

rawDescription: How to set the xticklabels for date in matplotlib

description: Set the xticklabels for date in matplotlib


code:
def get_directory_handle(path):
    rqIndexLck.acquire()
    ret = FakeHandleFactory.next()
    handle2file[ret] = path
    rqIndexLck.release()
    return ret

rawDescription: Watchdog compatibility: A workaround for "CancelIoEx"


code:
coo
values
unq_coo
average_values

rawDescription: Numpy: Average of values corresponding to unique coordinate positions


code:
s = db.session

user = User(username='Alex')
post = Post(title='First try', body='This is my first try!')
comment = Comment(body='This is a useful post!')

user.posts.append(post)
user.comments.append(comment)
post.comments.append(comment)

s.add(user)
s.add(post)
s.add(comment)

s.commit()
s.close()

rawDescription: How to specify more than 1 backref

description: Specify more than 1 backref


code:
a = set('abcde')
b = set('ace')
c = set('acx')

rawDescription: Check if none of the multiple chars appears in string A?


code: e = Employee(name="abc", age=32)

rawDescription: Set attributes from dictionary in python


code: monster = monster(100)

rawDescription: random.randint function isnt working the way i would like it to

description: Random.randint function isnt working the way i would like it to


code:
message = 'foo bar baz'
message.find('bar')
dokokotoba = 'bar'
message.find(dokokotoba)
message.find('dokokotoba')

rawDescription: python 2.7 string_name.find() function always returning -1 when using variable

description: Python 2.7 string_name.find() function always returning -1 when using variable


code:
items = data[0].xpath('n:Item', namespaces={'n': ns})
items

rawDescription: Can't access child elements in XML

description: Can't access child elements in XML


code:
for row in enumerate(cursor):
    exec("DB{0} = row[1][u'name']".format(row[0] + 1))

rawDescription: Assign variables to dictionary items with same key


code:
#!/usr/bin/python2
# encoding: utf-8
from __future__ import print_function
import urllib2
import gzip
import zlib
import StringIO

req = urllib2.Request('http://www.google.com')
req.add_header('Accept-Encoding', 'gzip, deflate')
response = urllib2.urlopen(req)

the_page = response.read()
print("Length before decompression:" + str(len(the_page)))
if response.info().get('Content-Encoding') == 'gzip':
    the_page = gzip.GzipFile(fileobj=StringIO.StringIO(the_page)).read()
elif response.info().get('Content-Encoding') == 'deflate':
    the_page = zlib.decompress(the_page)

print("Length after decompression:" + str(len(the_page)))

rawDescription: how can I get the total bytes sent and received using python 2.7?

description: Get the total bytes sent and received using python 2.7


code: weight = sum(weights[word] for word in sentence.split())

rawDescription: Optimizing the search of a string in a phrases. Don't know which Python structures I need to use


code: mydictvar['general']['UserKey']

rawDescription: Python 2.7.8: Printing a sub-dictionary value?


code:
from pprint import pprint
output = [{'in_reply_to_status_id_str': None, 'in_reply_to_screen_name': None, 'retweeted':     False, 'in_reply_to_status_id': None, 'contributors': None, 'favorite_count': 0, 'in_reply_to_user_id': None, 'coordinates': None, 'source': 'Twitter Web Client', 'geo': None, 'retweet_count': 0, 'text': 'Tweeting a url \nhttp://t.co/QDVYv6bV90', 'created_at': 'Mon Sep 01 19:36:25 +0000 2014', 'entities': {'symbols': [], 'user_mentions': [], 'urls': [{'expanded_url': 'http://www.isthereanappthat.com', 'display_url': 'isthereanappthat.com', 'url': 'http://t.co/QDVYv6bV90', 'indices': [16, 38]}], 'hashtags': []}, 'id_str': '506526005943865344', 'in_reply_to_user_id_str': None, 'truncated': False, 'favorited': False, 'lang': 'en', 'possibly_sensitive': False, 'id': 506526005943865344, 'user': {'profile_text_color': '333333', 'time_zone': None, 'entities': {'description': {'urls': []}}, 'url': None, 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'protected': False, 'default_profile_image': True, 'utc_offset': None, 'default_profile': True, 'screen_name': 'KickzWatch', 'follow_request_sent': False, 'following': False, 'profile_background_color': 'C0DEED', 'notifications': False, 'description': '', 'profile_sidebar_border_color': 'C0DEED', 'geo_enabled': False, 'verified': False, 'friends_count': 40, 'created_at': 'Mon Sep 01 16:29:18 +0000 2014', 'is_translator': False, 'profile_sidebar_fill_color': 'DDEEF6', 'statuses_count': 4, 'location': '', 'id_str': '2784389341', 'followers_count': 4, 'favourites_count': 0, 'contributors_enabled': False, 'is_translation_enabled': False, 'lang': 'en', 'profile_image_url': 'http://abs.twimg.com/sticky/default_profile_images/default_profile_6_normal.png', 'profile_image_url_https': 'https://abs.twimg.com/sticky/default_profile_images/default_profile_6_normal.png', 'id': 2784389341, 'profile_use_background_image': True, 'listed_count': 0, 'profile_background_tile': False, 'name': 'Maktub Destiny', 'profile_link_color': '0084B4'}, 'place': None}]
pprint(output)

rawDescription: Python Json loads() returning string instead of dictionary?


code: a.writerows([val] for val in allsnps)

rawDescription: csv writer is adding delimiters in each words..

description: Csv writer is adding delimiters in each words..


code:
fd = open(filename,'rU')
chars = []
for line in fd:
   for c in line:
       chars.append(c)

rawDescription: Break string into list of characters in Python


rawDescription: Acquiring the Minimum array out of Multiple Arrays by order in Python


code: remove = str.replace("\\", " ")

rawDescription: remove this unidentified character "\" from string python

description: Remove this unidentified character "\" from string python


code:
CELERY_ANNOTATIONS = {
     '*': {
         'loglevel': logging.DEBUG,
         'logger': logging.getLogger('foo'),
     },
}

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

description: Get all tasks and periodic tasks in Celery


code:
@api.model
def get_age_comp(self):
    to_add = {}
    # getting all male older than 19 years from fci.student
    for student in self.search([('gender','=','m'), ('birth_date', '<=', date.today() - relativedelta(years=20))]):
        to_add[student.name] = student.birth_date
    # ignoring the students already in stat
    for stat in self.env['stat'].search([('name', 'in', to_add.keys())]):
        del to_add[stat.name]
    # adding the new ones
    for name, birth_date in to_add.iteritems():
        stat_model.create({'name': name, 'birth_date': birth_date})

rawDescription: Automated Action Birthday =19

description: Automated Action Birthday =19


code:
df.pivot(index='time', columns='name', values='value').reset_index()
# name        time  A   B
# 0     01/01/1970  1   5
# 1     02/01/1970  2   3
# 2     03/01/1970  1 NaN

rawDescription: pandas - with restructuring data in data frame

description: Pandas - with restructuring data in data frame


code: return redirect(category)

rawDescription: Preferred arguments for redirect function


code:
words = text.split()
totalwords = len(words)

rawDescription: Python word length function example needed


code:
import json
data = '1   234  0.2\n1   235  0.1'
parsed = parse(data)
parsed
json.dumps(parsed)

rawDescription: Formatting a string in required format in Python


code:
tokens = ["Let", "'s", "check", "this", "out", "."]
def postproc(toks):
    toks_out = []
    while len(toks) > 1:
            bigram = toks[:2]
            if bigram[1][0] == "'":
                    toks_out.append("".join(bigram))
                    toks = toks[2:]
            else:
                    toks_out.append(bigram[0])
                    toks = toks[1:]
    toks_out.extend(toks)
    return toks_out

postproc(tokens)

rawDescription: Preserving contractions with textblob ngrams


code:
import requests

url = 'baseuri:port/resource'
username = 'user'
password = 'pswd'

response = requests.get(url, auth=(username, password))

rawDescription: REST GET request on Python sending named argument


code:
import xml.etree.ElementTree as ET
#- Parser content by fromstring method of ElementTree
root = ET.fromstring(data)
#- Get all targeted dict tags from the content plist->dict->dict
target_dicts = root.findall("./dict/dict")
#- Variable whoch store taget information.
resut_info = []
# Iterate target dict tag.
for i in target_dicts:
    #- Find dict tag from the dict tag.
    target_dict = i.find("dict")
    #- Get children of target dict tag.
    dict_children = target_dict.getchildren()
    #- Tmp variable which save all details.
    dict_details = {}
    #- Iterate over children.
    for j in dict_children:
        #- As structure well define so we can use following logic to get key and value.
        if j.tag=="key":
            tag_key = j.text
        else:
            dict_details[tag_key] = j.text

    resut_info.append({"Name":dict_details.get("Name", ""),\
                       "Artist":dict_details.get("Artist", ""),\
                       "Album":dict_details.get("Album", "")})

import pprint
pprint.pprint(resut_info)

rawDescription: Parsing song names and the like from a XML file in Python


code:
myList = ['', 'foo', '', 'bar', '', '', 'fizz', '', 'buzz', '',""]
myList[:] = chain.from_iterable(consec(myList))
myList
myList = ['', 'foo', '', 'bar', '', '', 'fizz', '', 'buzz', '']
myList[:] = chain.from_iterable(consec(myList))
myList
myList = ['', 'foo', '', 'bar', '', '', 'fizz', '', 'buzz']
myList[:] = chain.from_iterable(consec(myList))
myList
myList = ['', 'foo', '', 'bar', '', '', 'fizz', '', 'buzz', "",'foo',""]
myList[:] = chain.from_iterable(consec(myList))
myList

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

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


rawDescription: Python recursively printing a tree from a list structure


code:
names = ('Elizabeth', 'Peter, Angela, Thomas')
[y for x in names for y in x.split(', ')]

rawDescription: Tuple unpacking

description: Tuple unpacking


code:
class Klass(object):

    @staticmethod  # use as decorator
    def stat_func():
        return 42

    _ANS = stat_func.__func__()  # call the staticmethod

    def method(self):
        ret = Klass.stat_func()
        return ret

rawDescription: Calling class staticmethod within the class body?


code:
f.function
f.function('.')

rawDescription: Multiple dot syntax in python and matplotlib


code: map(list, product([0, 1], repeat=dimension))

rawDescription: For-loop to fill in node positions in an array for a cube


code:
class Data(LogFile):
    def __init__(self,log_file):
        super(Data, self).__init__(log_file)
        self._data = ''

class DataNET(Data):
    def __init__(self, logfile):
        super(DataNET, self).__init__(logfile)
        self._data = {}

rawDescription: Inheritance in Python, init method overrriding


code:
# If we receive a CONNECT request
if headers["Method"] == "CONNECT":
    # Connect to port 443
    try:
        # If successful, send 200 code response
        client.connect(( headers["Host"], headers["Port"] ))
        reply = "HTTP/1.0 200 Connection established\r\n"
        reply += "Proxy-agent: Pyx\r\n"
        reply += "\r\n"
        browser.sendall( reply.encode() )
    except socket.error as err:
        # If the connection could not be established, exit
        # Should properly handle the exit with http error code here
        print(err)
        break

    # Indiscriminately forward bytes
    browser.setblocking(0)
    client.setblocking(0)
    while True:
        try:
            request = browser.recv(1024)
            client.sendall( request )
        except socket.error as err:
            pass
        try:
            reply = client.recv(1024)
            browser.sendall( reply )
        except socket.error as err:
            pass

rawDescription: Python HTTPS Proxy Tunnelling

description: Python HTTPS Proxy Tunnelling


code:
import decorator
import sys

def wrapper_string(pre_decor):
    argspec = decorator.getfullargspec(pre_decor)
    if len(argspec.args) == 0:
        raise TypeError("Couldn't find a first argument to decorate away.")
    allargs = list(argspec.args[1:])
    allshortargs = list(argspec.args[1:])

    if argspec.varargs:
        allargs.append('*' + argspec.varargs)
        allshortargs.append('*' + argspec.varargs)
    elif argspec.kwonlyargs:
        allargs.append('*')  # single star syntax
    for a in argspec.kwonlyargs:
        allargs.append('%s=None' % a)
        allshortargs.append('%s=%s' % (a, a))
    if argspec.varkw:
        allargs.append('**' + argspec.varkw)
        allshortargs.append('**' + argspec.varkw)

    head = "def " + pre_decor.__name__ + "(" + ', '.join(allargs) + "):"
    body = "    return _decorator_(_func_)("+ ', '.join(allshortargs) +")"
    return head + "\n" + body

def update_signature(pre_decor, post_decor, **kw):
    "Update the signature of post_decor with the data in pre_decor"
    post_decor.__name__ = pre_decor.__name__
    post_decor.__doc__ = getattr(pre_decor, '__doc__', None)
    post_decor.__dict__ = getattr(pre_decor, '__dict__', {})
    argspec = decorator.getfullargspec(pre_decor)
    if len(argspec.args) == len(argspec.defaults):
        pos = 1
    else:
        pos = 0
    post_decor.__defaults__ = getattr(pre_decor, '__defaults__', ())[pos:]
    post_decor.__kwdefaults__ = getattr(pre_decor, '__kwdefaults__', None)
    #post_decor.__annotations__ = getattr(pre_decor, '__annotations__', None)
    try:
        frame = sys._getframe(3)
    except AttributeError:  # for IronPython and similar implementations
        callermodule = '?'
    else:
        callermodule = frame.f_globals.get('__name__', '?')
    post_decor.__module__ = getattr(pre_decor, '__module__', callermodule)
    post_decor.__dict__.update(kw)

@decorator.decorator
def decorate_first_arg(dec, pre_decor):
    evaldict = pre_decor.__globals__.copy()
    evaldict['_decorator_'] = dec
    evaldict['_func_'] = pre_decor
    wrapper = compile(wrapper_string(pre_decor), "<string>", "single")
    exec(wrapper, evaldict)
    post_decor = evaldict[pre_decor.__name__]
    update(pre_decor, post_decor)
    return post_decor

rawDescription: How to write a decorator to set the first argument?

description: Write a decorator to set the first argument


code:
from sympy import pretty_print as pp, latex
from sympy.abc import a, b, n

expr = (a*b)**n
pp(expr) # default
pp(expr, use_unicode=True)
print(latex(expr))
print(expr.evalf(subs=dict(a=2,b=4,n=5)))

rawDescription: How do you print superscript in Python?

description: Print superscript in Python


code:
class Subclass:
    ...

class ExtendsSubclass(Subclass):
    ...

rawDescription: Include / extend modules in python

description: Include / extend modules in python


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

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


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

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


rawDescription: Adding (inserting) array to dict

description: Adding (inserting) array to dict


code: d = defaultdict(lambda: myobj(param1))

rawDescription: Passing a parameter to objects created by defaultdict


code:
# remember that for n bins there are n+1 bin edges
x_edges = np.linspace(0, 100, 101)
y_edges = np.linspace(0, 75, 76)

wcounts = np.histogram2d(x, y, weights=w, bins=(x_edges, y_edges))[0]

rawDescription: Generate Weight Map in Color with MatPlotLib?


code:
import csv
from itertools import izip
a = izip(*csv.reader(open("input.csv", "rb")))
csv.writer(open("output.csv", "wb")).writerows(a)

rawDescription: How to pivot data in a csv file?

description: Pivot data in a csv file


rawDescription: Python - get variables from file using regular expressions


code:
def _main(fd):
    with os.fdopen(fd, 'rb', closefd=True) as from_parent:
        process.current_process()._inheriting = True
        try:
            preparation_data = pickle.load(from_parent)
            prepare(preparation_data)
            self = pickle.load(from_parent)
        finally:
            del process.current_process()._inheriting
    return self._bootstrap()

rawDescription: What does the term bootstrap refer to in Python Multiprocessing.Process Module?


code:
def __call__ (self, parser, namespace, values, option_string=None):
    with values as f:
        contents = f.read()

    data = parser.parse_args(contents.split())
    for k, v in vars(data).items():
        if v and k != option_string.lstrip('-'):
            setattr(namespace, k, v)

rawDescription: how to get argparse to read arguments from a file with an option rather than prefix

description: Get argparse to read arguments from a file with an option rather than prefix


code: parser.add_argument('--version', action='version', version='%(prog)s 2.0')

rawDescription: Python's argparse to show program's version with prog and version string formatting


code: bool(number % 2)

rawDescription: Boolean evaluation in a lambda

description: Boolean evaluation in a lambda


code:
def remaining(self):
  return self.quantity - self.buyers.all().count()

rawDescription: Django: How do I count the number of objects related to another in the database?


code:
import sys
import unittest

def func():
    sys.exit()

class MyTest(unittest.TestCase):

    def test_func(self):
        self.assertRaises(SystemExit, func)

if __name__ == "__main__":
    unittest.main()

rawDescription: Use `unittest` to verify that the `exit` function was called


code:
mynode = list(graph_db.find('mylabel', property_key='screen_name',
              property_value='foo'))

rawDescription: how to check if a node exists in NEO4J with py2neo

description: Check if a node exists in NEO4J with py2neo


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc_context
from matplotlib import ticker as tick

def init_plot_dark():
    params = {'backend' : 'agg', 'legend.numpoints' : 1,
    'lines.linewidth' : 1.0, 'lines.linestyle' : '-', 'axes.facecolor' : '#EEEEEE', 'axes.edgecolor' : '#FFFFFF',
    'axes.linewidth' : 0.0, 'axes.grid' : True, 'axes.titlesize' : 'large', 'axes.labelsize' : 12, 'axes.labelweight' : 'normal',
    'axes.labelcolor' : '000000', 'axes.axisbelow' : True, 'polaraxes.grid' : True , 'axes3d.grid' : True,
    'axes.color_cycle' : ('#E41A1C', '#377EB8', '#4DAF4A', '#984EA3', '#FF7F00', '#FFFF33', '#A65628', '#F781BF', '#999999'),
    'xtick.major.size' : 4 ,'xtick.minor.size' : 2 ,'xtick.major.width' : 0 ,'xtick.minor.width' : 0 ,'xtick.major.pad' : 6,
    'xtick.minor.pad' : 6, 'xtick.color' : '#000000' , 'xtick.labelsize' : 10, 'xtick.direction' : 'in',
    'ytick.major.size' : 4, 'ytick.minor.size' : 2 ,'ytick.major.width' : 0 ,'ytick.minor.width' : 0 ,'ytick.major.pad' : 6,
    'ytick.minor.pad' : 6 ,'ytick.color' : '#000000', 'ytick.labelsize' : 10, 'ytick.direction' : 'in',
    'grid.color' : '#FFFFFF', 'grid.linestyle' : '-', 'grid.linewidth' : 0.5, 'grid.alpha' : 1.0,
    'legend.fontsize' : 10, 'legend.borderaxespad' : 0.5, 'legend.shadow' : False, 'legend.frameon' : True}
    plt.rcParams.update(params)

init_plot_dark()

data = np.genfromtxt("secondary_axis.dat", skiprows = 2, delimiter = ',')
time = data[:, 0]
pressure = data[:, 1] * 0.006894759086775369
pressure_charge = data[0, 0]
needle_lift = data[:, 2]
figure = plt.figure(figsize=(5.15, 5.15))
figure.clf()
plot = plt.subplot(111)
plot.plot(time, needle_lift, color='#4DAF4A', zorder = 1)
plot.set_xlabel(r'\textit{X}', labelpad=6)
plot.set_ylabel(r'\textit{Z}', labelpad=6)
ax2 = plot.twinx()
ax2.plot(time, pressure, label = r'\textit{Raw}', zorder = 2)
ax2.grid(False)
ax2.set_ylabel(r'\textit{Y}', labelpad=6)
primary_ticks = len(ax2.yaxis.get_major_ticks())
plot.yaxis.set_major_locator(tick.LinearLocator(primary_ticks))

plot.yaxis.tick_right()
plot.yaxis.set_label_position("right")

ax2.yaxis.tick_left()
ax2.yaxis.set_label_position("left")

plt.show()

rawDescription: How to arrange plots of secondary axis to be below plots of primary axis in matplotlib?

description: Arrange plots of secondary axis to be below plots of primary axis in matplotlib


code: import time

rawDescription: Python: Generate a date time string that I can use in for MySQL


code:
from math import sqrt

def dot_product(x, y):
    return sum([x[i] * y[i] for i in range(len(x))])

def norm(x):
    return sqrt(dot_product(x, x))

def normalize(x):
    return [x[i] / norm(x) for i in range(len(x))]

def project_onto_plane(x, n):
    d = dot_product(x, n) / norm(n)
    p = [d * normalize(n)[i] for i in range(len(n))]
    return [x[i] - p[i] for i in range(len(x))]

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


rawDescription: Please help me understand a bit shift operation


code:
from itertools import starmap, repeat
from types import FunctionType
funcs = (lambda x: x + 1, lambda x: x + 2)
obj = 5
list(starmap(FunctionType.__call__, zip(funcs, repeat(obj))))

rawDescription: Apply list of functions on an object in Python


code:
class Parse(object):
    """A generator that iterates through a CC-CEDICT formatted file, returning
    a tuple of parsed results (Traditional, Simplified, Pinyin, English)"""
    def __init__(self, path):
        self.path = path

    def __is_comment(self, line):
        return line.startswith("#")

    def __iter__(self):
        with open(self.path) as f:
            for line in f:
                if self.__is_comment(line):
                    continue

                working = line.rstrip().split(" ")
                trad, simp = working[0], working[1]
                working = " ".join(working[2:]).split("]")
                pinyin = working[0][1:]
                english = working[1][1:]
                yield trad, simp, pinyin, english

rawDescription: Python Custom Iterator: Close a file on StopIteration


code: left, right = branches(tree)

rawDescription: how print_parts() function work in composing program chapter2.3

description: How print_parts() function work in composing program chapter2.3


rawDescription: how to parse a list or string into chunks of fixed length

description: Parse a list or string into chunks of fixed length


code:
cur.execute("SELECT Color, Smell FROM Table1, Table2 "
            "WHERE replace(Table1.Name, '\n', '') = Table2.Name")

rawDescription: Deal with new line character “\n” in Sqlite database using Python?


code:
import numpy as np

np.where(a<0,'LOW','HIGH')

rawDescription: How to update a 2d numpy array?

description: Update a 2d numpy array


code:
async def main(sleep, loop):
    for i in range(10):
        loop.create_task(sleep(i))
    await sleep(3)
    nb_cancelled = sleep.cancel_all()
    await asyncio.wait(sleep.tasks)
    return nb_cancelled

sleep = make_sleep()
loop = asyncio.get_event_loop()
result = loop.run_until_complete(main(sleep, loop))
print(result)  # Print '6'

rawDescription: Interrupt all asyncio.sleep currently executing


code: all(x == y for x, y in enumerate(numbers, numbers[0]))

rawDescription: Determine if numbers are in ascending order using 'all'


code: main()

rawDescription: Python Copy specified lines from text file


code:
polynomial = np.poly1d(coefficients)
xp = np.linspace(-2, 6, 100)

plt.plot(soDF['log_total_rep'], soDF['log_users'], '.', xp, polynomial(xp), '-')

rawDescription: using pandas and numpy to parametrize stack overflow's number of users and reputation

description: Using pandas and numpy to parametrize stack overflow's number of users and reputation


code:
class Foo (Base):
    def get_message_impl (self):
        return "Hello World";

rawDescription: How can I wrap an empty function to be implemented by a child class in a try-except block?

description: Wrap an empty function to be implemented by a child class in a try-except block


code: re.sub(r"\bhello\b", '<>', inputstring)

rawDescription: Regular Expressions working differently in Python and Ruby


code:
import sys, tty, termios
def getch():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

letter1 = getch()
letter2 = getch()
print("Pressed", letter1, "and", letter2)

rawDescription: Supersede users need to press enter after inputting a string in python 3.0


code:
from sqlalchemy import text

class Test(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    created = db.Column(db.DateTime, server_default=text('now()'))

rawDescription: Field default timestamp set to table creation time instead of row creation time


code:
from numpy import ma
from  matplotlib import cbook

class MidPointNorm(Normalize):
    def __init__(self, midpoint=0, vmin=None, vmax=None, clip=False):
        Normalize.__init__(self,vmin, vmax, clip)
        self.midpoint = midpoint

    def __call__(self, value, clip=None):
        if clip is None:
            clip = self.clip

        result, is_scalar = self.process_value(value)

        self.autoscale_None(result)
        vmin, vmax, midpoint = self.vmin, self.vmax, self.midpoint

        if not (vmin < midpoint < vmax):
            raise ValueError("midpoint must be between maxvalue and minvalue.")
        elif vmin == vmax:
            result.fill(0) # Or should it be all masked? Or 0.5?
        elif vmin > vmax:
            raise ValueError("maxvalue must be bigger than minvalue")
        else:
            vmin = float(vmin)
            vmax = float(vmax)
            if clip:
                mask = ma.getmask(result)
                result = ma.array(np.clip(result.filled(vmax), vmin, vmax),
                                  mask=mask)

            # ma division is very slow; we can take a shortcut
            resdat = result.data

            #First scale to -1 to 1 range, than to from 0 to 1.
            resdat -= midpoint
            resdat[resdat>0] /= abs(vmax - midpoint)
            resdat[resdat<0] /= abs(vmin - midpoint)

            resdat /= 2.
            resdat += 0.5
            result = ma.array(resdat, mask=result.mask, copy=False)

        if is_scalar:
            result = result[0]
        return result

    def inverse(self, value):
        if not self.scaled():
            raise ValueError("Not invertible until scaled")
        vmin, vmax, midpoint = self.vmin, self.vmax, self.midpoint

        if mpl.cbook.iterable(value):
            val = ma.asarray(value)
            val = 2 * (val-0.5)
            val[val>0]  *= abs(vmax - midpoint)
            val[val<0] *= abs(vmin - midpoint)
            val += midpoint
            return val
        else:
            val = 2 * (val - 0.5)
            if val < 0:
                return  val*abs(vmin-midpoint) + midpoint
            else:
                return  val*abs(vmax-midpoint) + midpoint

rawDescription: Defining the midpoint of a colormap in matplotlib


code:
{'ok': 1.0,
 'result': [{'Applicants': {'Advisor': 'Dr. DaPonte2',
                            'Major': 'CSC2',
                            'Name': 'Omar2',
                            'Research': 'Test data entry2',
                            'School': 'SCSU2',
                            'Time': '12 months2',
                            'URL': 'www.2.com',
                            'appId': 200,
                            'budget': 2,
                            'citizenship': 'YES2',
                            'preAwards': 'NO2',
                            'url': 'www.2.com'},
             'Type': 'faculty',
             '_id': 1,
             'award': 'Faculty Research Grant',
             'awardAmount': 20000,
             'numAwards': 2,
             'url': 'www.url.com'}]}

rawDescription: Return certain fields in mongodb

description: Return certain fields in mongodb


rawDescription: How can I get a Python decorator to run after the decorated function has completed?

description: Get a Python decorator to run after the decorated function has completed


code:
from lxml import etree
tree = etree.parse('test.xml')
tree.getroot().attrib['id']

rawDescription: Get attribute of first element using lxml


code:
from itertools import cycle, islice

def merge(a, b, pos):
    "merge('ABCDEF', [1,2,3], 3) --> A B 1 C D 2 E F 3"
    iterables = [iter(a)]*(pos-1) + [iter(b)]
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

rawDescription: Merge 2 lists at every x position

description: Merge 2 lists at every x position


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

driver = webdriver.Firefox()
driver.get("http://racing4everyone.eu/2015/10/25/formula-e-201516formula-e-201516-round01-china-race/")

# wait for the page to load
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".fluid-width-video-wrapper")))

# get the page source
page_source = driver.page_source

driver.close()

# parse the HTML
soup = BeautifulSoup(page_source, "html.parser")
script = soup.find_all("script")
print(script)

rawDescription: Use BeautifulSoup to obtain "View Element" code instead of "View Source" code


rawDescription: Python for-loop with if-statements

description: Python for-loop with if-statements


code:
xc = sum(x for (x, y) in points) / len(points)
yc = sum(y for (x, y) in points) / len(points)

rawDescription: How to compute the center of a polygon in 2D and 3D space

description: Compute the center of a polygon in 2D and 3D space


code:
# dictionary sorted by key
OrderedDict(sorted(d.items(), key=lambda t: t[0]))
# dictionary sorted by value
OrderedDict(sorted(d.items(), key=lambda t: t[1]))
# dictionary sorted by length of the key string
OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))

rawDescription: Python: Writing an empty dictionary with strings thats ordered


code: [(f1, f2) for f1 in fruits1 for f2 in fruits2 if f1 < f2]

rawDescription: String loops in Python

description: String loops in Python


code:
from ctypes import *

class vendrRecord(Structure):
    _fields_ = [("ytdPayments",c_ulong)]

    VendrRecord = vendrRecord()
    libc = cdll.msvcrt
    libc.sscanf(b"1 2 3", b"%d", byref(VendrRecord))   # read something into the structure
    print(vendrRecord.ytdPayments) # class name
    print(VendrRecord.ytdPayments) # instance name

rawDescription: Accessing a structure element in Python

description: Accessing a structure element in Python


code:
from weapons import Sword, Bow, Axe, MachinneGun
from medicine import HealthPotion, MaxHealthPotion, Poison, Antidote

rawDescription: How to pull information from classes through raw input

description: Pull information from classes through raw input


code: location = [l for l in (self.room, self.floor, self.building) if l is not None][:1]

rawDescription: Python: a better way to write a if-then block with join?


code:
class ComparableMixin(object):
    def _compare(self, other, method):
        try:
            return method(self._cmpkey(), other._cmpkey())
        except (AttributeError, TypeError):
            # _cmpkey not implemented, or return different type,
            # so I can't compare with "other".
            return NotImplemented

    def __lt__(self, other):
        return self._compare(other, lambda s, o: s < o)

    def __le__(self, other):
        return self._compare(other, lambda s, o: s <= o)

    def __eq__(self, other):
        return self._compare(other, lambda s, o: s == o)

    def __ge__(self, other):
        return self._compare(other, lambda s, o: s >= o)

    def __gt__(self, other):
        return self._compare(other, lambda s, o: s > o)

    def __ne__(self, other):
        return self._compare(other, lambda s, o: s != o)

rawDescription: Comparable classes in Python 3

description: Comparable classes in Python 3


code:
exclude = set(range(4, 8) + [1] + range(0, 2))
[n for n in nums if n not in exclude]

rawDescription: Can I use the slice method to return a list that excludes ranges in the middle of the original list?

description: Use the slice method to return a list that excludes ranges in the middle of the original list


code: df = df.loc[df['Var1'] != 0]

rawDescription: Iterate through rows in pandas dateframe in a cleaner way using .iterrows() and keep track of rows inbetween specific values


code:
import pprint

response = {"status": "ERROR", "email": "EMAIL_INVALID", "name":
            "NAME_INVALID"}

def convert(label):
    return {'NAME_INVALID': 'No special characters allowed',
            'EMAIL_INVALID': 'invalid email',
            'ERROR': 'ERROR'}[label]

ret = {}
for k in response:
    if k != 'status':
        ret[k + "_label"] = convert(response[k])
        ret[k] = response[k]
        info = {'converted_value': ret[k + "_label"],
                'field': k,
                'value': response[k]}
        (ret.setdefault('api_error', {})
            .setdefault('list', [])
            .append(info))
    else:
        ret[k] = convert(response[k])
        ret.setdefault('api_error', {})['status'] = ret[k]
pprint.pprint(ret)

rawDescription: create a python dictionary based on another dictionary

description: Create a python dictionary based on another dictionary


code: ln -s /path/to/virtualenv /usr/local/bin/virtualenv

rawDescription: Trouble Installing virtualenv on Python 3.5.1 OSX


rawDescription: A sequence of empty lists of length n in Python?


rawDescription: Recursion: Nested dictionaries to XML(HTML)


code:
df['colA'].fillna(modes)
df['colA'] = df['colA'].fillna(modes)

rawDescription: backfilling data from one column into another

description: Backfilling data from one column into another


code:
import os
desc = os.pipe()
desc
os.write(desc[1], 'foo')
os.read(desc[0], 100)
os.read(desc[0], 100)

rawDescription: Reads after select() - blocking on a pipe


code:
def hours_since(timestamp):
    import datetime
    return (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(timestamp)).total_seconds() / 3600.

rawDescription: How to get the number of hours since, from a UTC timestamp?

description: Get the number of hours since, from a UTC timestamp


code:
raw = subprocess.check_output('ps -eo pcpu,pid,user,args --sort -pcpu')
first_three_lines = list(raw.split('\n'))[:3]

rawDescription: piping in shell via Python subprocess module

description: Piping in shell via Python subprocess module


code:
def moveplot(self):
    self.t+=1
    self.updateplot()

rawDescription: How to update a realtime plot and use buttons to interact in pyqtgraph?

description: Update a realtime plot and use buttons to interact in pyqtgraph


rawDescription: How to sum elements of a list corresponding to elements of another list in python

description: Sum elements of a list corresponding to elements of another list in python


code:
import pandas as pd

df1 = pd.DataFrame(
[('A12VH45Q3H5R5I', 'B000NWJTKW', 5.0),
 ('A3J8AQWNNI3WSN', 'B000NWJTKW', 4.0),
 ('A1XOBWIL4MILVM', 'BDASK99000', 1.0)], columns=['user', 'item', 'rating'])

df2 = pd.DataFrame(
[('B000NWJTKW', 10),
 ('BDASK99000', 20)], columns=['item', 'extra'])

codes, uniques = pd.factorize(pd.concat([df1['item'], df2['item']]))
df1['item'] = codes[:len(df1)] + 1
df2['item'] = codes[len(df1):] + 1

codes, uniques = pd.factorize(df1['user'])
df1['user'] = codes + 1

print(df1)
print(df2)

rawDescription: How to factorize two data frame meanwhile with python-pandas?

description: Factorize two data frame meanwhile with python-pandas


code:
from bs4 import BeautifulSoup

with open('sample.html', 'r') as html_doc:

    soup = BeautifulSoup(html_doc, 'html.parser')

    for row in soup.find_all('tr', 'stats'):
        row_tds = row.find_all_next('td')
        print('{0} {1}'.format(
            row_tds[0].find('a').string.strip() if row_tds[0].find('a').string else 'None',
            row_tds[2].string.strip() if row_tds[2].string else 'None')
        )

rawDescription: Python HTML Regex

description: Python HTML Regex


code:
def StringTest(string1, string2):
  return string2 in string1

rawDescription: find if string1 is contained in string2 in python

description: Find if string1 is contained in string2 in python


code:
from operator import sub
C = map(sub, A, B)

rawDescription: Subtract values in one list from corresponding values in another list - Python


code:
def set_properties(cls):
    for name, propcls in vars(AttrContainer).iteritems():
        if name in cls.properties:
            setattr(cls, name, vars(propcls)[name])
    return cls

rawDescription: Python: Copy properties with it's functions (fget, fset, fdel) from one class to another


code:
import pygame
from collections import deque

pygame.init()
screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

# just some colored squares for our animation
def get_cache(colors):
    tmp=[]
    for c in colors:
        s = pygame.surface.Surface((50,50))
        s.fill(pygame.color.Color(c))
        tmp.append(s)
    return tmp

walk_left, walk_right = get_cache(('red', 'yellow', 'blue')), get_cache(('black', 'white', 'grey'))

rect = walk_left[0].get_rect(top=100, right=100)
cachedeque = deque(walk_left)
state = None
quit = False

# a simple variable to keep track of time
timer = 0

# a dict of {key: (animation, direction)}
moves = {pygame.K_LEFT:  (walk_left,  (-2, 0)),
         pygame.K_RIGHT: (walk_right, ( 2, 0))}

while not quit:
    quit = pygame.event.get(pygame.QUIT)
    pygame.event.poll()

    # state of the keys
    keys = pygame.key.get_pressed()

    # filter for the keys we're interessted in
    pressed = ((key, _) for (key, _) in moves.iteritems() if keys[key])
    key, (cache, dir) = next(pressed, (None, (None, None)))

    # if a key of the 'moves' dict is pressed:
    if key:
        # if we change the direction, we need another animation
        if state != key:
            cachedeque = deque(cache)
            state = key
        # move the square
        rect.move_ip(dir)
    else:
        state = None

    screen.fill(pygame.color.Color('green'))

    # display first image in cachedeque
    screen.blit(cachedeque[0], rect)

    # rotate cachedeque to the left, so the second image becomes the first
    # do this three times a second:
    if state and timer >= 1000./3:
        cachedeque.rotate(-1)
        timer = 0

    # call flip() and tick() only once per frame
    pygame.display.flip()

    # keep track of how long it took to draw this frame
    timer += clock.tick(60)

rawDescription: Pygame keyboard input event lag

description: Pygame keyboard input event lag


code:
import judy
dir(judy)
a=judy.JudyIntObjectMap()
dir(a)
a[100]=1
a[100]="str"
a["str"]="str"
for i in xrange(30000000):
    a[i]=i+30000000   #finally eats ~986MB memory

rawDescription: efficient way to hold and process a big dict in memory in python

description: Efficient way to hold and process a big dict in memory in python


code:
subprocess.call(['/Library/Frameworks/GDAL.framework/Programs/ogr2ogr', '-f',
                 '"GeoJSON"', 'output.json', 'input.shp'])

rawDescription: launching something within python

description: Launching something within python


code:
from binascii import unhexlify

cipher = unhexlify(b'A14E71A6F4E8D8E465C3C302C2A96BD2')

rawDescription: Decrypt hex string with python

description: Decrypt hex string with python


rawDescription: Is there a way to create argument in python's argparse that returns true in case no values given


code:
from django import forms

class GenderForm(forms.Form):
    CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    choice = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())

rawDescription: how to create a dynamically-created radio buttons form in django

description: Create a dynamically-created radio buttons form in django


code:
p = Project.objects.get(name='myproject')
users = p.users.all()

rawDescription: have multiple users as one model field in many to one format django models

description: Have multiple users as one model field in many to one format django models


code: area = [[] for i in range(37)]

rawDescription: List of named lists

description: List of named lists


code:
def my_patch(obj, attr_name):
    fake_class = mock.MagicMock()
    fake_instance = fake_class.return_value  # calling a class returns an instance.
    fake_instance.__class__ = getattr(obj, attr_name)
    return mock.patch.object(obj, attr_name, fake_class)

rawDescription: Mock class used in isinstance checks which has dynamic attributes


code:
if fields is None:
    fields = []
self.fields = fields

rawDescription: python method variables and Objects created in method

description: Python method variables and Objects created in method


code: [('international',), ('international',), ('international', 'open')]

rawDescription: Python: using scikit-learn to predict, gives blank predictions


rawDescription: Grab all but one element in pandas series


code:
all_columns = [
    ('H' , 'Hydrogen'    , 'grey', 1, 0),
    ('Li', 'Li-something', 'grey', 2, 0),
    ('Na', 'Na-something', 'grey', 3, 0),
    ('K' , 'K-something' , 'grey', 4, 0),
    ('Rb', 'Rb-something', 'grey', 5, 0),
    ('Cs', 'Cs-something', 'grey', 6, 0),
    ('Fr', 'Fr-something', 'grey', 7, 0),

    ('Be', 'Be-something', 'green', 2, 1),
    ('Mg', 'Mg-something', 'green', 3, 1),
    ('Ca', 'Ca-something', 'green', 4, 1),
    ('Sr', 'Sr-something', 'green', 5, 1),
    ('Ba', 'Ba-something', 'green', 6, 1),
    ('Ra', 'Ra-something', 'green', 7, 1),

    ('Sc', 'Sc-something', 'yellow', 4, 2),
    ('Y' , 'Y-something' , 'yellow', 5, 2),
    ('La   >|', 'La-something', 'yellow', 6, 2),
    ('Ac   >|', 'Ac-something', 'yellow', 7, 2)
]

# create all buttons with a loop
for element in all_columns:
    button_text, label_text, button_color, button_row, button_col = element
    tk.Button(self, text=button_text, width=5, height=2, bg=button_color, command=lambda text=label_text:self.info(text)) \
        .grid(row=button_row, column=button_col)

rawDescription: Python: Changing label depending which button is pressed


rawDescription: How to get full windows path in python

description: Get full windows path in python


code: print ('%02d' % (mydate.month))

rawDescription: datetime objects format

description: Datetime objects format


code:
import itertools
import pandas as pd

labels = ['IL', 'IL-1', 'IL-2', 'IL-3', 'IL-4', 'IL-5']
i = pd.MultiIndex.from_tuples(list(itertools.combinations(labels, 2)))
df = pd.DataFrame({'col1':range(len(i))}, index=i)

rawDescription: cross join/merge to create dataframe of combinations (order doesn't matter)

description: Cross join/merge to create dataframe of combinations (order doesn't matter)


code:
import time
from timeit import Timer

def my_timeit(func, *args, **kwargs):
    output_container = []
    def wrapper():
        output_container.append(func(*args, **kwargs))
    timer = Timer(wrapper)
    delta = timer.timeit(1)
    return delta, output_container.pop()

def foo():
    time.sleep(1.111)
    return 'potato'

delta, result = my_timeit(foo)

rawDescription: timeit eats return value

description: Timeit eats return value


code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
                            requestHandler=RequestHandler)

def myfunction(x, y):
    status = 1
    result = [5, 6, [4, 5]]
    return (status, result)
server.register_function(myfunction)

# Run the server's main loop
server.serve_forever()

rawDescription: convention to represent the exit status and actual result in XMLRPC

description: Convention to represent the exit status and actual result in XMLRPC


code:
back.grid(row=1, column=1)
mw.grid_rowconfigure(0, weight=1)
mw.grid_rowconfigure(2, weight=1)
mw.grid_columnconfigure(0, weight=1)
mw.grid_columnconfigure(2, weight=1)

rawDescription: Place objects in the middle of a frame in tkinter python


code:
import CMUTweetTagger

CMUTweetTagger.runtagger_parse(...)

rawDescription: Add Python script so can be imported in another Python script


code:
def elements_replaced(lst, new_element, indices):
    return [new_element if i in indices else e for i, e in enumerate(lst)]

rawDescription: Replacing selected elements in a list in Python


code:
register(
    "python-fu-draw",                                #<- this is plugin name
    N_("brief"),                                     #<- description
    "Long",                                          #<- description
    "name surname",                                  #<- author
    "@Copyright 2013",                               #<- copyright info
    "2013/10/29",                                    #<- creation date
    N_("_Draw..."),                                  #<- label shown in gimp's menu
    "",  #<- kind of image requested from your script (INDEX,RGB,...and so on)
    [                                                #<- input parameters array
        (PF_FILE, "ifile", N_("Color input file"), 'default.txt'),
],
[],                                                  #<- output parameters array (usually empty)
draw,                                                #<- main method to call
menu="<Image>/Filters/",                             #<- Where add your plugin
domain=("gimp20-python", gimp.locale_directory)
)

main()                                               #<- don't forget this

rawDescription: python can't import gimpfu

description: Python can't import gimpfu


rawDescription: Sort N-D numpy array by another 1-D array


rawDescription: Python, neighbors on a regular grid

description: Python, neighbors on a regular grid


code:
data = {'a': 1, 'aa': 2, 'b': 3, 'cd': 4}
list(data)
data['f'] = 1
list(data)
del data['a']
list(data)
data[1] = 1
list(data)
for c in ('cde', 'fgh', 'ijk', 'rmn'):
    data[c] = 1

list(data)

rawDescription: how to get key of dictionary in python

description: Get key of dictionary in python


code:
import whatever
import functools

def wrap_function(oldfunction, newfunction):
    @functools.wraps(function)
    def run(*args, **kwargs):
        return newfunction(oldfunction, *args, **kwargs)
    return run

def this_is_a_function(oldfunc, parameter):
    # Do some processing or something to customize the parameters to pass
    newparams = parameter * 2  # Example of a change to newparams
    return oldfunc(newparams)

whatever.this_is_a_function = wrap_function(
        whatever.this_is_a_function, this_is_a_function)

rawDescription: Hook python module function

description: Hook python module function


code:
@register.inclusion_tag('Kappa/sidebar.html', takes_context=True)
def get_game_list(context):
    return {'game_list': Game.objects.all(),  'user': context['user']}

rawDescription: Template not rendering properly with if user.is_authenticated for Django


rawDescription: How to extract last set of parentheses in a string

description: Extract last set of parentheses in a string


code:
import os
import glob

want_header = True
out_filename = "combined.files.csv"

if os.path.exists(out_filename):
    os.remove(out_filename)

read_files = glob.glob("*.csv")

with open(out_filename, "w") as outfile:
    for filename in read_files:
        with open(filename) as infile:
            if want_header:
                outfile.write('{},Filename\n'.format(next(infile).strip()))
                want_header = False
            else:
                next(infile)
            for line in infile:
                outfile.write('{},{}\n'.format(line.strip(), filename))

rawDescription: Merging all csvs in a folder and adding a new column with filename of original file in Python


code: a_list = [el[1:] for el in (tuple(x) for x in reader)]

rawDescription: Python removing first element of tuple in a list


code:
def updatesomethings(self):
    a = 100
    b = 200
    c = 300
    vars(self).update(locals())
    del self.self

rawDescription: Python importing class attributes into method local namespace


code:
def newChannel(cName):
    queue = j.queue(cName)
    r = queue.add_subscribers(*[subscriberCreateChanTable, subscriberSortScenes])

def newNetwork(hName):
    queue = j.queue(hName)
    r = queue.add_subscribers(*[subscriber1a])

def loginError(nName):
    pass

def hName(ok):
    return ok[11][1]

def cName(ok):
    return ok[12][1]

def nName(ok):
    return ok[10][1]

def eventType(ok):
    return ok[9][1]

action = {
    'newChannel': (newChannel, cName),
    'newNetwork': (newNetwork, hName),
    'loginError': (loginError, nName)
     }

ok = parse_qsl(urlparse(u).query, keep_blank_values=True)
handler, getter = action.get(eventType(ok))
handler(getter(ok))

rawDescription: Dispatch dictionary but pass different parameters to functions


rawDescription: Python/Scipy: Find "bounded" min/max of a matrix


code:
from random import choice
from string import ascii_uppercase

print(''.join(choice(ascii_uppercase) for i in range(12)))

rawDescription: What's the best way to generate random strings of a specific length in Python?


code:
a = []
for x in range(8):
    row = []
    for y in range(8):
        row.append(0)
    a.append(row)

rawDescription: More elegant way to create a 2D matrix in Python


rawDescription: how to remove hashtag, @user, link of a tweet using regular expression

description: Remove hashtag, @user, link of a tweet using regular expression


code:
for thread in threads:
    thread.start()

for thread in threads:
    thread.join()

rawDescription: python will different threads end at the same time as the first one to finish

description: Python will different threads end at the same time as the first one to finish


rawDescription: python regular expression to validate types of strings

description: Python regular expression to validate types of strings


code: sys.argv[0] = sys.argv[0].replace('-2.3', '')

rawDescription: Choose Python version for egg installation or install parallel versions of site-package


code:
with open('test.txt') as fp:
    api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
    data = json.load(fp)
    api.update_status(data['data']['children'][3]['data']['title'])

rawDescription: Trying update Twitter status with scraper data using Twython. Unsure on what to do


code:
from scipy.stats import t
t.interval(0.95, 10, loc=1, scale=2)  # 95% confidence interval
t.interval(0.99, 10, loc=1, scale=2)  # 99% confidence interval

rawDescription: student t confidence interval in python

description: Student t confidence interval in python


rawDescription: Confused with getattribute and setattribute in python


code:
intervals = [(2, 10), (3, 15), (4, 9), (8, 14), (7, 13), (5, 10), (11, 15)]
intqueue = sorted([(x[0], +1) for x in intervals] + [(x[1], -1) for x in intervals])
rsum = [(0,0)]
for x in intqueue:
    rsum.append((x[0], rsum[-1][1] + x[1]))
busiest_start = max(rsum, key=lambda x: x[1])
# busiest_end = the next element in rsum after busiest_start

# instead of using lambda, alternatively you can do:
#     def second_element(x):
#         return x[1]
#     busiest_start = max(rsum, key=second_element)
# or:
#     import operator
#     busiest_start = max(rsum, key=operator.itemgetter(1))

rawDescription: Algorithm for finding the busiest period?


code:
for x in iterable:
    num += x
    denom += 1
    yield num / denom

rawDescription: To make the following code run faster?

description: To make the following code run faster


code: result = '{}{:02d}'.format(letters, number)

rawDescription: List of 2 letters 2 numbers?

description: List of 2 letters 2 numbers


code:
for l in mygrid:
    print(l)

rawDescription: cipher exceeds the 4X4 grid and prints out wrong cipher

description: Cipher exceeds the 4X4 grid and prints out wrong cipher


code:
from scipy.spatial import distance_matrix
loc = df[['X','Y']].values
dist_mat = distance_matrix(loc, loc)

from scipy.spatial.distance import cdist
dist_mat = cdist(loc, loc)

rawDescription: Pandas Dataframe: Operations on columns without iterrows()


code:
test = False
test = ""
test = 0
test = 0.0
test = []
test = ()
test = {}
test = set()

rawDescription: Difference between "if x" and "if x is not None"


rawDescription: Fancy indexing in pandas

description: Fancy indexing in pandas


rawDescription: Howto sort alphanumerical values (a1,a2,a3,...) in a CSV line after line with Python


code: 'SELECT * FROM table WHERE column IN (1,2,3);'

rawDescription: Passing list of parameters to SQL in psycopg2


code:
from __future__ import division
import numpy as np
from PIL import Image

im = Image.open(imfile)
arr = np.asarray(im)

arr[..., 0]  # All Red values
arr[..., 1]  # All Green values
arr[..., 2]  # All Blue values
arr[0, 0]    # RGB for first corner pixel
arr[m, n]    # RGB for pixel at [m, n]
arr[m, n, 0] # R value for pixel [m, n]
arr[m, n, c] # value for color c at pixel [m, n]

rawDescription: Iterating a function over the RGB values of individual pixels


code:
values = [1, 2, 3, 4, 5]
thecsv = csv.writer(open("your.csv", 'wb'))
for value in values:
    thecsv.writerow(value)

rawDescription: Convert Python List to Column in CSV

description: Convert Python List to Column in CSV


code:
def add_to_result(x):
    def decorator(fn):
        def wrapped_function(*args, **kwargs):
            return fn(*args, **kwargs)+x
        return wrapped_function
    return decorator

@add_to_result(3)
def my_func(a, b):
    return a+b
print(my_func(1,2)) # 6

rawDescription: Python decorators theory

description: Python decorators theory


code:
#create a color palette with the same number of colors as unique values in the Source column
network_pal = sns.light_palette('red', len(df.Source.unique()))

#Create a dictionary where the key is the category and the values are the
#colors from the palette we just created
network_lut = dict(zip(df.Source.unique(), network_pal))

#get the series of all of the categories
networks = df.Source

#map the colors to the series. Now we have a list of colors the same
#length as our dataframe, where unique values are mapped to the same color
network_colors = pd.Series(networks).map(network_lut)

#plot the heatmap with the 16S and ITS categories with the network colors
#defined by Source column
sns.clustermap(df[['16S', 'ITS']], row_colors=network_colors, cmap='BuGn_r')

rawDescription: Setting col_colors in seaborn clustermap from pandas


code:
import pytz
from datetime import datetime
datetime.utcnow().replace(tzinfo = pytz.utc)

rawDescription: Python: How to get a value of datetime.today() that is "timezone aware"?


code:
for i in xrange(len(A)):
    for j in xrange(len(A)):
        if i != j:
            do_stuff(A[i], A[j])

rawDescription: How to do C++ style(indexed) nested loops in python?

description: Do C++ style(indexed) nested loops in python


code:
for i in range(1,r+1):
    for j in range(1,c+1):
        currentNumber = i**j
        print ("{0:>{1}}".format(currentNumber ,numberLength), end=' ')
    print()

rawDescription: correct layout of format

description: Correct layout of format


code:
self.collection.update({"email": "email", "pwd_list.pwd": "Password2"},
        {
        "$set": {
            "pwd_list.$": {
                        "pwd": "NEW VALUE",
                        "pwd_date": "str(int(time.time()))"
                        }
               }
        })

rawDescription: Pymongo How to update specific value of row in array


code:
for element in tree.iter(tag = 'element10'):
    ...

rawDescription: XML parsing: set great-great-...-grandchild element as a root in Python


code: config.readfp(open('%sconfig/clenotes.cfg' % System.getProperty('jython.home'), "rU"))

rawDescription: Python sys.argv[1:] not picking up command line options


code:
import tkinter as tk
from random import randint

root= tk.Tk()
entry= tk.Entry(root)
def callback(text):
    entry.insert(0, text)

for i in range(20):
    data= str(randint(0,100))
    tk.Button(root, text=data, command=lambda data=data: callback(data)).pack()
entry.pack()
root.mainloop()

rawDescription: Make a button's command cause the button's text to be inserted into an entry


code:
"""
An experimental support for curvilinear grid.
"""
import numpy as np
import  mpl_toolkits.axisartist.angle_helper as angle_helper
import matplotlib.cm as cmap
from matplotlib.projections import PolarAxes
from matplotlib.transforms import Affine2D

from mpl_toolkits.axisartist import SubplotHost

from mpl_toolkits.axisartist import GridHelperCurveLinear

def curvelinear_test2(fig, rect=111):
    """
    polar projection, but in a rectangular box.
    """

    # see demo_curvelinear_grid.py for details
    tr = Affine2D().translate(0,90) + Affine2D().scale(np.pi/180., 1.) + PolarAxes.PolarTransform()

    extreme_finder = angle_helper.ExtremeFinderCycle(10, 60,
                                                     lon_cycle = 360,
                                                     lat_cycle = None,
                                                     lon_minmax = None,
                                                     lat_minmax = (-90, np.inf),
                                                     )

    grid_locator1 = angle_helper.LocatorHMS(12) #changes theta gridline count
    tick_formatter1 = angle_helper.FormatterHMS()

    grid_helper = GridHelperCurveLinear(tr,
                                        extreme_finder=extreme_finder,
                                        grid_locator1=grid_locator1,
                                        tick_formatter1=tick_formatter1
                                        )

    ax1 = SubplotHost(fig, rect, grid_helper=grid_helper)

    # make ticklabels of right and top axis visible.
    ax1.axis["right"].major_ticklabels.set_visible(True)
    ax1.axis["top"].major_ticklabels.set_visible(True)
    ax1.axis["bottom"].major_ticklabels.set_visible(True) #Turn off?
    # let right and bottom axis show ticklabels for 1st coordinate (angle)
    ax1.axis["right"].get_helper().nth_coord_ticks=0
    ax1.axis["bottom"].get_helper().nth_coord_ticks=0

    fig.add_subplot(ax1)

    grid_helper = ax1.get_grid_helper()

    # You may or may not need these - they set the view window explicitly rather than using the
    # default as determined by matplotlib with extreme finder.
    ax1.set_aspect(1.)
    ax1.set_xlim(-4,25) # moves the origin left-right in ax1
    ax1.set_ylim(-3, 30) # moves the origin up-down

    ax1.set_ylabel('Declination')
    ax1.set_xlabel('Ascension')
    ax1.grid(True)
    #ax1.grid(linestyle='--', which='x') # either keyword applies to both
    #ax1.grid(linestyle=':', which='y')  # sets of gridlines

    return ax1,tr

def skip_comments(f):
    '''
    Read lines that DO NOT start with a # symbol.
    '''
    for line in f:
        if not line.strip().startswith('#'):
            yield line

def get_data_bb():
    '''RA, DEC data file.
    '''

    # Path to data file.
    out_file = 'bb_cat.dat'

    # Read data file
    with open(out_file) as f:
        ra, dec = [], []

        for line in skip_comments(f):
            ra.append(float(line.split()[0]))
            dec.append(float(line.split()[1]))

    return ra, dec

import matplotlib.pyplot as plt
fig = plt.figure(1, figsize=(5, 5))
fig.clf()

ax1, tr = curvelinear_test2(fig,121) # tr.transform_point((x, 0)) is always (0,0)
                            # => (theta, r) in but (r, theta) out...

# Read RA, DEC data from file.
ra, dec = get_data_bb()
out_test = tr.transform(zip(ra, dec))

# Use this block to generate colored points with a colorbar.
cm = plt.cm.get_cmap('RdYlBu_r')
z = np.random.random((len(ra), 1))  # RGB values

SC = ax1.scatter(out_test[:,0], #ax1 is a global
            out_test[:,1],
            marker = 'o',
            c=z,
            cmap=cm,
            lw = 0.,
            zorder=9) #on top of gridlines

# Colorbar
cbar = plt.colorbar(SC, shrink=1., pad=0.1)
cbar.ax.tick_params(labelsize=8)
cbar.set_label('colorbar', fontsize=8)

ax2, tr = curvelinear_test2(fig,122) # tr.transform_point((x, 0)) is always (0,0)
                            # => (theta, r) in but (r, theta) out...

# Read RA, DEC data from file.
ra, dec = get_data_bb()
out_test = tr.transform(zip(ra, dec))

# Use this block to generate colored points with a colorbar.
cm = plt.cm.get_cmap('RdYlBu_r')
z = np.random.random((len(ra), 1))  # RGB values

SC = ax2.scatter(out_test[:,0], #ax1 is a global
            out_test[:,1],
            marker = 'o',
            c=z,
            cmap=cm,
            lw = 0.,
            zorder=9) #on top of gridlines

# Colorbar
cbar = plt.colorbar(SC, shrink=1., pad=0.1)
cbar.ax.tick_params(labelsize=8)
cbar.set_label('colorbar', fontsize=8)

plt.show()

rawDescription: Produce a RA vs DEC equatorial coordinates plot with python


code:
from pyparsing import *
# sample string with enums and other stuff
sample = '''
    stuff before
    enum hello {
        Zero,
        One,
        Two,
        Three,
        Five=5,
        Six,
        Ten=10,
        minusone=-1,
        par1 = ((0,5)),
        par2 = sizeof("a\\")bc};,"),
        par3 = (')')
        };
    in the middle
    enum
        {
        alpha,
        beta,
        gamma = 10 ,
        zeta = 50
        };
    at the end
    '''

# syntax we don't want to see in the final parse tree
LBRACE,RBRACE,EQ,COMMA = map(Suppress,"{}=,")

lpar  = Literal( "(" )
rpar  = Literal( ")" )
anything_topl = Regex(r"[^'\"(,}]+")
anything      = Regex(r"[^'\"()]+")

expr = Forward()
pths_or_str = quotedString | lpar + expr + rpar
expr <<     ZeroOrMore( pths_or_str | anything )
expr_topl = ZeroOrMore( pths_or_str | anything_topl )

_enum = Suppress('enum')
identifier = Word(alphas,alphanums+'_')
expr_topl_text = originalTextFor(expr_topl)
enumValue = Group(identifier('name') + Optional(EQ + expr_topl_text('value')))
enumList = Group(ZeroOrMore(enumValue + COMMA) + Optional(enumValue) )
enum = _enum + Optional(identifier('enum')) + LBRACE + enumList('names') + RBRACE
enum.ignore(cppStyleComment)

# find instances of enums ignoring other syntax
for item,start,stop in enum.scanString(sample):
    for entry in item.names:
        print('%s %s = %s' % (item.enum,entry.name, entry.value))

rawDescription: Is it possible to parse non-trivial C enums with pyparsing?


code:
nested_list = [[123,'Aaron','CA'],[124,'Bob','WY'],[125,'John','TX']]
insert_me = [122,'George','AL']
keys = [r[1] for r in nested_list]
nested_list.insert(bisect.bisect_left(keys,insert_me[1]),insert_me)
[[123, 'Aaron', 'CA'],
 [124, 'Bob', 'WY'],
 [122, 'George', 'AL'],
 [125, 'John', 'TX']]

rawDescription: Inserting in order to a nested list

description: Inserting in order to a nested list


code:
from bs4 import BeautifulSoup
import requests

url = "http://www.bbc.com/news/world/asia/"
r = requests.get(url)
soup = BeautifulSoup(r.content)

india_links = lambda tag: (getattr(tag, 'name', None) == 'a' and
                           'href' in tag.attrs and
                           'india' in tag.get_text().lower())
results = soup.find_all(india_links)

rawDescription: How to extract html links with a matching word from a website using python

description: Extract html links with a matching word from a website using python


code:
def join(self, timeout=None):
    '''
    Wait until child process terminates
    '''
    assert self._parent_pid == os.getpid(), 'can only join a child process'
    assert self._popen is not None, 'can only join a started process'
    res = self._popen.wait(timeout)
    if res is not None:
        _current_process._children.discard(self)

rawDescription: Background Process Locking up GUI Python


rawDescription: If value contains string, then set another column value


code:
def F_C(x):
    x = raw_input("Please Enter A Value")
    x = int(x)
    x = x - 32
    x = x * 0.55
    return x

rawDescription: Python Temperature Converter

description: Python Temperature Converter


code: [dic[k] for k in sorted(dic)]

rawDescription: Grouping of element in a list given a list of intervals


code:
if __name__ == '__main__':
    for i in range(1, 10):
        port = r'\\.\COM%d' % i
        try:
            prop = get_comm_properties(port)
        except WindowsError as e:
            if e.winerror == ERROR_FILE_NOT_FOUND:
                continue
        print('%s properties' % port)
        x = prop.dwMaxTxQueue if prop.dwMaxTxQueue else 'no limit'
        print('\tMax output buffer size: %s' % x)
        x = prop.dwMaxRxQueue if prop.dwMaxRxQueue else 'no limit'
        print('\tMax input buffer size: %s' % x)
        x = prop.dwCurrentTxQueue if prop.dwCurrentTxQueue else 'unavailable'
        print('\tCurrent output buffer size: %s' % x)
        x = prop.dwCurrentRxQueue if prop.dwCurrentRxQueue else 'unavailable'
        print('\tCurrent input buffer size: %s' % x)
        x = prop.max_baud if prop.max_baud else 'user programmable'
        print('\tMax baud rate: %s' % x)
        print('\tProvider subtypes:\n\t\t%s' %
                    '\n\t\t'.join(prop.prov_subtype))
        print('\tProvider capabilities:\n\t\t%s' %
                    '\n\t\t'.join(prop.prov_capabilities))
        print('\tSettable parameters:\n\t\t%s' %
                    '\n\t\t'.join(prop.settable_params))
        print('\tSettable baud rates:\n\t\t%s' %
                    '\n\t\t'.join([str(x) for x in prop.settable_baud]))
        print('\tSettable user baud rates: %s' %
                    prop.user_settable_baud)
        print('\tSettable data bits:\n\t\t%s' %
                    '\n\t\t'.join([str(x) for x in prop.settable_data]))
        print('\tSettable wide data bits: %s' %
                    prop.wide_settable_data)
        print('\tSettable stop bits:\n\t\t%s' %
                    '\n\t\t'.join([str(x) for x in prop.settable_stop]))
        print('\tSettable parity:\n\t\t%s' %
                    '\n\t\t'.join(prop.settable_parity))

rawDescription: Python serial module failing to configure port


rawDescription: List of named lists

description: List of named lists


code:
threads = []
for i in range(5):
    while True:
        inputNum = long(raw_input("Enter first number: "))
        if inputNum > 1:
            break

    thread = PrimeNumber(inputNum)
    threads += [thread]

rawDescription: I have a program to check if five numbers are prime but it is not working correctly


code:
X, Y = np.indices(A.shape)
np.vstack((X.ravel(), Y.ravel(), A.ravel())).T

rawDescription: Convert n-dimensional numpy array to 2-dimensional index array


code:
@annotate_overrides
class Rectangle(Shape):
    @override
    def area(self):
        return self.height * self.width

rawDescription: How to type annotate overrided methods in a subclass?

description: Type annotate overrided methods in a subclass


rawDescription: Python Convert ordered list of relative changes to absolute changes


rawDescription: Python: Retrieve a file from url and generate data: URI


code:
import json
# Some code that puts result into variable r
# This won't work if r contains non-unicode strings,
# you will have to write your own serializer in this case.
# As far as I know, it will also fail if some characters in the string
# can be represented only using surrogate pairs.
vim.command("let reply=".json.dumps(r))
# Now in the caller function variable l:reply is defined

rawDescription: "scripting" vim using python with greater granularity


code:
def replace2inplace(lst):
    lst[1::2], lst[::2] = lst[::2], lst[1::2]

rawDescription: Python list: exchange every n-th value with the (n+1)th


code:
env = Environment(variable_start_string="{", variable_end_string="}")
env.globals["RANDOM_INT"] = random.randint

user_input = 'file write hi.txt { RANDOM_INT(1, 10) }'
template = env.from_string(user_input)
result = template.render()
print(result)

rawDescription: Python 3 - Replacing part of a string with imformation from the string


rawDescription: How to start checking from specific part of a list in python

description: Start checking from specific part of a list in python


rawDescription: Joining String after certain steps

description: Joining String after certain steps


code:
def count(M, N):
    return sum(N[i:i+len(M)]==M for i in range(len(N)-len(M)+1))

rawDescription: Counting substrings in string

description: Counting substrings in string


rawDescription: Fast vectorized indexing in numpy

description: Fast vectorized indexing in numpy


code:
my_mock.return_value = 'foobar'
my_mock()
my_mock(1, 2)

rawDescription: How to setup return_value for a function call with specific signature?

description: Setup return_value for a function call with specific signature


code: print(rabbit)

rawDescription: Python3 Classes- Can you change it into a string?


code:
t = [[x for x in string if len(x) > 2] for string in s]
t

rawDescription: Converting this filter statement to list comprehension


code:
def __init__(self, **kwargs):
    self.features = kwargs

def getFeatures(self):
    return {feature for feature, isEnabled in self.features.items() if isEnabled}

rawDescription: filling up a list python

description: Filling up a list python


code: any(len(set(l)) < len(l) for l in list1)

rawDescription: Finding repeated values in multiple lists


code:
wavelengths = wavelengths[2:]
intensitiesshaped = intensities[:,:,2:]

rawDescription: Loading .txt data into 10x256 3d numpy array


code:
with open('/tmp/test', 'w') as test:
    test.write('hello!')
    test.flush()
    test.truncate(0)
    test.write('world')
    test.tell()

with open('/tmp/test', 'r') as test:
    print(repr(test.read()))

rawDescription: If I truncate a file to zero in Python 3 do I also need to seek to position zero?


rawDescription: How to append the second return value, directly to a list, in Python

description: Append the second return value, directly to a list, in Python


rawDescription: Count occurrence of tuples with Python

description: Count occurrence of tuples with Python


code: log = open(logLocation).read()

rawDescription: Python Logging: Evaluate Time before adding a new entry


code:
import tkinter as tk

def populate(frame):
    '''Put in some fake data'''
    for row in range(100):
        tk.Label(frame, text="%s" % row, width=3, borderwidth="1",
                 relief="solid").grid(row=row, column=0)
        t="this is the second column for row %s" %row
        tk.Label(frame, text=t).grid(row=row, column=1)

def onFrameConfigure(canvas):
    '''Reset the scroll region to encompass the inner frame'''
    canvas.configure(scrollregion=canvas.bbox("all"))

root = tk.Tk()
canvas = tk.Canvas(root, borderwidth=0, background="#ffffff")
frame = tk.Frame(canvas, background="#ffffff")
vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)

vsb.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
canvas.create_window((4,4), window=frame, anchor="nw")

frame.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))

populate(frame)

root.mainloop()

rawDescription: Adding a scrollbar to a group of widgets in Tkinter


code:
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

STATIC_URL = '/static/'

# remove STATIC_ROOT

rawDescription: django how to include javascript in template

description: Django how to include javascript in template


code: [td.text for td in browser.find_elements_by_xpath("//tbody[@id='mrc_main_table']/tr/td")]

rawDescription: How can I make a list of elements Selenium?

description: Make a list of elements Selenium


rawDescription: Neighbourhood of Scipy Labels

description: Neighbourhood of Scipy Labels


code:
df.ndim

2

rawDescription: Benefits of panda's multiindex?

description: Benefits of panda's multiindex


code:
from datetime import datetime
import time
example = u'2013-10-20T00:41:32.000Z'
datetime.strptime(example, '%Y-%m-%dT%H:%M:%S.%fZ')
time.strptime(example, '%Y-%m-%dT%H:%M:%S.%fZ')

rawDescription: python convert datetime formatted string to seconds

description: Python convert datetime formatted string to seconds


code:
import numbers
df[df[['x','y']].applymap(lambda x: isinstance(x, numbers.Number)).all(1)]

rawDescription: find values of pandas columns that only has numbers

description: Find values of pandas columns that only has numbers


code:
class TokenRegisterForm(Form):

    username = StringField('Username',
        validators=[DataRequired(), Length(min=3, max=25)])

    password = PasswordField('Password',
        validators=[DataRequired(), Length(min=6, max=40)])

class RegisterForm(TokenRegister):

    email = StringField('Email',
        validators=[DataRequired(), Email(), Length(min=6, max=40)])

rawDescription: Displaying jinja2 form fields based on attribute value


code: scipy.optimize.brute(lambda x: (x if 1 <= x <= 100 else np.inf), (slice(1,100,1),))

rawDescription: Using scipy.optimize.brute: How I get the minimizer outside the specified range?


code:
from functools import partial
from operator import attrgetter

def treecomp(tree, funcs):
    '''Returns the composition of a tree of functions.'''
    symbtree = makesymbtree(tree, funcs)
    symbexp = makesymbexp(symbtree)
    return partial(evalsymbexp, symbexp)

FUNC_CALL = '{func}({{}})'

def makesymbtree(tree, funcs):
    '''Returns the symbolic expression of a tree composition.'''
    symbols = [FUNC_CALL.format(func=func.__name__) for func in funcs]
    symbtree = sorted((SymbNode(*x) for x in zip(tree, symbols)),
                      key=attrgetter('addr'))
    symbtree.sort(key=len)
    return symbtree

def makesymbexp(symbtree):
    root = symbtree[0]
    if len(symbtree) == 1: # symbtree is a leaf node
        return root.symb
    symbargs = [makesymbexp(subsymbtree(symbtree, root=node))
                for node in symbtree if root.begets(node)]
    return root.symb.format(','.join(symbargs))

def subsymbtree(symbtree, root):
    subsymbtree = [node for node in symbtree if root <= node]
    return subsymbtree

ARGS = 'args[{idx}]'

def evalsymbexp(symbexp, *args):
    '''Returns the evaluation of a symbolic expression on arguments.'''
    argnames = [ARGS.format(idx=str(n)) for n, _ in enumerate(args)]
    return eval(symbexp.format(*argnames))

rawDescription: Composition of a hierarchy of functions

description: Composition of a hierarchy of functions


rawDescription: I can't find the logic error in this bubble sort code


code:
for collision in collisions:
    print("Collision between {0[0]}^{0[1]} and key".format(collision))

rawDescription: Reducing the complexity of dictionary brute force in python


code:
result = {}
result[(a,b)] = yourCalculation(a,b)

rawDescription: Python datastructure with string for indexing


code:
message = {'isbn_number': 123, 'authorlist': ['foo', 'bar', 'baz']}
book = book_message_adaptor(message)
# Does the equivalent of:
# Book(isbn=ISBNNumber(message['isbn_number']),
#      authors=map(Author, message['author_list']))

rawDescription: What is the pythonic way to add type information to an object's attributes?


code:
def has23(nums):
    return 2 in nums or 3 in nums

rawDescription: Iteration over a list

description: Iteration over a list


code:
index = pandas.MultiIndex.from_product([
    ['school{0}'.format(n) for n in xrange(3)],
    ['class{0}'.format(n) for n in xrange(3)],
    ['student{0}'.format(n) for n in xrange(10)]
])
d = pandas.DataFrame({'course1': np.random.randint(0, 10, 90), 'course2': np.random.randint(0, 10, 90)},
                     index=index)

rawDescription: Mann–Whitney U test on Pandas dataframe

description: Mann–Whitney U test on Pandas dataframe


code:
banana
carrot
dragonfruit

rawDescription: Can I add a condition to a for loop?

description: Add a condition to a for loop


code:
import datetime as dt
today = dt.date.today()
time = dt.datetime.strptime('09:30', '%H:%M').time()
dt.datetime.combine(today, time)

rawDescription: Combining a parsed time with today's date in Python


rawDescription: Is this control structure a code smell?

description: Is this control structure a code smell


code:
class Sites(models.Model):
    name = models.CharField(max_length=75)
    link = models.CharField(max_length=150)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name

class PaymentProcessors(models.Model):
    name = models.CharField(max_length=75)
    sites = models.ManyToManyField('Sites', related_name='payment_processors')

    def __str__(self):
        return self.name

rawDescription: Update Table Relationship in Django Admin


rawDescription: Dict into Dict Python

description: Dict into Dict Python


code:
class Population(object):

    OCCUPATIONS = ('miners', 'workers', 'farmers', 'loggers')

    def __init__(self):
        self.miners = 1
        self.workers = 2
        self.farmers = 3
        self.loggers = 4

    def kill_random(self, n):
        for _ in range(n):
            choices = [attr for attr in self.OCCUPATIONS
                       for _ in range(getattr(self, attr))]
            occupation = random.choice(choices)
            setattr(self, occupation, getattr(self, occupation)-1)

rawDescription: accessing a variable reference with a list

description: Accessing a variable reference with a list


rawDescription: Converting a RGB color tuple to a six digit code, in Python


code:
# load the image
image = pygame.image.load("some_image.png")

# draw a yellow line on the image
pygame.draw.line(image, (255, 255, 0), (0, 0), (100, 100))

rawDescription: how to draw lines on a picture background in pygame

description: Draw lines on a picture background in pygame


code:
from sys import maxsize as INF

def indices(s: 'string with indices list') -> 'indices generator':
    for x in s.split(','):
        splitter = ':' if (':' in x) or (x[0] == '-') else '-'
        ix = x.split(splitter)
        start = int(ix[0]) if ix[0] is not '' else -INF
        if len(ix) == 1:
            stop = start + 1
        else:
            stop = int(ix[1]) if ix[1] is not '' else INF
        step = int(ix[2]) if len(ix) > 2 else 1
        for y in range(start, stop + (splitter == '-'), step):
            yield y

rawDescription: pythonic format for indices

description: Pythonic format for indices


code:
res = 250. #desired resolution (number of samples on sphere)
phi,theta = np.mgrid[0:np.pi:np.pi/res, 0:np.pi:np.pi/res]

x=np.cos(theta) * np.sin(phi)
y=np.sin(theta) * np.sin(phi)
z=np.cos(phi)

mlab.mesh(x,y,z,color=(1,1,1))

rawDescription: generating a hemispherical surface with triangular_mesh and representing a data( as value or as colors) at each vertex

description: Generating a hemispherical surface with triangular_mesh and representing a data( as value or as colors) at each vertex


rawDescription: Replicating GROUP_CONCAT for pandas.DataFrame


code:
import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]

rawDescription: How can I get all filename in different directories?

description: Get all filename in different directories


code:
def predicate(fruit_type, fruit_color, fruit_size):
    def _predicate(fruit):
        if not fruit_type == 'All' and not fruit_type == fruit[1][0]:
            return False
        if not fruit_color == 'All' and not fruit_color == fruit[1][1]:
            return False
        if not fruit_size == 'All' and not fruit_size == fruit[1][2]:
            return False
        return True
    return _predicate

query_type = 'All'
query_color = 'All'
query_size = 'All'
myfruits = {}
my_filtered_fruit = list(filter(predicate(query_type, query_color, query_size), myfruits.items()))

rawDescription: How to implement efficient filtering logic in Python?

description: Implement efficient filtering logic in Python


code:
import collections
grouped = collections.defaultdict(list)
for path, size in sizes:
    grouped[size].append(path)

grouped

rawDescription: How to check size of the files in a directory with python?

description: Check size of the files in a directory with python


rawDescription: Reading Text File From Webpage by Python3


code: ['When in the course', 'of human Events, it', 'becomes necessary for one', 'People to dissolve the', 'Political Bands which have', 'connected them with another,', 'and to assume among', 'the Powers of the', 'Earth, the separate and', 'equal Station to which']

rawDescription: Split a large string into multiple substrings containing 'n' number of words via python


rawDescription: Creating a multi-part MIME message with a binary component for an HTTP request in Python 3


code: masked[~masked.mask] = analyzed.ravel()

rawDescription: Python, looking to extract values from a masked array, then rebuild an array


code:
data.execute("SELECT path, filename FROM audio WHERE filename LIKE ?",
             ('%{}%'.format(keywrd),))
paths, results = zip(*data)

rawDescription: return two lists from a list comprehension -- performance

description: Return two lists from a list comprehension -- performance


code:
while True:
    with open('log.txt', 'a+b') as logfile:
        ping = subprocess.Popen(['ping', '-c1', '-w4', 'www.example.com'],
                                stdout=logfile)
        time.sleep(5)
        # Not strictly necessary, but it avoids signaling for no reason
        if ping.poll() is None:
            ping.kill()
        ping.wait()

rawDescription: Logging ping successes and failures in linux


rawDescription: Pandas count(distinct) equivalent

description: Pandas count(distinct) equivalent


code:
f = open('filename')
fileList = f.readlines()

rawDescription: Complex parsing query

description: Complex parsing query


code:
result = {}

for value, key in tuples:
    result.setdefault(key, []).append(value)

rawDescription: Python dictionary key assign

description: Python dictionary key assign


code:
def my_time_abbr(value):
    return value.replace( 'hours', 'Hr').replace('minutes','Min')

rawDescription: Django - Timeuntil Tag output abbreviation


code: form = waypointForm(user)

rawDescription: Creating a dynamic choice field

description: Creating a dynamic choice field


code:
import fileinput
import sys
from glob import glob

all_files = [f for files in sys.argv[1:] for f in glob(files)]

for line in fileinput.input(all_files):
     print(fileinput.filename(), fileinput.filelineno(), line)

rawDescription: How to pass wildcard argument like *.txt in windows cmd

description: Pass wildcard argument like *.txt in windows cmd


rawDescription: Argparse: how to distinguish between arguments for parsers and subparsers


rawDescription: pandas groupby count string occurrence over column

description: Pandas groupby count string occurrence over column


code: conds = ["_".join(i.split("_")[1:]) for i in df.index]

rawDescription: Improvement in pandas dataframe conversion in Python


code:
currency = input('What currency are you looking for? ')
match = root.find('.//ex:Cube[@currency="{}"]'.format(currency.upper()), namespaces=namespaces)
if match is not None:
    print('The rate for {} is {}'.format(currency, match.attrib['rate']))

rawDescription: How to parse XML file from European Central Bank with Python

description: Parse XML file from European Central Bank with Python


rawDescription: How to filter the string patterns to match in textlines with regex?

description: Filter the string patterns to match in textlines with regex


code:
chunkIt(range(10), 3)
chunkIt(range(11), 3)
chunkIt(range(12), 3)

rawDescription: splitting a list of arbitrary size into only roughly N-equal parts

description: Splitting a list of arbitrary size into only roughly N-equal parts


rawDescription: Extraction of common element from multiple arrays to make a new array


rawDescription: Pythonic way of percentagechance

description: Pythonic way of percentagechance


code:
def concat(self, digit):
    self.nums.append(digit)
    print(''.join(self.nums))

rawDescription: How can I execute more a command based on the Button that called it? (Classes and tkinter)

description: Execute more a command based on the Button that called it? (Classes and tkinter)


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

# make up some data
n = 100
dates = pd.date_range(start = "2015-01-01", periods = n, name = "yearDate")

dfs = []

for i in range(3):
    df = pd.DataFrame(data = np.random.random(n)*(i + 1), index = dates,
                      columns = ["FishEffort"] )
    df.df_name = str(i)
    dfs.append(df)

# plot it directly using matplotlib instead of through the DataFrame
fig = plt.figure()
ax = fig.add_subplot()

for df in dfs:
    plt.plot(df.index,df["FishEffort"], label = df.df_name)

plt.legend()
plt.show()

rawDescription: Date removed from x axis on overlaid plots matplotlib


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

x = np.linspace(0, 10, 100)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left')
plt.show()

rawDescription: How to adjust the size of matplotlib legend box?

description: Adjust the size of matplotlib legend box


code:
y_values = temp2[y_key]
for test_d, test_p in temp2.iteritems():
    if test_d == y_key:
        continue
    y_values.difference_update(test_p)

rawDescription: python: how to compare more than two keys in the same dictionary?

description: Python: how to compare more than two keys in the same dictionary


code:
args_str = "-k test_myfavorite"
py.test.cmdline.main(args_str.split(" "))

rawDescription: How to use py.test from Python?

description: Use py.test from Python


code:
from collections import defaultdict
user_to_count_map = defaultdict(lambda: 0)
for username in list_of_usernames:
    user_to_count_map[username] += 1

rawDescription: Using setdefault, but not wanting to reassign back to map/dict


rawDescription: Difference between logical line and physical line in python


rawDescription: Simultaneous Loops in Python

description: Simultaneous Loops in Python


rawDescription: string replacement in python

description: String replacement in python


code:
from Tkinter import *

root = Tk()

root.title("Exemption?")

root.geometry("400x200")

root["bg"] = "green"

a = StringVar()
b = StringVar()
c = StringVar()
d = StringVar()

int_a = 0
int_b = 0
int_c = 0
int_d = 0

def pn(int_a, int_b, int_c, int_d):
        print (720 - 2 * int_d - int_a - int_b - 2 * int_c ) / 2

def aWriter(*args):
    global int_a
    int_a = int(a.get())

def bWriter(*args):
    global int_b
    int_b = int(b.get())

def cWriter(*args):
    global int_c
    int_c = int(c.get())

def dWriter(*args):
    global int_d
    int_d = int(d.get())

a.trace("w", aWriter)
b.trace("w", bWriter)
c.trace("w", cWriter)
d.trace("w", dWriter)

label1 = Label(root, text = "Name:")

label2 = Label(root, text = "Subject:")

label3 = Label(root, text = "Average 1:", textvariable=a)

label4 = Label(root, text = "Average 2:", textvariable=b)

label5 = Label(root, text = "Average 3:", textvariable=c)

label6 = Label(root, text = "Average 4:", textvariable=d)

entry1 = Entry(root)

entry2 = Entry(root)

entry3 = Entry(root, textvariable=a)

entry4 = Entry(root, textvariable=b)

entry5 = Entry(root, textvariable=c)

entry6 = Entry(root, textvariable=d)

button = Button(root, text="Average needed", command=pn(int_a,int_b,int_c,int_d))

label1.grid(row=1,column=1)

label2.grid(row=2,column=1)

label3.grid(row=3,column=1)

label4.grid(row=4,column=1)

label5.grid(row=5,column=1)

label6.grid(row=6,column=1)

entry1.grid(row=1,column=2)

entry2.grid(row=2,column=2)

entry3.grid(row=3,column=2)

entry4.grid(row=4,column=2)

entry5.grid(row=5,column=2)

entry6.grid(row=6,column=2)

button.grid(row=7,column=2)

root.mainloop()

rawDescription: how to make an entry into a string, and then into an input so I can put 4 entries into a formula?

description: Make an entry into a string, and then into an input so I can put 4 entries into a formula


code: "".join(reversed([a[i:i+2] for i in range(0, len(a), 2)]))

rawDescription: Reverse a string in Python two characters at a time (Network byte order)


code: print(*(succeeded-failed), sep='\n')

rawDescription: Python: iterate over a list of list

description: Python: iterate over a list of list


code:
LoT=[('H', 'C', 'G'), ('H', 'M', 'G'), ('L', 'M', 'S')]
[['Col{}'.format(i) for i, t in enumerate(zip(*pair), 1) if t[0]!=t[1]] for pair
       in pairs(LoT)]

rawDescription: Element by element comparison in tuple to return set of sets - python


code:
a_list = [1, 2, 3]
a_list.__hash__ is None
hash(a_list)

rawDescription: A list as a key for PySpark's reduceByKey


code:
a_str = 'CGGACTCGACAGATGTGAAGAACGACAATGTGAAGACTCGACACGACAGAGTGAAGAGAAGAGGAAACATTGTAA'
b = 5      #length of substring
c = 50     #length of window
repeat = 4 #minimum number of repetitions

substrings = list({
    a_str[i:i+b]
    for i in range(len(a_str) - b)
    if a_str.count(a_str[i:i+b], i+b, i+c) >= repeat - 1
})
print(substrings)

rawDescription: Python:Comparing all list items to substring of string


rawDescription: Check if current thread is main thread, in Python


code:
import lxml.etree as ET

tree = ET.parse('VimKeys.xml')
root = tree.getroot()

newroot = ET.Element('root')
for i, child in enumerate(root):
    table = ET.Element('table')
    newroot.insert(i, table)
    caption = ET.Element('caption')
    caption.text = child.attrib['title']
    table.insert(0, caption)
    for j, c in enumerate(child, 1):
        tr = ET.Element('tr')
        table.insert(j, tr)
        th = ET.Element('th')
        th.text = c.text
        tr.insert(0, th)

        td = ET.Element('td')
        td.text = c.attrib['description']
        tr.insert(1, td)

print(ET.tostring(newroot, pretty_print=True))

rawDescription: preserve entity references when parsing xml

description: Preserve entity references when parsing xml


code:
with open(filename, 'a') as f:
    f.write('some text')

rawDescription: Printing a .txt File Python

description: Printing a .txt File Python


code:
self.processFile(root, file(os.path.join(root, f), "r"), age, inString)
self.processFile(root, file(os.path.abspath(f), "r+"), age, inString)

rawDescription: Mental block with os.walk - want to process a file not the filename string


code:
def getBusinesses():
    businessesQuery = ("SELECT * FROM business")
    businessRows = cursor.fetchall()

    businessObjects = []
    for businessRow in businessRows:
        menuQuery = ("SELECT * FROM menu WHERE business_id = %s" % businessRow[0])
        menuRows = cursor.fetchall()

        for menuIdx, menuRow in enumerate(menuRows):
            sectionQuery = ("SELECT * FROM menu_section WHERE menu_id = %s" % menuRow[0])
            cursor.execute(sectionQuery)
            sectionRows = cursor.fetchall()

            sectionObjects = []
            for sectionIdx, sectionRow in enumerate(sectionRows):
                itemQuery = ("SELECT * FROM menu_item WHERE section_id = %s" % sectionRow[0])
                itemRows = cursor.fetchall()

rawDescription: Data extraction and transform efficiency


rawDescription: Processing XML file with networkx in python


code:
name = input("Enter your name").rstrip() # make "foo" == "foo "
score = input("Enter your score")
with open("highscores.txt","a+") as f: # a+ will allow us to read and will also create the file if it does not exist
    scores_list = f.readlines()
     # if scores_list is empty this is our first run
    if not scores_list:
        f.write("{} {}\n".format(name, score))
    else:
        # else check for name and update score
        new_names = []
        for ind, line in enumerate(scores_list):
            # if name exists update name and score
            if name in line.split():
                scores_list[ind] = "{} {}\n".format(name, score)
                break # break so we don't add existing name to new names
        else:
            # else store new name and score
            new_names.append("{} {}\n".format(name, score))

        # all scores updated so open and overwrite
        with open("highscores.txt","w") as scores_file:
             scores_file.writelines(scores_list + new_names)

rawDescription: Updating a Python list based on a search append


code:
@hybrid_method
def other_user_id(self, user):
    if user.id == self.sender_id:
        return self.receiver_id
    elif user.id == self.receiver_id:
        return self.sender_id
    else:
        raise ValueError

rawDescription: How to control field name for related model fetching in Peewee?

description: Control field name for related model fetching in Peewee


code:
def g(x):
    return np.ones_like(x)*3

rawDescription: How to determine if numpy.vectorize() is needed?

description: Determine if numpy.vectorize() is needed


code:
import sklearn.cluster
import numpy as np

kmeans = sklearn.cluster.KMeans(n_clusters=4)
kmeans.fit_predict(numpy.array([123, 127, 99, 75, 86, 83, 81]).reshape(-1, 1))

rawDescription: Given a list of numbers, find a fix range that can cover the most numbers


code:
from itertools import islice
from random import randint

def random_chunk(li, min_chunk=1, max_chunk=3):
    it = iter(li)
    while True:
        nxt = list(islice(it,randint(min_chunk,max_chunk)))
        if nxt:
            yield nxt
        else:
            break

rawDescription: Best way to split a list into randomly sized chunks?

description: Split a list into randomly sized chunks


code:
f=Frac('2/3') + Frac('1/6') + Frac('1/10')
f
f.numerator
f.denominator
import decimal
decimal.Decimal(f.numerator) / decimal.Decimal(f.denominator)

rawDescription: Can I keep decimal precision while using integer division in Python?

description: Keep decimal precision while using integer division in Python


code:
import requests
from bs4 import BeautifulSoup
import time

# post url
js = "https://angel.co/company_filters/search_data"

# X-Requested-With is important
headers = {"X-Requested-With": "XMLHttpRequest",
           "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36"}

# get url
u = "https://angel.co/companies/startups?ids%5B%5D={}&total={}&page={}&sort=signal&new=false&hexdigest={}"

def get_next_pages(js, u, start_page=1):
    with requests.Session() as s:
        params = s.post(js, data={"sort": "signal","page":start_page}, headers=headers).json()
        companies = s.get(
            u.format("&ids%5B%5D=".join(map(str, params["ids"])), params["page"], params["total"], params["hexdigest"]),
            headers=headers)
        soup = BeautifulSoup(companies.json()["html"])
        comps = soup.select("div.company.column")
        yield comps
        while True:
            # increment page count from previous.
            page = params["page"] + 1
            params = s.post(js, data={"sort": "signal", "page": page}, headers=headers).json()
            # keep going until we have reached the maximum queries
            if "ids" not in params:
                break
            companies = s.get(u.format("&ids%5B%5D=".join(map(str, params["ids"])), params["page"], params["total"],
                                       params["hexdigest"]),
                              headers=headers)
            soup = BeautifulSoup(companies.json()["html"])
            comps = soup.select("div.company.column")
            # don't hammer with requests
            time.sleep(.3)
            yield comps

for comps in get_next_pages(js, u):
    print(comps)

rawDescription: unable to scrape

description: Unable to scrape