code:
import cv
blue = cv.LoadImage("blue.jpg")
red = cv.LoadImage("red.jpg")

sub = cv.GetSubRect(blue, (100, 100, 50, 50))
cv.Copy(red,sub)

cv.ShowImage('blue_red', blue)
cv.WaitKey(0)

rawDescription: IplImage inside IplImage

description: IplImage inside IplImage


code:
for line in LinesOfFile:
    indexN = filter(None, re.split("[ \!?:]+", line))

rawDescription: How to make filter regex not ignore minus sign in a line of text?

description: Make filter regex not ignore minus sign in a line of text


code: output = map(lambda x: int(x), output)

rawDescription: Python string to list conversion

description: Python string to list conversion


code:
class ThingManager(models.Manager):
    def get_queryset(self):
        return super(ThingManager, self).get_queryset().exclude(discarded=True)

rawDescription: Django: Using a deleted/discarded field en lieu of deleting a database row - What to do with related models?


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

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


code:
def eventFilter(self, tableView, event):
    if event.type() == QtCore.QEvent.KeyPress:
        key = event.key()
        if event.modifiers() in (QtCore.Qt.NoModifier, QtCore.Qt.KeypadModifier):
            if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
                self.menu.editItem.trigger()
                return True

rawDescription: Optimizing `in`

description: Optimizing `in`


code:
import numpy as np
import collections
import itertools as IT
import matplotlib.pyplot as plt
import timeit

def using_unique(x):
    y, inverse = np.unique(x, return_inverse=True)
    return np.column_stack((y, np.bincount(inverse)))

def using_counter(x):
    result = collections.Counter(x)
    return np.array(sorted(result.items()))

def using_ordered_dict(x):
    result = collections.OrderedDict()
    for item in x:
        result[item] = result.get(item,0)+1
    return np.array(result.items())

def using_groupby(x):
    return np.array([(k, sum(1 for i in g)) for k, g in IT.groupby(x)])

fig, ax = plt.subplots()
timing = collections.defaultdict(list)
Ns = [int(round(n)) for n in np.logspace(0, 3, 10)]
for n in Ns:
    x = np.random.random(n)
    x.sort()
    timing['unique'].append(
        timeit.timeit('m.using_unique(m.x)', 'import __main__ as m', number=1000))
    timing['counter'].append(
        timeit.timeit('m.using_counter(m.x)', 'import __main__ as m', number=1000))
    timing['ordered_dict'].append(
        timeit.timeit('m.using_ordered_dict(m.x)', 'import __main__ as m', number=1000))
    timing['groupby'].append(
        timeit.timeit('m.using_groupby(m.x)', 'import __main__ as m', number=1000))

ax.plot(Ns, timing['unique'], label='using_unique')
ax.plot(Ns, timing['counter'], label='using_counter')
ax.plot(Ns, timing['ordered_dict'], label='using_ordered_dict')
ax.plot(Ns, timing['groupby'], label='using_groupby')
plt.legend(loc='best')
plt.ylabel('milliseconds')
plt.xlabel('size of x')
plt.show()

rawDescription: Grouping repetitions in an array?

description: Grouping repetitions in an array


code:
class Player:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

rawDescription: What is a better way to define a class' __init__ method with optional keyword arguments?


code:
import matplotlib.pyplot as plt

x = [1, 2, 3]
y =[1, 2, 3]

fig, ax = plt.subplots()
ax.plot(x, y, linewidth=10, color='yellow')
ax.text(2, 2, 'label', ha='center', size=72, zorder=0)

# For the moment, hide everything else...
ax.axis('off')
fig.tight_layout()

plt.show()

rawDescription: Remove matplotlib text plot border

description: Remove matplotlib text plot border


code: data = ifile.readlines()

rawDescription: Trouble sorting a list with python

description: Trouble sorting a list with python


code:
label_string = "Test"
query = "CREATE (n:%s {name: {name})" % label_string
graph.cypher.execute(query, parameters={"name": "Bob"})

rawDescription: Multiple variables in cypher query (name, label) - py2neo


rawDescription: Using Numpy arrays as lookup tables

description: Using Numpy arrays as lookup tables


rawDescription: Printing a dictionary in python with n elements per line


code:
def fib():
    a, b = 0, 1
    while True:            # First iteration:
        yield a            # yield 0 to start with and then
        a, b = b, a + b    # a will now be 1, and b will also be 1, (0 + 1)

rawDescription: bottom up fibonacci in python using O(1) space

description: Bottom up fibonacci in python using O(1) space


code:
from random import shuffle, sample
list = range(100000)
shuffle(list)
sublist = sample(list, 20000)
set_sublist = set(sublist)

rawDescription: Efficient algorithm or python's built-in function to remove sublist from very large list


code:
ts = df.set_index('Date')
ts.resample('6M', ...)

rawDescription: Dataframe Wrangling with Dates and Periods in Pandas


rawDescription: Resizing and stretching a NumPy array

description: Resizing and stretching a NumPy array


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

rawDescription: Extracting key/value pair from dictionary


code:
iter = d.itervalues()
while True:
    try:
        x = next(iter)
        # loop body
    except StopIteration:
        break

rawDescription: Why does python's dictionary iteration seemingly work with a copy?


code: isinstance(o, (int, long, float, complex))

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

description: Determine that a Python object is numeric


code:
result = np.empty((3, 3), order='F') # Fortran-order, i.e. column-major
X.sum(0, out=result)

rawDescription: Numpy: transpose result of advanced indexing


code:
import re
re.VERBOSE
re.IGNORECASE
re.VERBOSE | re.IGNORECASE

rawDescription: Python Pipe Character for calling functions


code:
set1 = set([col[0] for col in data])
set2 = set([col[1] for col in data])
nodes = list(set1.union(set2))

rawDescription: Heat Map Python

description: Heat Map Python


code:
x = 'this has - a few - dashes - in it'
x.split('-', maxsplit=1)

rawDescription: Splitting information in a specific column python?


code:
from xml.sax import make_parser
from xml.sax.handler import ContentHandler
import sys

class Xml2PseudoJson(ContentHandler):

    def __init__(self):
        self.tags = []
        self.chars = []
        self.json = []

    def startElement(self, tag, attrs):
        d = {''.join(self.chars): self.tags[:]}
        self.json.append(d)
        self.tags.append(tag)
        self.chars = []

    def endElement(self, tag):
        d = {''.join(self.chars): self.tags[:]}
        self.chars = []
        self.tags.pop()
        self.json.append(d)

    def characters(self, content):
        self.chars.append(content)

    def endDocument(self):
        print(list(filter(lambda x: '' not in x, self.json)))

parser = make_parser()
handler = Xml2PseudoJson()
parser.setContentHandler(handler)
parser.parse(open(sys.argv[1]))

rawDescription: Parse HTML style text annotations to a list of dictionaries


code:
from datetime import datetime, timedelta
from dateutil import tz

AmericaNewYorkTz = tz.gettz('America/New_York')

def _to_datetime(air_date, air_time):
    schedule_time = '{}:{}'.format(air_date, air_time)
    return datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p').replace(tzinfo=AmericaNewYorkTz)

dt = _to_datetime('07/27/2015', '06:00 AM')
print('DateTime:', dt)
# DateTime: 2015-07-27 06:00:00-04:00

rawDescription: How to convert datetime string without timezone to another datetime with timezone in python?

description: Convert datetime string without timezone to another datetime with timezone in python


code:
for i in range(256):
    rgb = (i, i, i)

rawDescription: How to add each element of a tuple or list by a fixed value?

description: Add each element of a tuple or list by a fixed value


code:
# master.py

# List of plugins
plugins = []

# registration API called by plugin
import inspect
def register():
    frame = inspect.stack()[1]
    module = inspect.getmodule(frame[0])
    plugins.append(module)

# functional API called by application
def callout():
    for m in plugins:
        m.shout()

def dynamic_callout(s):
    for m in plugins:
        getattr(m, s[:2]+s[-3:])()

rawDescription: How can I call a function from inside an imported module, aka design issue

description: Call a function from inside an imported module, aka design issue


code:
str_list = filter(None, str_list) # fastest
str_list = filter(bool, str_list) # fastest
str_list = filter(len, str_list)  # a bit of slower
str_list = filter(lambda item: item, str_list) # slower than list comprehension

rawDescription: Remove empty strings from a list of strings


rawDescription: finding duplicates in a list of lists

description: Finding duplicates in a list of lists


rawDescription: What area deals with the extraction of words with similar characteristics?


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

rawDescription: Learn Python The Hard Way Exercise 21 Extra Credit


code:
[(a,b,c,d)
 for a in range(2)
 for b in range(2)
 if a+b <= 4
 for c in range(3)
 if a+b+c <= 4
 for d in [0,1,2,4]
 if a+b+c+d == 4]

rawDescription: Challenge: Creating a list of tuples of different combinations with different value 'options' in each location of the tuple.


code:
Book.objects.annotate(count=Count('author')).filter(author__id=1)\
                .filter(author__id=13).filter(count=2)

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

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


code:
def match(s1, s2):
    pos = -1

    for i, (c1, c2) in enumerate(zip(s1, s2)):
        if c1 != c2:
            if pos != -1:
                return -1
            else:
                pos = i

    return pos

rawDescription: Compare strings, allowing one character difference


code:
list(random_weighted_sample_no_replacements_inverse_weights(d, 3))
list(random_weighted_sample_no_replacements_inverse_weights(d, 3))
list(random_weighted_sample_no_replacements_inverse_weights(d, 3))
list(random_weighted_sample_no_replacements_inverse_weights(d, 3))
list(random_weighted_sample_no_replacements_inverse_weights(d, 3))
list(random_weighted_sample_no_replacements_inverse_weights(d, 3))
list(random_weighted_sample_no_replacements_inverse_weights(d, 3))

rawDescription: Random from Python Dict with lowest values as priority


code: (A[:,np.newaxis,:] + B).reshape(-1, 3)

rawDescription: Adding up all pairs of columns of two matrices


code:
import pprint

def my_safe_repr(object, context, maxlevels, level):
    typ = pprint._type(object)
    if typ is unicode:
        object = str(object)
    return pprint._safe_repr(object, context, maxlevels, level)

printer = pprint.PrettyPrinter()
printer.format = my_safe_repr
printer.pprint({u'foo': u'bar', u'baz': [u'apple', u'orange', u'pear', u'guava', u'banana'], u'hello': u'world'})

rawDescription: Suppress unicode prefix on strings when using pprint


code:
from collections import Counter
my_list=[['a','b','c','d'],['a','b','z','d'],['a','c','f','e'],['d','w','f','a']]
Counter(x for sublist in my_list for x in sublist)
Counter(sublist[0] for sublist in my_list)

rawDescription: counting element occurences in nested lists

description: Counting element occurences in nested lists


code:
# This example should work in any version of Python.
# urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 }
urls_d = {}
for url in list_of_urls:
    if not url in urls_d:
        urls_d[url] = 1
    else:
        urls_d[url] += 1

rawDescription: Python : List of dict, if exists increment a dict value, if not append a new dict


code:
bar_flags = wx.SizerFlags().Expand().Border(wx.ALL, 1).Proportion(0)
box_flags = wx.SizerFlags().Expand().Border(wx.ALL, 1).Proportion(1)

main_box.Add(tool_status_bars.main, bar_flags)
main_box.Add(wrap_panels_box, box_flags)
main_box.Add(tool_status_bars.panel_view, bar_flags)
main_box.Add(tool_status_bars.status, bar_flags)

rawDescription: How to layout wxPython panels that expand both directions

description: Layout wxPython panels that expand both directions


code: print("I a {0} find {1} {2} {2} {2} {2} useful".format(name, site, 'very'))

rawDescription: Use same variable multiple times in print


rawDescription: Table tennis simulator

description: Table tennis simulator


rawDescription: configparser: parsing error with ommited values

description: Configparser: parsing error with ommited values


rawDescription: fastest way to find the magnitude (length) squared of a vector field

description: Fastest way to find the magnitude (length) squared of a vector field


code: l3 = [[sum(i*j) for j in l2] for i in l1]

rawDescription: Iterating over two lists and resulting in a third one


code:
    #p6 states
    #reads text file from the web
state_list=[]
import urllib.request

def read_file(url):
    """ reads the url and returns a unicode txt file"""
    with urllib.request.urlopen(url) as webpage: #opens the webpage
        for line in webpage:
            line= line.strip()
            line= line.decode('utf-8')#unicode
            if line [0] != "#":
                item_list =line.split(',')#splits list at comma
                state= item_list[0].lower()
                capital = item_list[1].lower()
                area=int(item_list[2])
                pop= float(item_list[3])
                state_list.append([state, capital, area, pop])
                #print(state_list)
    return state_list
        #end if
    #end for
#end with
#----------------------------------------------------------------
def find_starts_with(start_letters, state_list):
    """ searches  text file to find a state beginning with the letters     entered"""
    print()
    found= False
    n_to_match=len(state_to_find)
    total_pop = 0
    total_area = 0
    for item_list in state_list:
        state= item_list[0].lower()
        if state_to_find == state[0:n_to_match]:

            total_pop = 0.0
            total_area = 0
        if state_to_find == state[0:n_to_match]:
            print_state=state.title()
            capital = item_list[1]
            print_capital = capital.title()
            area = int(item_list[2])
            print_area = format(area, '10,d') # 10 spaces, show commas
            pop = float(item_list[3])
            print_pop = format(pop, '10,.1f')
            found= True
            total_pop += pop
            total_area += area
            print(print_state, "capital: ", print_capital, "\n",
                  print_area, "sq km\n   ",
                  print_pop, "million people\n")
    #print("total area", total_area, "Total population ", total_pop)

    if not found:
        print("don't you know how to spell your states correctly? ")
    return total_pop,total_area

#-----------------------------------------------------------------------

#-----------------------------------------------------------------------
url = "http://www.cs.uoregon.edu/classes/15F/cis122/data/state_data.txt"
state_list= read_file(url)

request=input("type the first few letters of a states name or type q to quit ")
while request != 'q':
    state_to_find=request
    state_to_find= state_to_find. lower()
    total_pop,total_area=find_starts_with(state_to_find, state_list)
    print ("total area: ", total_area, "\n Total population: ", total_pop)
    request= input("type the first few letters of a states name or type q to quit ")

if request=='q':
    print("have a nice day")

rawDescription: adding population from a website

description: Adding population from a website


code:
def get(self):
    if self.request.path == '/foo':
        # here i write something out
        # but you would serve a template
        self.response.write('urlpath is /foo')
    elif self.request.path == '/bar':
        self.response.write('urlpath is /bar')
    else:
        self.response.write('urlpath is %s' %self.request.path)

rawDescription: google app engine (python27) fetch request url

description: Google app engine (python27) fetch request url


rawDescription: can't get the objects of foreign keys of django models also my design is probably bad

description: Can't get the objects of foreign keys of django models also my design is probably bad


rawDescription: Switching between Anaconda and Anaconda3


code:
codes = [  1020301.,  10050002.]
number_of_cols = max(ceil(math.log(v, 100)) for v in codes)
print(number_of_cols)
print(decode_with_strings(codes))
print(decode_direct(codes))

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


code:
from sklearn.feature_extraction.text import TfidfVectorizer

train_data = [["the","sun","is","bright"],["blue","is","the","sky"]]

tfidf = TfidfVectorizer(tokenizer=lambda i:i, lowercase=False)
result_train = tfidf.fit_transform(train_data)

rawDescription: TFIDF with previously preprocessed data

description: TFIDF with previously preprocessed data


rawDescription: How to decrypt unsalted openssl compatible blowfish CBC/PKCS5Padding password in python?

description: Decrypt unsalted openssl compatible blowfish CBC/PKCS5Padding password in python


code:
SpecialClass = ClassFactory("SpecialClass", "a b c".split())
s = SpecialClass(a=2)
s.a
s2 = SpecialClass(d=3)

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

description: Dynamically create derived classes from a base class


code:
array = [['X', 'Y', 'Z'], [Decimal('1'), Decimal('2'), Decimal('3')]]
return render_to_response('page2.html', {
    'array': json.dumps(array, cls=DecimalEncoder),
})

rawDescription: Passing data to Google Charts with Django


code:
frame.canvas = canvas
frame.ax = a

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

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


code:
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from django.utils.timezone import now

class UserSerializer(serializers.HyperlinkedModelSerializer):
    hours_since_joined = serializers.SerializerMethodField()
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups', 'hours_since_joined', 'first_name', 'last_name', 'get_full_name' )

    def get_hours_since_joined(self, obj):
        return (now() - obj.date_joined).total_seconds() // 3600

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name', 'user_set')

rawDescription: Django rest framework: serializers.ReadOnlyField() doesn't display field in browsable api


code: links = browser.find_elements_by_xpath("//a[contains(@href, 'jam') or contains(@href, 'honey') or contains(@href, 'choc')]")

rawDescription: Python SeleniumExtract href containing specific strings


rawDescription: "Best" pythonic way to retreive an item from a list based on two criteria


code:
with open(urlFile) as f:
  for line in f:
    doAction(line)

rawDescription: Python 3 - Reading line by line from a textfile and doing action for each line


code:
# new.py
#!/usr/bin/python
import subprocess

subprocess.Popen(["./old.py"])
print(2+2)

rawDescription: How to execfile an independent .py and continue on to next line of code in the original .py?

description: Execfile an independent .py and continue on to next line of code in the original .py


rawDescription: Array indexing by array-value and array-value dependant operation


code:
"""
MySQLdb session module for CherryPy by Ken Kinder <http://kenkinder.com/>

Version 0.3, Released June 24, 2000.

Copyright (c) 2008-2009, Ken Kinder
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

    * Neither the name of the Ken Kinder nor the names of its contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import MySQLdb
import cPickle as pickle
import cherrypy
import logging
import threading

__version__ = '0.2'

logger = logging.getLogger('Session')

class MySQLSession(cherrypy.lib.sessions.Session):
    ##
    ## These can be over-ridden by config file
    table_name = 'web_session'
    connect_arguments = {}

    SCHEMA = """create table if not exists %s (
            id varchar(40),
            data text,
            expiration_time timestamp
        ) ENGINE=InnoDB;"""

    _database = None

    def __init__(self, id=None, **kwargs):
        logger.debug('Initializing MySQLSession with %r' % kwargs)
        for k, v in kwargs.items():
            setattr(MySQLSession, k, v)

        self.db = self.get_db()
        self.cursor = self.db.cursor()

        super(MySQLSession, self).__init__(id, **kwargs)

    @classmethod
    def get_db(cls):
        ##
        ## Use thread-local connections
        local = threading.local()
        if hasattr(local, 'db'):
            return local.db
        else:
            logger.debug("Connecting to %r" % cls.connect_arguments)
            db = MySQLdb.connect(**cls.connect_arguments)
            cursor = db.cursor()
            cursor.execute(cls.SCHEMA % cls.table_name)
            db.commit()
            local.db = db

            return db

    def _load(self):
        logger.debug('_load %r' % self)
        # Select session data from table
        self.cursor.execute('select data, expiration_time from %s '
                            'where id = %%s' % MySQLSession.table_name, (self.id,))
        row = self.cursor.fetchone()
        if row:
            (pickled_data, expiration_time) = row
            data = pickle.loads(pickled_data)

            return data, expiration_time
        else:
            return None

    def _save(self, expiration_time):
        logger.debug('_save %r' % self)
        pickled_data = pickle.dumps(self._data)

        self.cursor.execute('select count(*) from %s where id = %%s and expiration_time > now()' % MySQLSession.table_name, (self.id,))
        (count,) = self.cursor.fetchone()
        if count:
            self.cursor.execute('update %s set data = %%s, '
                                'expiration_time = %%s where id = %%s' % MySQLSession.table_name,
                                (pickled_data, expiration_time, self.id))
        else:
            self.cursor.execute('insert into %s (data, expiration_time, id) values (%%s, %%s, %%s)' % MySQLSession.table_name,
                                (pickled_data, expiration_time, self.id))
        self.db.commit()

    def acquire_lock(self):
        logger.debug('acquire_lock %r' % self)
        self.locked = True
        self.cursor.execute('select id from %s where id = %%s for update' % MySQLSession.table_name,
                            (self.id,))
        self.db.commit()

    def release_lock(self):
        logger.debug('release_lock %r' % self)
        self.locked = False
        self.db.commit()

    def clean_up(self):
        logger.debug('clean_up %r' % self)
        self.cursor.execute('delete from %s where expiration_time < now()' % MySQLSession.table_name)
        self.db.commit()

    def _delete(self):
        logger.debug('_delete %r' % self)
        self.cursor.execute('delete from %s where id=%%s' % MySQLSession.table_name, (self.id,))
        self.db.commit()

    def _exists(self):
        # Select session data from table
        self.cursor.execute('select count(*) from %s '
                            'where id = %%s and expiration_time > now()' % MySQLSession.table_name, (self.id,))
        (count,) = self.cursor.fetchone()
        logger.debug('_exists %r (%r)' % (self, bool(count)))
        return bool(count)

    def __del__(self):
        logger.debug('__del__ %r' % self)
        self.db.commit()
        self.db.close()
        self.db = None

    def __repr__(self):
        return '<MySQLSession %r>' % (self.id,)

cherrypy.lib.sessions.MysqlSession = MySQLSession

rawDescription: CherryPy Sessions and large objects?

description: CherryPy Sessions and large objects


code:
#!/usr/local/bin/python3
# -*- coding: utf8 -*-

import struct

SOURCE_IP = "fe80000000000000020086fffe0580da"
DEST_IP = "fe80000000000000026097fffe0769ea"
TYPE_CODE = "8700"
REMAINDER = "00000000fe80000000000000026097fffe0769ea01010000860580da"

def calc_checksum(packet):
    total = 0

    # Add up 16-bit words
    num_words = len(packet) // 2
    for chunk in struct.unpack("!%sH" % num_words, packet[0:num_words*2]):
        total += chunk

    # Add any left over byte
    if len(packet) % 2:
        total += ord(packet[-1]) << 8

    # Fold 32-bits into 16-bits
    total = (total >> 16) + (total & 0xffff)
    total += total >> 16
    return (~total + 0x10000 & 0xffff)

def build_pseudo_header(src_ip, dest_ip, payload_len):
    source_ip_bytes = bytearray.fromhex(src_ip)
    dest_ip_bytes = bytearray.fromhex(dest_ip)
    next_header = struct.pack(">I", 58)
    upper_layer_len = struct.pack(">I", payload_len)
    return source_ip_bytes + dest_ip_bytes + upper_layer_len + next_header

def build_icmpv6_chunk(type_and_code, other):
    type_code_bytes = bytearray.fromhex(type_and_code)
    checksum = struct.pack(">I", 0)
    other_bytes = bytearray.fromhex(other)
    return type_code_bytes + checksum + other_bytes

def main():
    icmpv6_chunk = build_icmpv6_chunk(TYPE_CODE, REMAINDER)
    pseudo_header = build_pseudo_header(SOURCE_IP, DEST_IP, 32)
    icmpv6_packet = pseudo_header + icmpv6_chunk
    checksum = calc_checksum(icmpv6_packet)

    print("checksum: {:#x}".format(checksum))

if __name__ == '__main__':
    main()

rawDescription: Computing 16-bit checksum of ICMPv6 header


code: df.xs("x", 1, level=1)

rawDescription: Selecting a subset of columns from a dataframe using multi index


rawDescription: Truncating ints without rounding?

description: Truncating ints without rounding


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

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


code: E = np.diff(C, axis = -1)

rawDescription: In place difference between elements of a Numpy array


code: np.nonzero(np.any(a != 0, axis=0))[0]

rawDescription: Find Indices Of Columns Having Some Nonzero Element In A 2d array


code:
def numpy_there(A,val):
    return np.in1d(np.arange(val),A)

rawDescription: Is there a numpy.there?

description: Is there a numpy.there


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

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

# load data in clean_users from csv (shelve use same syntax than
# hashmap). Note: the timestamp must be a string

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

# for each iteration (not time related as previous version)
# could also stop when there is no new infected users in the iteration
for iteration in range(1, N):

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

    # get timestamp from infected_users
    for an_infected_timestamp in infected_users.keys():

        # get infected users for this time stamp
        current_infected_users = infected_users[an_infected_timestamp]

        # get relevant timestamp from clean users
        for a_clean_timestamp in clean_users.keys():
            if time_stamp_in_delta(an_infected_timestamp, a_clean_timestamp):

                # get clean users for this clean time stamp
                current_clean_users = clean_users[a_clean_timestamp]

                # compute infected users from current_clean_users and
                # current_infected_users then append the result to
                # new_infected_users

        # remove user in new_infected_users from clean_users

        # add user in new_infected_users to infected_users

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

rawDescription: Contact Tracing in Python - working with timeseries


code:
# in mod_scanPfiles.main:
p = subprocess.Popen(...)
p.wait() # wait until the process completes.

rawDescription: wait till other python script ends

description: Wait till other python script ends


rawDescription: Pandas: Y Axis consistency across graphs


code:
df
df['hb'] - 5

rawDescription: How can i substract a single value from a column using pandas and python

description: Substract a single value from a column using pandas and python


code:
target = pd.DataFrame(0, index=df.index, columns=range(1,13))
dm = pd.get_dummies(df.index.month).set_index(df.index)
target = (target + dm).fillna(0)
target.columns = ['is'+x.capitalize() for x in pd.datetools.MONTHS]
pd.concat([df, target], axis=1)

rawDescription: Pandas Dataframe - How To Convert Date to Boolean Columns?


code:
class PersonAdmin(admin.ModelAdmin):
    list_display = ('upper_case_name',)

    def upper_case_name(self, obj):
        return ("%s %s" % (obj.first_name, obj.last_name)).upper()
    upper_case_name.short_description = 'Name'

rawDescription: How to see how many relations a Django model has in admin?

description: See how many relations a Django model has in admin


code:
#setup to recieve analog data
it = util.iterator(board)
it.start()
board.analog[0].enable_reporting()
# later to read
board.analog[0].read()

rawDescription: Raspberry Pi analog read

description: Raspberry Pi analog read


code:
#!/usr/bin/env python3
# coding: utf-8

import pandas as pd

# define DataFrame using same sample data
d = {'i': [1, 2, 3, 4, 5, 6, 1, 4, 9, 10 ], 'j': [4, 12, 13, 1 ,15, 16, 4, 1, 19, 20]}
df = pd.DataFrame(data=d)

# print sample DataFrame
print(df)

# print DataFrame with dropped duplicate rows
print(df.drop_duplicates())

# print DataFrame containing `True` for each duplicate row, see doc for further options
print(df.duplicated())

rawDescription: New column showing number of occurrences of unique rows


code:
from collections import Counter
lis = ['Name', 'Allen Doe', 'Jane Doe', 'Larry Hackman']
Counter(y[-1][1] for y in (x.rsplit(None, 1) for x in lis) if len(y)>1)

rawDescription: How to get frequency of specific character in a list?

description: Get frequency of specific character in a list


code:
def start(root):
    startframe = tkinter.Frame(root)
    canvas = tkinter.Canvas(startframe,width=1280,height=720)

    startframe.pack()
    canvas.pack()

    # Escape / raw string literal
    one = tkinter.PhotoImage(file=r'images\one.gif')
    root.one = one  # to prevent the image garbage collected.
    canvas.create_image((0,0), image=one, anchor='nw')

rawDescription: tkinter canvas image not displaying

description: Tkinter canvas image not displaying


code: from __future__ import print_function

rawDescription: Removing Stop words from NLTK

description: Removing Stop words from NLTK


code: {s: getattr(obj, s, None) for s in obj.__slots__}

rawDescription: How can I convert python class with slots to dictionary?

description: Convert python class with slots to dictionary


code:
# Python 2.6
print("{0}, {1}, {2}").format(foo, bar, baz)

# Python 2.7/3.1+
print("{}, {}, {}").format(foo, bar, baz)

rawDescription: Unpythonic way of printing variables in Python?


code:
df['Rolled'] = df.RollBasis.apply(f)
df

rawDescription: pandas rolling computation with window based on values instead of counts

description: Pandas rolling computation with window based on values instead of counts


code:
units = {
    'nm': 1,
    'mm': 10**6,
    'cm': 10**7,
    'm': 10**9
}

unit = input('Unit? ')

if unit in units:
    wave *= units[unit]
else:
    print('Invalid Unit! Valid units are: ' + ', '.join(units))
    frequency()

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


code:
def inplace_map(items, func):
    for i, item in enumerate(items):
        items[i] = func(item)

rawDescription: How to replace an object in python

description: Replace an object in python


code:
lestring = "Text123"
lelist = ["Text", "foo", "bar"]
[e for e in lelist if e in lestring]

rawDescription: Python - Fastest way to check if a string contains specific characters in any of the items in a list


code:
from matplotlib import pyplot as plt
import pandas as pd
from pandas import Series
import numpy as np
n = 50
x = pd.period_range('2001-01-01', periods=n, freq='M')
y1 = (Series(np.random.randn(n)) + 5).tolist()
y2 = (Series(np.random.randn(n))).tolist()
df = pd.DataFrame({'bar':y2, 'line':y1}, index=x)

# let's plot
plt.figure(figsize=(20, 4))
ax1 = df['bar'].plot(kind='bar', label='bar')
ax2 = ax1.twiny()
df['line'].plot(kind='line', label='line', ax=ax2)
ax2.grid(color="red", axis="x")

def align_xaxis(ax2, ax1, x1, x2):
    "maps xlim of ax2 to x1 and x2 in ax1"
    (x1, _), (x2, _) = ax2.transData.inverted().transform(ax1.transData.transform([[x1, 0], [x2, 0]]))
    xs, xe = ax2.get_xlim()
    k, b = np.polyfit([x1, x2], [xs, xe], 1)
    ax2.set_xlim(xs*k+b, xe*k+b)

align_xaxis(ax2, ax1, 0, n-1)

rawDescription: Multiple plots on same figure with DataFrame.Plot


code:
def matches_pattern(s, patterns):
    return re.match('|'.join('(?:%s)' % p for p in patterns), s)

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


code:
from glob import glob

files = glob('./*/*.csv')

rawDescription: Grab one specific column from multiple csv files and merge into one


code:
urlfinder = re.compile('^(http:\/\/\S+)')
urlfinder2 = re.compile('\s(http:\/\/\S+)')
@register.filter('urlify_markdown')
def urlify_markdown(value):
    value = urlfinder.sub(r'<\1>', value)
    return urlfinder2.sub(r' <\1>', value)

rawDescription: How do I get python-markdown to additionally "urlify" links when formatting plain text?

description: Get python-markdown to additionally "urlify" links when formatting plain text


code:
SERVICES = "FTP Download", "FTP Upload", "HTTP"
received = {k: {'MS1': []} for k in SERVICES}
received
received["HTTP"]["MS1"].append(17)
received

rawDescription: dict.fromkeys method in Python 3.2

description: Dict.fromkeys method in Python 3.2


rawDescription: backward slash followed by a number in python strings

description: Backward slash followed by a number in python strings


rawDescription: NumPy: Pretty print tabular data

description: NumPy: Pretty print tabular data


code:
a = list()
item = 1
a.extend((item,item))

rawDescription: Overriding list method

description: Overriding list method


code:
from xml.etree import ElementTree

tree = ElementTree.parse('products.xml')
root = tree.getroot()
product_elements = root.findall('product')

rawDescription: Python : How to pass XML element as an argument


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

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


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


code:
# If you have the A entity from somewhere and want to find B.
b = B.query(ancestor=entity_a.key).get()

# You have the B entity from somewhere and want to find A.
a = entity_b.key.parent().get()

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

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


code:
import pickle
with open('data.p', 'wb') as out:
    pickle.dump(users, out)

rawDescription: Python extend matrix

description: Python extend matrix


code: [x for x in re.split(r'(.*?\s.*?\s.*?)\s', "a bb c dd ee f") if x]

rawDescription: Split a string on every third space

description: Split a string on every third space


code:
df = DataFrame(randn(10, 3), columns=list('abc'))
values = df.values
columns = df.columns.values

with open('csv.csv', 'w') as f:
    savetxt(f, columns[newaxis], fmt='%10s')
    savetxt(f, values, fmt='%10.4f')

rawDescription: Printing to CSV file with automatic width


code:
def row(seq):
    result = []
    for i in range(1, len(seq)):
        diff = abs(sum(seq[:i]) - sum(seq[i:]))
        result.append((diff, i))

    i = min(result)[1]
    return seq[:i], seq[i:]

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

description: Make a general coding from my function


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

rawDescription: Webassets - exclude file in bundle

description: Webassets - exclude file in bundle


code:
myFile = open('/tmp/result.file', 'w') # or 'a' to add text instead of truncate
myFile.write('whatever')
myFile.close()

rawDescription: Python: Echoing to a File (like Bash)

description: Python: Echoing to a File (like Bash)


code:
df = df.set_index('concatenated')
df

rawDescription: Concatenate Columns as Index in Pandas

description: Concatenate Columns as Index in Pandas


code:
employees_on_projects = [project.employee_set.values() for project in projects]
tasks_in_projects = [project.task_set.values() for project in projects]

rawDescription: Selecting all columns from related model with django queryset


code:
good = 'hello'
bad = '\033[41mRED'

print('{!r}'.format(good))
print('{!r}'.format(bad))

rawDescription: Prevent terminal character set switch on data printing


code:
content += '%s %s  %s' % tuple(itertools.chain((item.slug,),
           str(item.title).ljust(25).split(" ", 1), (item.date.ljust(10),)))

rawDescription: Python Not Web Linking Entire variable in str.ljust


code:
token = 'foo'
chunks = []
current_chunk = []

for line in open('sample_csv.csv'):
   if line.startswith(token) and current_chunk:
      # if line starts with token and the current chunk is not empty
      chunks.append(current_chunk[:]) #  add not empty chunk to chunks
      current_chunk = [] #  make current chunk blank
   # just append a line to the current chunk on each iteration
   current_chunk.append(line)

chunks.append(current_chunk)  #  append the last chunk outside the loop

rawDescription: Python:How to split file into chunks by the occurrence of the header word


code:
first_set = set(map(tuple, first_list))
secnd_set = set(map(tuple, secnd_list))

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

description: Compare a list of lists/sets in python


code:
for i in range(xbox, xbox+3):
    for j in range(ybox, ybox+3):
        if val == sud[i][j]:                    ### check box for val
            return 1

rawDescription: Passing matrix in recursive sudoku solver


code:
user = UserProfile.objects.get(user=request.user)
user.check_updates()

rawDescription: Properly Defining Relationships in Django DB


code:
claw = map(lambda x: 'Fizzbuzz' if x % 15 == 0 else 'Fizz' if x % 3 == 0 else 'Buzz' if x % 5 == 0 else x, alist)
claw

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


code:
In : g.has_edge("Alice","Pencil","1/1/12")
Out: False

In : g.has_edge("Alice","Pencil","1/2/12")
Out: True

rawDescription: What is the correct graph data structure to differentiate between nodes with the same name?


code:
class Test2:
    var = 0

    @classmethod
    def method(cls):
        cls.var = 1

test2 = Test2()
test2.method()
print(test2.var)

rawDescription: python: imported module is in a different context

description: Python: imported module is in a different context


code:
from scrapy.conf import settings
from scrapy.contrib.exporter import CsvItemExporter

class CsvOptionRespectingItemExporter(CsvItemExporter):

    def __init__(self, *args, **kwargs):
        delimiter = settings.get('CSV_DELIMITER', ',')
        kwargs['delimiter'] = delimiter
        super(CsvOptionRespectingItemExporter, self).__init__(*args, **kwargs)

rawDescription: Modifiying CSV export in scrapy

description: Modifiying CSV export in scrapy


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


code:
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8

rawDescription: character encoding differences between local, Dev, and Prod env causing a roadblock

description: Character encoding differences between local, Dev, and Prod env causing a roadblock


code:
import ast

class ImportNodeVisitor(ast.NodeVisitor):
    def visit_Import(self, node):
        print(ast.dump(node))
        self.generic_visit(node)

    def visit_ImportFrom(self, node):
        print(ast.dump(node))
        self.generic_visit(node)

with open(sourcefilename) as sf:
    tree = ast.parse(sf.read(), sourcefilename)
    ImportNodeVisitor().visit(tree)

rawDescription: How to tell which modules have been imported in some source code?

description: Tell which modules have been imported in some source code


code:
arg_dict = lambda l, d=locals(): dict((k, d[k]) for k in l.split(', '))
f(**arg_dict('a, b, c, d, e'))

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


code:
file = open('1qib.pdb', 'r')
file2 = open('new.pdb', 'w')

for i, line in enumerate(file):
    spl = line.split() #1
    spl[4] = spl[4].replace("A", "B") #2
    newline = " ".join(spl) #3
    file2.write(newline) #4

file.close()
file2.close()

rawDescription: Replacing strings in specific positions into a text and then rewriting all the text


code: os.system('open "%s"' % foldername)

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


code:
entry_points = {
    'console_scripts': [
        'pelican = pelican:main',
        'pelican-import = pelican.tools.pelican_import:main',
        'pelican-quickstart = pelican.tools.pelican_quickstart:main',
        'pelican-themes = pelican.tools.pelican_themes:main'
    ]
}

rawDescription: which is pelican executable script that user executes from shell?

description: Which is pelican executable script that user executes from shell


code:
import random
def shuffle_n(s, n):
  idx = range(len(s))
  random.shuffle(idx)
  idx = idx[:n]
  mapping = dict((idx[i], idx[i-1]) for i in range(n))
  return ''.join(s[mapping.get(x,x)] for x in range(len(s)))

rawDescription: How to make a random but partial shuffle in Python?

description: Make a random but partial shuffle in Python


code:
while True: #really you should set some sort of a timeout here.
   r = tn.read_some()
   if any(x in r for x in ["#", ">"]):
       break

rawDescription: Python Telnetlib read_until '#' or '>', mutiple string determination?


rawDescription: Python: Pandas, Dataframe, Convert 1column data into 2D data format


code:
class Project(models.Model):
    ...

    @property
    def sumTaskAmounts(self):
        return self.tasks.aggregate(amount=Sum('amount')).amount

rawDescription: django parent child summation in view and pass to a template

description: Django parent child summation in view and pass to a template


code:
def random_function(*args):
    n = sum(args)
    bottom = 0
    for m in args:
            for _ in range(m):
                    yield random.uniform(bottom, bottom + m/n)
            bottom += m/n
list(random_function(6,3,1))
list(random_function(6,3,1))

rawDescription: How to generate highly uniform random number in python?

description: Generate highly uniform random number in python


code:
globalcoordinate = Vector((x, y, z))
localcoordinateforobject = (globalcoordinate - object.location) * object.matrix_world.inverted()

rawDescription: cannot get ray_cast in blender to work

description: Cannot get ray_cast in blender to work


code: print('\n'.join(map(' '.join, itertools.product(list1, list2, list3))))

rawDescription: how do I concatenate 3 lists using a list comprehension?

description: Concatenate 3 lists using a list comprehension


code: object.__getattr__(self, name)

rawDescription: __getattr__ throwing maximum recursion error when __setattr__ implemented


code:
class LatestMixin(object):
    """A mixin for db.Model objects that will add a `latest` method to the
    `Query` object returned by cls.all(). Requires that the ORDER_FIELD
    contain the name of the field by which to order the query to determine the
    latest object."""

    # What field do we order by?
    ORDER_FIELD = None

    @classmethod
    def all(cls):
        # Get the real query
        q = super(LatestMixin, cls).all()
        # Define our custom latest method
        def latest():
            if cls.ORDER_FIELD is None:
                raise ValueError('ORDER_FIELD must be defined')
            return q.order('-' + cls.ORDER_FIELD).get()
        # Attach it to the query
        q.latest = latest
        return q

# How to use it
class Foo(LatestMixin, db.Model):
    ORDER_FIELD = 'timestamp'
    timestamp = db.DateTimeProperty(auto_now_add=True)

latest = Foo.all().latest()

rawDescription: Equivalent of objects.latest() in App Engine


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

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

fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
cnt = ax.contour(data)
ax.clabel(cnt)
ax.axis('off')

plt.show()

rawDescription: Completely removing axes from contour plot


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

description: Cut a substring from a formated string in python


rawDescription: Formatting numbers consistently in Python


code: data = {k:v[0] for (k,v) in data.items()}

rawDescription: LDAP Python query and converting the appropriate dictionary


code:
category_dispatch = {}
for cat, dispatch in reversed(categories):
    category_dispatch.update(dict.fromkeys(cat.keys(), dispatch))

rawDescription: Best practices for Python if-elif-elif-elif when dispatching requests


rawDescription: Extracting Groups

description: Extracting Groups


code:
List1 = ["apple","peach","grapes","berries"]
List2 = [98,7,47,33]
List1 = [x[1] for x in sorted(zip(List2, List1))]
List2.sort()
List2.append(200)
DictFinal = dict((key, List2[i:i+2]) for i, key in enumerate(List1))
DictFinal

rawDescription: Python - Dictionary with Lists and tuples


code:
li=st2.split()
n=2
[(s, s in st1) for s in (' '.join(li[i:i+n]) for i in range(len(li)-n+1))]

rawDescription: Check if string contains a certain amount of words of another string


code:
dict1 = {'key1':['value11','value12','value13'] , 'key2':['value21','value22','value23']}
dict2 = {'key1':['value14','value15'] , 'key2':['value24','value25']}

dict3 = {}
for key in set().union(dict1, dict2):
    if key in dict1: dict3.setdefault(key, []).extend(dict1[key])
    if key in dict2: dict3.setdefault(key, []).extend(dict2[key])

print(dict3)
# {'key2': ['value21', 'value22', 'value23', 'value24', 'value25'], 'key1': ['value11', 'value12', 'value13', 'value14', 'value15']}

rawDescription: Combining 2 dictionaries with common key


code:
import numpy

coeffs = numpy.loadtxt("test.dat", dtype = numpy.complex128)

rawDescription: Writing and reading complex numbers using numpy.savetxt and numpy.loadtxt


code:
import re
test = r'"hello" "Hello\\" "I am an example" "the man said:\"hello!\\\""'
for match in re.findall(r'"(?:\\.|[^"\\])*"', test):
    print(match)

rawDescription: Parsing an escape character in Python

description: Parsing an escape character in Python


code:
voices = Voice.objects.filter(user__id=1)
new_voices = []
for voice in voices:
    voice.pk = None
    voice.user = user
    right_answsers = 0
    wrong_anwsers = 0
    new_voices.append(voice)

Voice.objects.bulk_create(new_voices)

rawDescription: Fetch and save a copy of a QuerySet with a new User field in Django


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

x = np.linspace(0,2,10)
y = np.sin(x)

marker = itertools.cycle((',', '+', '.', 'o', '*'))

fig = plt.figure()
ax = fig.add_subplot(111)

for q,p in zip(x,y):
    ax.plot(q,p, linestyle = '', marker=marker.next())

plt.show()

rawDescription: unique plot marker for each plot in matplotlib

description: Unique plot marker for each plot in matplotlib


code: np.savetxt('temp.txt', x)

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

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


code:
def transform(inputt, outputt_base):
    with open(inputt, "r") as f:
        for count, block in enumerate(f.read().split("***")):
            outputt_name = outputt_base + "_{0}.txt".format(count)
            with open(outputt_name, "w") as f1:
                f1.write(block)

rawDescription: Python copy all lines before string in another text file


code: price_list[-2] < stock_averages[-2]

rawDescription: Output issue calculating moving average

description: Output issue calculating moving average


code:
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

def send_file_zipped(the_file, recipients, sender='you@you.com'):
    zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')
    zip = zipfile.ZipFile(zf, 'w')
    zip.write(the_file)
    zip.close()
    zf.seek(0)

    # Create the message
    themsg = MIMEMultipart()
    themsg['Subject'] = 'File %s' % the_file
    themsg['To'] = ', '.join(recipients)
    themsg['From'] = sender
    themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
    msg = MIMEBase('application', 'zip')
    msg.set_payload(zf.read())
    encoders.encode_base64(msg)
    msg.add_header('Content-Disposition', 'attachment',
                   filename=the_file + '.zip')
    themsg.attach(msg)
    themsg = themsg.as_string()

    # send the message
    smtp = smtplib.SMTP()
    smtp.connect()
    smtp.sendmail(sender, recipients, themsg)
    smtp.close()

rawDescription: How can I compress a folder and email the compressed file in Python?

description: Compress a folder and email the compressed file in Python


code:
def TextFileEncyption(offset, txt):
    '''This will convert the text file that the user inputted earlier,
       using the offset factor to do so'''
    Message = ""
    print("The program is now going to encrypt your chosen text file...")
    # go through each character in the input text
    for char in txt:
        number = ord(char)
        # ...and only modify characters that are *not* a space character
        if number != 32:
            number = number + offset
            if number > 126:
                number -= 94
        # ...then convert the value back into a character
        ASCIIletter = chr(number)
        # and append it to the message variable for output.
        Message += ASCIIletter
    print(Message)

if __name__ == "__main__":
    import sys
    inText = "This is a test of the function."
    if len(sys.argv) > 1:
        inText = sys.argv[1]
    TextFileEncyption(10, inText)

rawDescription: Trying to not convert spaces with 'ord()' in Python


code:
def steamid_to_64bit(steamid):
    steam64id = 76561197960265728 # I honestly don't know where
                                    # this came from, but it works...
    id_split = steamid.split(":")
    steam64id += int(id_split[2]) * 2 # again, not sure why multiplying by 2...
    if id_split[1] == "1":
        steam64id += 1
    return steam64id

In [14]: steamid_to_64bit("STEAM_1:0:61759597")
Out[14]: 76561198083784922

In [15]: steamid_to_64bit("STEAM_1:1:20263946")
Out[15]: 76561198000793621

In [16]: steamid_to_64bit("STEAM_1:0:105065707")
Out[16]: 76561198170397142

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

description: Get a steamid 64 from a steamID in python


code:
import urllib2
from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen("http://www.webmd.com/diet/belly-fat-diet"))

print([header.text for header in soup.find_all("h3")])
print([p.text for p in soup.find_all("p")])

rawDescription: Only print content between tags

description: Only print content between tags


code:
dataset = []
for entry in data['wc']:
    dataset.extend([entry['value'], entry['id']])
dataset
[0, 8, 1, 9]

rawDescription: Convert json to array in python (value,id,value,id....)


code:
key1 = table.index.labels[0]
key2 = table.rank(ascending=False)

# sort by key1, then key2
sorter = np.lexsort((key2, key1))

sorted_table = table.take(sorter)

rawDescription: Pandas: Sort pivot table

description: Pandas: Sort pivot table


code:
x= [['first sentence'],['second sentence'],['third sentence']]
y= [1,0,1]

for zx,zy in zip(x, y):
    print('{}, {}'.format(zx[0], zy))

rawDescription: how to write two elements into one row in Python

description: Write two elements into one row in Python


rawDescription: How to split rows into two columns in Pandas

description: Split rows into two columns in Pandas


code:
X,Y = [np.arange(-r,r+1)]*2
disk_mask = X[:,None]**2 + Y**2 <= r*r
Ridx,Cidx = np.where(disk_mask)

out = np.zeros(out_shp,dtype=bool)

absidxR = maskcenters[:,None,0] + Ridx-r
absidxC = maskcenters[:,None,1] + Cidx-r

valid_mask = (absidxR >=0) & (absidxR <out_shp[0]) & \
             (absidxC >=0) & (absidxC <out_shp[1])

out[absidxR[valid_mask],absidxC[valid_mask]] = 1

rawDescription: Applying a disc shaped mask to several locations in a NumPy array


rawDescription: Concatenate lines with similar key

description: Concatenate lines with similar key


code:
def s(n):
    tsum = 1
    for p in primes:
        d = 1
        # divide out all factors p of n
        while n % p == 0:
            n = n//p
            d = p*d + 1
        tsum *= d
        if p*p > n: # n = 1, or n is prime
            break
    if n > 1:       # one last prime factor to account for
        tsum *= 1 + n
    return tsum

rawDescription: How would I go about improving/making this run faster?


code: cmd = '{} {}'.format(LS, FILENAME)

rawDescription: python command substitution for linux commands

description: Python command substitution for linux commands


code:
import collections

def flattendict(d, prefix=()):
  r = {}
  for k, v in d.iteritems():
    pk = prefix + (k,)
    if isinstance(v, collections.Mapping):
      r.update(flattendict(v, pk))
    else:
      r['_'.join(pk)] = v
  return r

rawDescription: Transforming deeply nested dictionary to 1D dictionary with Python


code: dt = Symbol('dt', complex=True)

rawDescription: Suppress the transpose of a symbol in sympy output when the symbol is a scalar


code:
import threading
import logging
logger = logging.getLogger(__name__)
lock = threading.Lock()

def f1():
    with lock:
        logger.info('f1')
        threading.Timer(10, f1).start()

def f2():
    with lock:
        logger.info('f2')
        threading.Timer(8, f2).start()

def f3():
    with lock:
        logger.info('f3')
        threading.Timer(23, f3).start()

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG,
                        format='[%(asctime)s %(threadName)s] %(message)s',
                        datefmt='%H:%M:%S')
    threading.Thread(target=f1).start()
    threading.Thread(target=f2).start()
    threading.Thread(target=f3).start()

rawDescription: Python schedule repeating multiple threads


rawDescription: How can I make my code more readable and DRYer when working with XML namespaces in Python?

description: Make my code more readable and DRYer when working with XML namespaces in Python


code:
t_list = [object1, object2, object3, object1, object1, object5]
# ...
data = {
    'some_path': t_list[1],
    'some_more': {
        t_list[3]
    }
};

rawDescription: Replacing references in Python3

description: Replacing references in Python3


code: max_height = heights[0][1]

rawDescription: Suggestions for improving my method for finding the max value


code:
class PrefixCompares(object):
    def __init__(self, value):
        self.value = value
    def __lt__(self, other):
        return self.value < other[0:len(self.value)]

import bisect
names = ['adam', 'bob', 'bob', 'bob', 'bobby', 'bobert', 'chris']
names.sort()
key = PrefixCompares('bob')
leftIndex = bisect.bisect_left(names, key)
rightIndex = bisect.bisect_right(names, key)
print(names[leftIndex:rightIndex])

rawDescription: Perform a binary search for a string prefix in Python


rawDescription: Best way to decode command line inputs to Unicode Python 2.7 scripts

description: Decode command line inputs to Unicode Python 2.7 scripts


code:
def reach(travel_dict, x, visited=None):
    if visited is None:
        visited = set() # see note
    visited.add(x)
    for y in travel_dict.get(x, []):
        if y not in visited:
            yield y
            for z in reach(travel_dict, y, visited):
                yield z

rawDescription: Recursive traversal of a dictionary in python (graph traversal)


code:
def conv_app(A, WSZ):
    K = np.ones(WSZ,dtype=int)
    L = WSZ-1
    return (np.convolve(np.convolve(A,K)>=WSZ,K)[L:-L]>0).astype(int)

rawDescription: Filtering pandas or numpy arrays for continuous series with minimum window length


code:
import os

def deleteAll(infilepath):
    with open(infilepath) as infile:
        for line in infile:
            os.remove(line)

rawDescription: Deleting specific files from a directory


code:
class PrintThis(object):

    def __init__(self, print_list=None):
        if print_list is None:
            print_list = []
        self.print_list = print_list

    def __call__(self):
        if self.print_list:
            print("Print list: {0}".format(self.print_list))
        else:
            print("Print list empty.")

    def send(self, item):
        self.print_list.append(item)

rawDescription: Initializing Functions Like a Class

description: Initializing Functions Like a Class


code: df[(df.str.contains("b") == True) & (df.str.contains("a") == False)]

rawDescription: Python Pandas: String Contains and Doesn't Contain


code:
def my_safe_method(*args):
    my_cool_object = CoolClass()
    my_cool_object.populate_from_stuff(*args)
    return my_cool_object.result()

rawDescription: If I have an @staticmethod in my python webapp, do I need to protect it with threading.RLock()?


code:
r1,r2,r3,r4=np.arange(3),np.ones(3),np.zeros(3),np.arange(3)[::-1]
x1=np.array((r1,r2))
x2=np.array((r3,r4))
rays=[x1,x2]
rays

rawDescription: Efficient way of appending / extracting list elements


rawDescription: Read (little endian) hex pair that represents a byte in python


code:
import itertools
import numpy as np
from scipy.spatial.distance import pdist, squareform

points = np.random.rand(100,2)  # could be nodes in 3 dimensions too, but you specify a handpalm, so I'm guessing your contour is merely 2D

def palm_combinations(points, dist_min=.0, dist_max=.05):
    dists = pdist(points)
    # This matrix lists the distance between each pair of nodes
    # (represented by their column and row index, so that the mat[i,j]
    # represents the distance between points[i,:], points[j,:])
    mat = squareform(dists)

    mask = (mat > dist_min) & (mat < dist_max)

    two_good_legs = {}  # store all combinations of point indices where "two legs" of the triangles have a distance that matches the spec.
    myinds = []
    for rowind, row in enumerate(mask):
        relevant = row[rowind+1:]  # distance to a point itself is always zero, hence exclude from list
        inds = np.where(relevant)[0] + (rowind+1)
        myinds.append(inds)
        two_good_legs[rowind] = list(itertools.combinations(inds, 2))

    triangles = []
    # The only thing left to do now is to check if the third leg's norm is also within spec.
    for k,v in two_good_legs.items():
        for tup in v:
            if tup[1] in myinds[tup[0]]:
                triangles.append((k, tup[0], tup[1]))
    return triangles

rawDescription: Speeding up selecting sets of 3 nodes that form triangles with given min and max side length


code:
from functools import reduce
from operator import mul

for numset in itertools.product(numbers, repeat=n):
    print(reduce(mul, numset))

rawDescription: Nest n loops for any n in Python

description: Nest n loops for any n in Python


code:
def main():

    ...

    if 300 <= pt.getY() <= 350 and 220 <= pt.getX() <= 370:
        # you can chain conditionals as above. It makes it much easier to read!
        # `a <= N <= b` is easily read as `N is between a and b`

        userPhrase = inputBox.getText()
        if userPhrase.strip():  # if there's something there
            file_open(userPhrase)
        else:
            file_open()

rawDescription: Files won't be read in GUI program, only in shell


code:
with open("my.file", "r+") as f:
    for x in xrange(100):
        f.readline()
    f.truncate()

rawDescription: Python: truncate a file to 100 lines or less


code:
bin_width = bins[1:] - bins[:-1]
values2 = values1 / np.sum(values1) / bin_width

rawDescription: How to convert between different pylab.histogram results

description: Convert between different pylab.histogram results


code:
#!/usr/bin/env python3

EXCHANGE_DATA = [('AIA', 'Auckair', 1.50),
                 ('AIR', 'Airnz', 5.60),
                 ('AMP', 'Amp',3.22)]

user_input = input("Please Specify Shares: ")

names = set(user_input.upper().split())

print ('Listing the following shares: ' + str(names))
print (" ")

# Print header
n=["Code", "Name", "Price"]
print ('{0: <6}{1:<20}{2:>8}'.format(n[0],n[1],n[2]))

#print data
for i in [data for data in EXCHANGE_DATA if data[0] in names]:
  print ('{0: <6}{1:<20}{2:>8}'.format(i[0],i[1],i[2]))

rawDescription: Return multiple input (Python)

description: Return multiple input (Python)


rawDescription: Concat DataFrame Reindexing only valid with uniquely valued Index objects


code:
def cutit(s,n):
   return s[n:]

rawDescription: Remove n characters from a start of a string


code:
from issue import A, B, C
c.__class__ = C

rawDescription: Any way to manually fix operation of `super()` after IPython reload (avoiding TypeError)?


rawDescription: Transform irregular quadrilateral to rectangle in python matplotlib


code:
class MixedNumber(object):
   def __init__(self, whole_number, fraction):
        self.whole_number = whole_number
        self.fraction = fraction

   def __str__(self):
        if self.fraction.numerator == 0:
            return str(self.whole_number)
        elif self.whole_number == 0:
            return str(self.fraction)
        else:
            return '{} {}'.format(self.whole_number,self.fraction)

   def __repr__(self):
        return 'MixedNumber({},{!r})'.format(self.whole_number,self.fraction)

rawDescription: Python sub-classes

description: Python sub-classes


code:
import scipy.stats as ss
ss.rankdata([3, 1, 4, 15, 92])
ss.rankdata([1, 2, 3, 3, 3, 4, 5])

rawDescription: Efficient method to calculate the rank vector of a list in Python


rawDescription: how to get a 2d numpy array from a pandas dataframe? - wrong shape

description: Get a 2d numpy array from a pandas dataframe? - wrong shape


code:
def f(t_):
    return sol.args[1].subs([(t, t_)])

print(sol)
print(f(0))

rawDescription: how to solve first-order linear differential equations analytically and numerically with sympy?

description: Solve first-order linear differential equations analytically and numerically with sympy


rawDescription: Remove everything but the last part of an element


code:
data = [
{
    "State_Code": "01",
    "County_Code": "000",
    "State_Abbrv": "AL",
    "County_Name": "ALABAMA",
    "DATA": "12345"

},
{
    "State_Code": "01",
    "County_Code": "001",
    "State_Abbrv": "AL",
    "County_Name": "AUTAUGA COUNTY",
    "DATA": "123"

},
{
    "State_Code": "01",
    "County_Code": "003",
    "State_Abbrv": "AL",
    "County_Name": "BALDWIN COUNTY",
    "DATA": "321"

},
{
    "State_Code": "02",
    "County_Code": "000",
    "State_Abbrv": "AK",
    "County_Name": "ALASKA",
    "DATA": "98765"

},
{
    "State_Code": "02",
    "County_Code": "013",
    "State_Abbrv": "AK",
    "County_Name": "ALEUTIANS EAST BOROU",
    "DATA": "456"

}
]

roots = [ d for d in data if d['County_Code'] == '000']

def crawl(data, roots):
    for root in roots:
        yield {
            'name' : root['County_Name'],
            'children' : [{ 'name' : d['County_Name'], 'DATA' : d['DATA'] }
                for d in data if d['County_Code'] != '000' and d['State_Code'] == root['State_Code']]
        }

final = { 'name' : 'USA', 'children' : [ x for x in crawl(data, roots)]}

import pprint

pprint.pprint(final)

rawDescription: Refactor a list of JSON objects to a nested list


code:
enter
A
exit
enter2
A
exit2

rawDescription: python: cleanest way to wrap each method in parent class in a "with"

description: Python: cleanest way to wrap each method in parent class in a "with"


code:
import urllib2
import csv
from bs4 import BeautifulSoup

url = "http://www.chicagoreader.com/chicago/BestOf?category=4053660&year=2013"
soup_package = BeautifulSoup(urllib2.urlopen(url))
all_categories = soup_package.find_all("div", class_="bestOfItem")

with open("file.csv", 'w') as f:
    csv_writer = csv.writer(f)
    for match_categories in all_categories:
        value = match_categories.a.string
        if value:
            csv_writer.writerow([value.encode('utf-8')])

rawDescription: Moving scraped data using BeautifulSoup to csv


code:
from posixpath import curdir, sep, pardir, join

def relpath(path, start=curdir):
    """Return a relative version of a path"""
    if not path:
        raise ValueError("no path specified")
    start_list = posixpath.abspath(start).split(sep)
    path_list = posixpath.abspath(path).split(sep)
    # Work out how much of the filepath is shared by start and path.
    i = len(posixpath.commonprefix([start_list, path_list]))
    rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
    if not rel_list:
        return curdir
    return join(*rel_list)

rawDescription: How to get relative file path on Python 2.5?

description: Get relative file path on Python 2.5


code:
import numpy as np
square = np.array([[1,2,3],[4,5,6],[7,8,9]])
square[0]
square[..., 0]
square[:, 0]

rawDescription: In a list of lists, is there a way to get the elements in an element's row and column simultaneously?


rawDescription: Check Density of a Scipy Sparse Matrix

description: Check Density of a Scipy Sparse Matrix


code:
class TimedButton(Button):
    """A simple ``Button`` subclass that produces an event at regular intervals
    when pressed.

    This class, when long-pressed, emits an ``on_time_slice`` event every
    ``time_slice`` milliseconds.

    :param long_press_interval: Defines the minimum time required to consider
                                the press a long-press.
    :type long_press_interval: int
    :param time_slice: The number of milliseconds of each slice.
    :type time_slice: int
    """

    def __init__(self, long_press_interval=550, time_slice=225, **kwargs):
        super(TimedButton, self).__init__(**kwargs)

        self.long_press_interval = long_press_interval
        self.time_slice = time_slice

        self._touch_start = None
        self._long_press_callback = None
        self._slice_callback = None

        self.register_event_type('on_time_slice')
        self.register_event_type('on_long_press')

    def on_state(self, instance, value):
        if value == 'down':
            start_time = time.time()
            self._touch_start = start_time

            def callback(dt):
                self._check_long_press(dt)

            Clock.schedule_once(callback, self.long_press_interval / 1000.0)
            self._long_press_callback = callback
        else:
            end_time = time.time()
            delta = (end_time - (self._touch_start or 0)) * 1000
            Clock.unschedule(self._slice_callback)
            if (self._long_press_callback is not None and
                delta > self.long_press_interval):
                self.dispatch('on_long_press')
            self._touch_start = None
            self._long_press_callback = self._slice_callback = None

    def _check_long_press(self, dt):
        delta = dt * 1000
        if delta > self.long_press_interval and self.state == 'down':
            self.dispatch('on_long_press')
            self._long_press_callback = None

            def slice_callback(dt):
                self.dispatch('on_time_slice')
                return self.state == 'down'

            Clock.schedule_interval(slice_callback, self.time_slice / 1000.0)

            self._slice_callback = slice_callback

    def on_long_press(self):
        pass

    def on_time_slice(self):
        pass

rawDescription: Bind working at random times

description: Bind working at random times


code:
txt='1|abc|Red|no'
txt=[txt,txt,txt]
A=np.genfromtxt(txt, dtype=None, delimiter='|')
A

rawDescription: Python generate from list instead of Genfromtext


rawDescription: Python .join() iterable string

description: Python .join() iterable string


code:
import numpy
with open('test.txt', 'r') as fil:
    lines = fil.readlines()
lines = [line.strip().split() for line in lines]
arr = numpy.array(lines)

rawDescription: Finding duplicates in each row and column


code: values

rawDescription: Convert formatted log string back to LogRecord


code:
for f in os.listdir(folder):
    process(f)

rawDescription: Modify python script to run on every file in a directory


rawDescription: Deleting everything that is enclosed with quotes or is a number in Python?


code:
def test(xlist):
    from collections import defaultdict
    ret = defaultdict(list)
    for x in xlist:
        y = somefunction(x)
        ret[y.variable].append(y)
    return ret

rawDescription: How to create a dict of lists in as little coding as possible in Python?

description: Create a dict of lists in as little coding as possible in Python


code:
from haystack.query import SearchQuerySet
from django.contrib.sites.models import Site
from django.shortcuts import render

current_site = Site.objects.get_current()

def search(request):
    cx = {}
    query = request.GET.get('q', '')
    cx['query'] = query
    cx['result'] = SearchQuerySet().filter(content=query, sites__in=[current_site.domain])
    return render(request, 'search/search.html', cx)

rawDescription: Django Haystack Multisite Indexes

description: Django Haystack Multisite Indexes


code:
elements = ['a','aa','aaaaaaaa']
simple_values = [ e[:3] + ('...' if len(e) > 3 else '') for e in elements]
combo = Combobox(root,values=simple_values )

rawDescription: In Python Tkinter, how do I set an OptionMenu to a fixed size shorter than the longest item?


rawDescription: How do I get rid of Python Tkinter root window?

description: Get rid of Python Tkinter root window


code:
one_variable = DoubleVar()

scaleX = Scale(root, variable=one_variable)
scaleY = Scale(root, variable=one_variable)

rawDescription: Update Scale Widget from the value of other Scale Widget


code:
key = random.sample(ints, 8)
key
offset = sum(key)
offset
key = ''.join(map(chr, key))
key

rawDescription: How do i take out values from a string? Python

description: Take out values from a string? Python


code:
# some imports
import numpy as np
import glob
from multiprocessing import Pool
import os

# creating some temporary data
tmp_dir = os.path.join('tmp', 'nptest')
if not os.path.exists(tmp_dir):
    os.makedirs(tmp_dir)
    for i in range(100):
        x = np.random.rand(10000, 50)
        file_path = os.path.join(tmp_dir, '%05d.npz' % i)
        np.savez_compressed(file_path, x=x)

def read_x(path):
    with np.load(path) as data:
        return data["x"]

def serial_read(files):
    x_list = list(map(read_x, files))
    return x_list

def parallel_read(files):
    with Pool() as pool:
        x_list = pool.map(read_x, files)
    return x_list

rawDescription: Loading several npz files in a multithreadedly


rawDescription: How to get RMSE from scipy.optimize.leastsq module

description: Get RMSE from scipy.optimize.leastsq module


code: area, population = countries["USA"]

rawDescription: reading file into a dictionary

description: Reading file into a dictionary


code:
ne_stacked = (df1 != df2).stack()
changed = ne_stacked[ne_stacked]
changed.index.names = ['id', 'col']
changed

rawDescription: Outputting difference in two pandas dataframes side by side - highlighting the difference


code:
def add_alt_name(template):
    def decorator(klass):
        klass.alt_name = template.format(klass.__name__)
        return klass
    return decorator

@add_alt_name(template="{}_ending")
class Foo:
    pass

print(Foo.alt_name)

rawDescription: How to add or change a Class (not an instance)?

description: Add or change a Class (not an instance)


code:
def msearch():
    es = get_es_instance()

    request = []

    req_head = {'index': 'my_test_index', 'type': 'doc_type_1'}
    req_body = {
        'query': {'term': {'text' : 'bag'}},
        'from' : 0, 'size': 2  }
    request.extend([req_head, req_body])

    req_head = {'index': 'my_test_index', 'type': 'doc_type_2'}
    req_body = {
        'query': {'range': {'price': {'gte': 100, 'lt': 300}}},
        'from' : 0, 'size': 2  }
    request.extend([req_head, req_body])

    resp = es.msearch(body = request)

rawDescription: How to create request body for Python Elasticsearch mSearch

description: Create request body for Python Elasticsearch mSearch


code: dict(line.split(':', 1) for line in open('words.txt'))

rawDescription: read text file (colon-separated words) and get a list of tuples

description: Read text file (colon-separated words) and get a list of tuples


rawDescription: Sort a numpy array by another array, along a particular axis


code:
import re

s  = 'ref_layerid_mapping="x4049" lyvis="off" toc_visible="off"'
pat = re.compile(r'ref_layerid_mapping=(.+) lyvis="off" toc_visible="off"')

def replacer(m):
    return "ref_layerid_mapping=" + m.group(1) + 'lyvis="on" toc_visible="on"';

re.sub(pat, replacer, s)

rawDescription: Search for string in file while ignoring id and replacing only a substring


rawDescription: Python's re library's sub method "eating" capturing groups


rawDescription: How to do linear regression, taking errorbars into account?

description: Do linear regression, taking errorbars into account


code:
from Tkinter import *

master = Tk()

def my_callback():
    print('Running my_callback')

b = Button(master, text="OK", command=my_callback)
b.pack()

mainloop()

rawDescription: Call back in Python

description: Call back in Python


code:
import string

alphabet = string.ascii_lowercase
message = input('Please insert the message you want to encrypt: ')
key = int(input('What key value do you want in your encryption? '))

output = []

for m in message:
    if m in alphabet:
        output.append(alphabet[(alphabet.index(m) + key) % (len(alphabet))])

print(''.join(output))

rawDescription: How do I make a cipher and encrypt the text?

description: Make a cipher and encrypt the text


code:
datacursor(l, hover=True, point_labels=df['E'], bbox=dict(fc='white'),
           formatter=lambda **kwargs: kwargs['point_label'][0], xytext=(0, 25),
           arrowprops=dict(arrowstyle='simple', fc='white', alpha=0.5))

rawDescription: How to show data labels when you mouse over data

description: Show data labels when you mouse over data


code:
def quit_app(self,obj):
    App.get_running_app().stop()

rawDescription: How can I add one more button on kivy?

description: Add one more button on kivy


code:
def test_index_should_validate_depth_in_operations(self):
    # ....
    # depth=3
    idx = HierarchicalIndex(3)

    assert_that(idx.get('A'), has_length(0))
    assert_that(idx.get('A', 'X'), has_length(0))
    assert_that(idx.get('A', 'X', 'i'), has_length(0))
    self.assertRaises(AssertionError, lambda: idx.get('A', 'X', 'i', '1'))

    self.assertRaises(AssertionError, lambda: idx.insert(1))
    self.assertRaises(AssertionError, lambda: idx.insert(1, 'A'))
    self.assertRaises(AssertionError, lambda: idx.insert(1, 'A', 'X'))
    idx.insert(1, 'A', 'X', 'i')        # should not raise anything
    self.assertRaises(AssertionError, lambda: idx.insert(1, 'A', 'X', 'i', 'a'))

    assert_that(idx.get('A', 'X', 'i'), equal_to([1]))

rawDescription: A tree structure with dynamic depth and data in only leaves


code: new_list = reduce(lambda x, y: x+y, old_list)

rawDescription: Looking for a strategy for parsing a file


code:
INSTALLED_APPS = ('storages',)

AWS_ACCESS_KEY_ID = 'xxxxxx'
AWS_SECRET_ACCESS_KEY = 'xxxxxxx'
AWS_STORAGE_BUCKET_NAME = 'bucket_name'

STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

STATIC_URL = 'http://s3.amazonaws.com/%s' % AWS_STORAGE_BUCKET_NAME + '/'

rawDescription: Serve static files on heroku using AWS S3 for django?


code:
import re
inputstring = "pixel1blue pin10off output2high foo9182bar"
re.sub(r'(\d+)', r'[\1]', inputstring)

rawDescription: Add [] around numbers in strings

description: Add [] around numbers in strings


code: np.minimum(df, df.quantile(0.9))

rawDescription: set value to 99 percentile for each column in a dataframe

description: Set value to 99 percentile for each column in a dataframe


code:
s = '''foo = 'some',"stuff?",'that "could be?" nested?', ? but still capture this? and "this?"'''
[i for i in re.split(r'^((?:"[^"]*"|\'[^\']*\'|[^\'"?])*)\?', s) if i]

rawDescription: Regular Expression Split on character not in Qualified String (python)


code:
import global_vals
def foo():
  v1 = global_vals.VAL1
  v2 = global_vals.VAL2

rawDescription: Django Cached Class

description: Django Cached Class


code:
import sys
signal.signal(signal.SIGTERM, lambda num, frame: sys.exit(0))

rawDescription: Run code in python script on shutdown signal


code:
class MonFrozenSet(frozenset):
    def __new__(cls, data):
        return super(MonFrozenSet,cls).__new__(cls, data)

rawDescription: Python: Subclassing frozenset not iterable?


code:
def get_sql(tuple_of_querysets):
    '''Return a set of SQL statements from a tuple of QuerySets'''
    return set([str(queryset.query) for queryset in tuple_of_querysets])

# ordering of items in sets do not matter: set([q1, q2]) = set([q2, q1])
if get_sql(qsets_arb) in map(get_sql, list_of_querysets[:]):
     print("This tuple of QuerySets has already been included")
else:
     list_of_querysets.append(qsets_arb)

rawDescription: Check if queryset already exists

description: Check if queryset already exists


code:
class LoginPage(object):

    def __init__(self, testcase):
        self.tc = testcase

    def login(self, username, password, at_login_page=False):
        if not at_login_page:
            self.tc.browser.get(self.tc.ROOT + '/login')

        self.tc.browser.find_element_by_id('id_username').send_keys(username)
        self.tc.browser.find_element_by_id('id_password').send_keys(password)
        login_button = self.tc.browser.find_element_by_id('login-button').click()

rawDescription: selenuim webdriver in python. any 3rd party libs?

description: Selenuim webdriver in python. any 3rd party libs


code:
import module1

if __name__ == '__main__':
    module1.shared.name = 'Shailendra'
    module1.print_value()

rawDescription: Sharing data between two functions in two different modules in python 2.x


code:
df.set_index(['ticker', 'date'], inplace=True)
df

rawDescription: How do I create pandas DataFrame (with index or multiindex) from list of namedtuple instances?

description: Create pandas DataFrame (with index or multiindex) from list of namedtuple instances


code:
dt = date.today()   # today's a Wednesday
dt
dt.isocalendar()[1]
dt.isocalendar()[1] - (dt.isoweekday() < 2)  # week starts on Tuesday
dt.isocalendar()[1] - (dt.isoweekday() < 3)  # week starts on Wednesday

rawDescription: Python: Define starting day in week definition in isocalendar or strftime or else


code:
def getItems():
    cursor.execute(query1)
    for row in cursor.fetchall():
        yield row
    cursor.execute(query2)
    for row in cursor.fetchall():
        yield row

gen = getItems()

for item in gen:
    ...

rawDescription: How do I combine the output of several MySQLdb fetch_all() calls into one list?

description: Combine the output of several MySQLdb fetch_all() calls into one list


code:
from klepto.archives import dir_archive
d = {'a':1, 'b':2, 'c':map, 'd':None}
# map a dict to a filesystem directory
demo = dir_archive('demo', d, serialized=True)
demo['a']
demo['c']
demo
# is set to cache to memory, so use 'dump' to dump to the filesystem
demo.dump()
del demo

demo = dir_archive('demo', {}, serialized=True)
demo
# demo is empty, load from disk
demo.load()
demo
demo['c']

rawDescription: Saving pickle object at each iteration without writing whole object each time


code:
s = df.Price * 2
s.name = 'PriceSquared'

rawDescription: DataFrameGroupBy object Column Name

description: DataFrameGroupBy object Column Name


rawDescription: Run epydoc and/or pylint builders from scons file


code: p = Popen('ssh servername cat /proc/cpuinfo', shell=True, stdout=PIPE)

rawDescription: Interface with remote computers using Python


code:
from rest_framework import routers, views, reverse, response

class HybridRouter(routers.DefaultRouter):
    def __init__(self, *args, **kwargs):
        super(HybridRouter, self).__init__(*args, **kwargs)
        self._api_view_urls = {}

    def add_api_view(self, name, url):
        self._api_view_urls[name] = url

    def remove_api_view(self, name):
        del self._api_view_urls[name]

    @property
    def api_view_urls(self):
        ret = {}
        ret.update(self._api_view_urls)
        return ret

    def get_urls(self):
        urls = super(HybridRouter, self).get_urls()
        for api_view_key in self._api_view_urls.keys():
            urls.append(self._api_view_urls[api_view_key])
        return urls

    def get_api_root_view(self):
        # Copy the following block from Default Router
        api_root_dict = {}
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)
        api_view_urls = self._api_view_urls

        class APIRoot(views.APIView):
            _ignore_model_permissions = True

            def get(self, request, format=None):
                ret = {}
                for key, url_name in api_root_dict.items():
                    ret[key] = reverse.reverse(url_name, request=request, format=format)
                # In addition to what had been added, now add the APIView urls
                for api_view_key in api_view_urls.keys():
                    ret[api_view_key] = reverse.reverse(api_view_urls[api_view_key].name, request=request, format=format)
                return response.Response(ret)

        return APIRoot.as_view()

rawDescription: django rest-framework singleton ViewSet

description: Django rest-framework singleton ViewSet


rawDescription: creating Qlabels with dynamic name at run time

description: Creating Qlabels with dynamic name at run time


code: [sorted(g,cmp=cmp_tasks)[-1] for g in groups.values()]

rawDescription: Python way of getting max of list containing integers and floats


code:
import os
i = 0
while os.path.exists('{}{:d}.png'.format(filename, i)):
    i += 1
plt.savefig('{}{:d}.png'.format(filename, i))

rawDescription: Python: Keep savefig from overwriting old plots


code: last_phrase = v.voiceRecognition() # like this?

rawDescription: Python 2.7 Get return value from function without running what is in the function again?


rawDescription: Python script losing arguments when run from PATH on Windows


rawDescription: Is it possible to run a while loop and check for tkinter input in python 3


code:
conditions = []
if category_id is not None:
    conditions.append(docs.c.category_id == category_id)
if sub_category_id is not None:
    conditions.append(docs.c.sub_category_id == sub_category_id)
if alert_date is not None:
    conditions.append(docs.c.alert_date == alert_date)

s = select([docs]).where(and_(*conditions))

rawDescription: sqlalchemy core build dynamic query

description: Sqlalchemy core build dynamic query


code:
def cdiv(x, y):
    return abs(x) / abs(y) * cmp(x, 0) * cmp(y, 0)

rawDescription: Changing python math module behaviour for non-positive numbers division


code:
min_boundaries = set(min for id, min, max in orig)
max_boundaries = set(max for id, min, max in orig)
segment_boundaries = sorted(list(min_boundaries | max_boundaries))

rawDescription: python array challenge

description: Python array challenge


code:
import numpy as np
import matplotlib.pyplot as plt
s = [1,1,1,1,2,2,2,3,3,4,5,5,5,6,7,7,7,7,7,7,7]

xmin = 1
xmax = 7
step = 1
y, x = np.histogram(s, bins=np.linspace(xmin, xmax, (xmax-xmin)/step))

nbins = y.size

plt.bar(x[:-1], y, width=x[1]-x[0], color='red', alpha=0.5)
plt.hist(s, bins=nbins, alpha=0.5)
plt.grid(True)
plt.show()

rawDescription: What is the difference between `np.histogram` and `plt.hist`? Why don't these commands plot the same graphics?


code:
x = range(20)
b = x[:]
a = sorted([b.pop(b.index(random.choice(b))) for n in xrange(limit)])
a
b

rawDescription: Random split list, keeping the original order in new lists


code:
import requests
import hashlib

r = requests.get(url, stream=True)

sig = hashlib.md5()
for line in r.iter_lines():
    sig.update(line)

print(sig.hexdigest())

rawDescription: python on-the-fly md5 as one reads a stream

description: Python on-the-fly md5 as one reads a stream


code:
import Tkinter as tk

import module1 as md1

main_sizex = 1280
main_sizey = 750
main_posx = 1
main_posy = 1
main_title = "Hello! This is a test"
main_titlesize = 22
root = tk.Tk()
window = md1.Drag_Window(root, main_sizex, main_sizey, main_posx, main_posy, main_title, main_titlesize)
window.button.config(bg='green')
root.mainloop()

rawDescription: Python tkinter accessing object properties


code:
def test(self, index=None):
    if index is not None:
        print(str(index))
    else:
        print("Index not found")

rawDescription: 0 being passed as an optional parameter to a class' method, param not found


code: l.sort(key=len, reverse=True)

rawDescription: Sort a list of sets

description: Sort a list of sets


code:
lst = [5,6,3,2,7]
quicksort(lst)
lst

rawDescription: Python QuickSort returning original input


code:
class AccountManager(models.Manager):
    def get_query_set(self):
        return AccountQuerySet(self.model)

rawDescription: override Django Get or Create

description: Override Django Get or Create


rawDescription: Python object1 = object2

description: Python object1 = object2


code:
fig, ax = subplots()
ax.plot(t, x, 'o-')
ax.set_xlim(1/(4*f)-1/fs*3, 1/(4*f)+1/fs*3)
ax.set_ylim(0, 1.1)
ax.set_xlabel('Time',fontsize =18)
ax.set_ylabel('Amplitude',fontsize = 18)

rawDescription: Python not setting range correctly in plots


rawDescription: How do you find and delete the highest integer in a list of unknown integers

description: Find and delete the highest integer in a list of unknown integers


code: [int.from_bytes(x[i:i+3], 'big', signed=False) for i in range(0, len(x), 3)]

rawDescription: Python convert a bytearray to hex array

description: Python convert a bytearray to hex array


code: taxoDict['familia']

rawDescription: Parse Wikipedia Wikitext Template Named Parameters to Extract Data from Taxobox


rawDescription: BeautifulSoup - How do I extract a substring of a string between tags?


rawDescription: Python sequence translation

description: Python sequence translation


code:
from django.db.models import F

class PurchaseOrder(models.Model):
    product = models.ManyToManyField('Product', through='OrderItem')
    dollar_amount = models.DecimalField(verbose_name='Total Price')

class OrderItem(models.Model):
    current_price = models.DecimalField()
    product = models.ForeignKey(Product)
    order = models.ForeignKey(PurchaseOrder)

    def save(self, *args, **kwargs):
        if self.pk is None:
            # new item
            self.current_price = self.product.price_for_each_item
            self.order.dollar_amount = F('dollar_amount') + self.current_price
            self.order.save(update_fields=['dollar_amount']) # Or self.save() in Django < v1.5
        super(OrderItem, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        self.order.dollar_amount = F('dollar_amount') - self.current_price
        self.order.save(update_fields=['dollar_amount']) # Or self.save() in Django < v1.5
        super(OrderItem, self).save(*args, **kwargs)

rawDescription: Making an instance of a class equal to a definition Django


rawDescription: Reduce resolution of array through summation


code:
class Particle():
    def __init__(self, col, size, *strategies):
        self.x, self.y = 0, 0
        self.col = col
        self.alive = 0
        self.strategies = strategies
        self.size = size

    def kill(self):
        self.alive = -1 # alive -1 means dead

    def move(self):
        for s in self.strategies:
            s(self)

rawDescription: How to implement a particle engine

description: Implement a particle engine


code:
keyname = str(user.id) + "-" + str(post.id)
vote = Vote.get_or_insert(keyname, value="vote value")

rawDescription: More Efficient Way to Prevent Duplicate Voting


rawDescription: Open File, then read file and make them no line


rawDescription: Python: Make last item of array become the first


code: df['race4'] = pd.Categorical(df.race4, categories=['White', 'Black', 'Hispanic', 'Other'])

rawDescription: Pandas function for generating series from dataframe


code:
obj = ChildA.objects.create(owner=Peter, name="alex")
obj.owner

rawDescription: Django Admin Non Staff Access Data Filtering


rawDescription: Complex expressions in python reduce

description: Complex expressions in python reduce


code: sorted(['Some', 'words', 'sort', 'differently'])

rawDescription: What is key=lambda

description: What is key=lambda


code:
import random
a=[1,2,3,4,6,10]
random.shuffle(a)
a

rawDescription: python and numpy: Get random distribution from existing distribution

description: Python and numpy: Get random distribution from existing distribution


code:
def bar_weave():
    code = """
    int a = 0;
    for (int i=0;i<10;++i){
        py::tuple arg(1);
        arg[0] = i;
        a += (int) foo.call(arg);
    }
    return_val = a;
    """
    return inline(code,['foo'])

rawDescription: Calling Python functions from inline C with scipy.weave


code: self.lUSER = tk.Label(self, text="Username: ").pack(side="left")

rawDescription: Different Windows in TKinter

description: Different Windows in TKinter


code: df.apply(lambda x: lookup(x.name, date), axis=1)

rawDescription: pandas.DataFrame.apply() with a parameter?

description: Pandas.DataFrame.apply() with a parameter


code: import ntu       # instead of import ntu.modname for each module !

rawDescription: logging being stopped by importing a trivial function?

description: Logging being stopped by importing a trivial function


code:
lenmap = {i: open('file{}'.format(i), 'w') for i in range(10)}
try:
    for entry in List1:
        f = lenmap.get(len(entry))
        if f:
            f.write(entry)
finally:
    for f in lenmap.values():
        f.close()

rawDescription: Extract elements from a list and sorting them by length


code: createWordList('please. let! this3 work.')

rawDescription: clean line of punctuation and split into words python

description: Clean line of punctuation and split into words python


code:
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-a', type=int)
parser.add_argument('-b', type=int)

args = parser.parse_args()
fun(**dict(args._get_kwargs()))

rawDescription: Python: Using run time inputs to change key values in a function


code:
for j in OrderedDict.fromkeys(Files['key_file']):
  i = Files['key_file'].index(j)
  if j not in newFiles['key_file']:
    for key in newFiles.keys():
      newFiles[key].append(Files[key][i])
newFiles

rawDescription: Python remove duplicate values of one key in dict


code:
import itertools
for x in itertools.islice(thousand, 400, 500):
    pass

rawDescription: Is there a way to loop through a sub section of a list in Python


rawDescription: comparing list of tuple elements python

description: Comparing list of tuple elements python


rawDescription: How to split a column based on several string indices using pandas

description: Split a column based on several string indices using pandas


code:
if not d[2][3][4][5]:
    print('That element is empty!')

rawDescription: How can I get Python to automatically create missing key/value pairs in a dictionary?

description: Get Python to automatically create missing key/value pairs in a dictionary


code:
result = [yourlist for yourlist in yourlists
          if any(node.startswith('4-') for node in yourlist)]

rawDescription: Deleting a list that does not meet a specific criteria?


code: soup = BeautifulSoup(res.content.decode('gbk'), 'html5lib')

rawDescription: BeautifulSoup fails to parse html with `html5lib`


rawDescription: Shortest Syntax To Use numpy 1d-array As sklearn X


code: df

rawDescription: Pandas reformatting multiple columns into one.


code:
class Node(object):
    __slots__ = ["_data", "_next_node"]
    def __init__(self, data, next_node=None):
        self._data = data
        self._next_node = next_node

    def __str__(self):
        return str(self._data)

    def __repr__(self):
        return repr(self._data)

    @property
    def data(self):
        return self._data

    @property
    def next_node(self):
        return self._next_node

    def link_node(self, next_node):
        if not hasattr(next_node, "_next_node"):
            self._next_node = Node(next_node)
        self._next_node = next_node

class LinkedList(object):
    def __init__(self, head=None):
        if head is not None and not isinstance(head, Node):
            self._head = Node(head)
        else:
            self._head = head

    def __repr__(self):
        return repr([repr(node) for node in self.iter_links()])

    def __str__(self):
        return ','.join(str(node) for node in self.iter_links())

    def __len__(self):
        return sum(1 for _ in self.iter_links())

    def set_head(self, head):
        self._head = head

    def insert(self, node):
        if not isinstance(node, Node):
            node = Node(node)
        node.link_node(self._head)
        self._head = node

    def insert_with_lookup(self, node):
        """
        Inserts a node if the data it contains is not equal to the one
        stored in the the head node.
        """
        if not isinstance(node, Node):
            node = Node(node)
        if node.data != self._head.data:
            self.insert(node)

    def iter_links(self):
        current_node = self._head
        while current_node:
            yield current_node
            current_node = current_node.next_node

linked_list = LinkedList(1)
linked_list.insert(2)
linked_list.insert(3)

rawDescription: using dictionaries and linked list python

description: Using dictionaries and linked list python


rawDescription: Converting a column value when filtering in pandas


code:
vc = df['Series'].value_counts()
u  = [i not in set(vc[vc==1].index) for i in df['Series']]
df = df[u]

rawDescription: Pandas: Delete rows of a DataFrame if total count of a particular column occurs only 1 time


code:
rows, cols = a.shape
new_shape = rows / 2, cols / 2

rawDescription: resize a 2D numpy array excluding NaN

description: Resize a 2D numpy array excluding NaN


code: a = np.array(zip(foo_list, bar_list), dtype=dt)

rawDescription: How to do numpy structural arrays

description: Do numpy structural arrays


code:
def CloseConnection(cnxIn, cursorIn):

    cursorIn.close()

    cnxIn.close

    return

user = input('Enter your user name: ')

user = user.strip()

password = getpass.getpass()

host = input('Enter the host name: ')

host = host.strip()

cnx = mysql.connector.connect(user=user, password=password, host=host)

cursor =  cnx.cursor(buffered=True)

cursor.execute ('select VERSION()')

row = cursor.fetchone()

CloseConnection(cnx, cursor)

rawDescription: general connection to a mysql server

description: General connection to a mysql server


code:
import b
foo = b.foo
del b

rawDescription: What is the scope of python argparse

description: What is the scope of python argparse


code: abc_columns = [col for col in df.columns if str(col).startswith('abc')]

rawDescription: Efficiently creating additional columns in a pandas DataFrame using .map()


code:
from leapyear import leap
leap()

rawDescription: Leap-year program in Python

description: Leap-year program in Python


rawDescription: sorting list of lists Python 2.7

description: Sorting list of lists Python 2.7


code:
b = open ('Filter_Lines.txt','w')
DRIVE = "E:" #windows

with open('filetest') as f:
    for trim in f:
        repl = (re.sub('(' + DRIVE +'.*\\\\)|('+ DRIVE + '.*/)','',trim).rstrip('\n'))
        b.write(repl + '\n')

b.close()

rawDescription: Remove file path with backslash (////) from a text file


code:
from django.http import HttpResponseRedirect

def getting_started_view(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('home_view'))

rawDescription: User flow after registration

description: User flow after registration


code:
False
True

rawDescription: Why don't these two string equal each other?


rawDescription: How to find nearest value that is greater in numpy array?

description: Find nearest value that is greater in numpy array


code:
def todos_lista(lista, guarda):
    return all(guarda(x) for x in lista)

rawDescription: Functional Python with Lists

description: Functional Python with Lists


rawDescription: Subprocess calls are they done in parallel?