code:
from django import template
from django.template.defaultfilters import stringfilter
import logging

register=template.Library()

@register.filter(name='pretty_checkbox')
@stringfilter
def pretty_checkbox(value):
    # Iterate over the HTML fragment, extract <label> and <input> tags, and
    # switch the order of the pairs where the input type is "checkbox".
    scratch = value
    output = ''
    try:
        while True:
            ls = scratch.find('<label')
            if ls > -1:
                le = scratch.find('</label>')
                ins = scratch.find('<input')
                ine = scratch.find('/>', ins)
                # Check whether we're dealing with a checkbox:
                if scratch[ins:ine+2].find(' type="checkbox" ')>-1:
                    # Switch the tags
                    output += scratch[:ls]
                    output += scratch[ins:ine+2]
                    output += scratch[ls:le-1]+scratch[le:le+8]
                else:
                    output += scratch[:ine+2]
                scratch = scratch[ine+2:]
            else:
                output += scratch
                break
    except:
        logging.error("pretty_checkbox caught an exception")
    return output

rawDescription: How do I create a Django form that displays a checkbox label to the right of the checkbox?

description: Create a Django form that displays a checkbox label to the right of the checkbox


code:
from newmodule1 import MyClass1, MyClass2
from newmodule2 import MyClass3

rawDescription: pickle/zodb: how to handle moving .py files with class definitions?

description: Pickle/zodb: how to handle moving .py files with class definitions


code:
from xml.etree import ElementTree as ET
root = ET.fromstring('''\
<root><string>11>2</string></root>''')
root.find('string')
root.find('string').text

rawDescription: Getting Actual String from Python XML parsing


code: {label: values.asList() for label, values in line.searchString(text)}

rawDescription: Accept everything until "more than 1 white space", using pyparsing


code: multidot()

rawDescription: multiplying two huge matrices using numpy.dot

description: Multiplying two huge matrices using numpy.dot


code:
with open('/home/kwal0203/Desktop/Apple.csv', 'a') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow([value.get_text(strip=True).encode("utf-8") for value in revenue])

rawDescription: How to write output of web scrape to column instead of rows in Beautiful Soup

description: Write output of web scrape to column instead of rows in Beautiful Soup


code:
from collections import defaultdict

def count_chars(s):
    res = defaultdict(int)
    for char in s:
        res[char] += 1
    return res

rawDescription: Python: no. of occurences of each character in a string


code:
from operator import itemgetter
first_names = map(itemgetter(0), map(str.split, names))

rawDescription: Best way to split strings

description: Split strings


rawDescription: Pandas: How to apply a function to different columns


code: sum(v[1] for d in myList for v in d.itervalues())

rawDescription: Python List of Dictionaries[int : tuple] Sum


rawDescription: All possible combinations of numbers of length 5 in a 4X4 matrix


rawDescription: How can a class that inherits from list and uses keyword arguments be made to work in both Python 2 and Python 3?


code:
import itertools

i, j = 10, 20
with open(trainFile, 'rt') as csvfile:
    spamreader = csv.reader(itertools.islice(csvfile, i, j+1),
                            delimiter=' ', quotechar='|')
    for row in spamreader:
        print (', '.join(row))

rawDescription: How to loop through specific range of rows with Python csv reader?

description: Loop through specific range of rows with Python csv reader


code:
import sqlite3
import collections

LanguageRecord = collections.namedtuple('LanguageRecord', 'id name creation_date')
def namedtuple_factory(cursor, row):
    return LanguageRecord(*row)

con = sqlite3.connect(":memory:")
con.row_factory = namedtuple_factory
cur = con.cursor()
cur.execute("select 1,2,3")
print(cur.fetchone())

rawDescription: Mapping result rows to namedtuple in python sqlite


code: key = (name, id)

rawDescription: How can I create dictionary within dictionary

description: Create dictionary within dictionary


code:
import numpy as np
data = []
N_x_values, N_y_values = 0, 0
with open(file_name, 'r') as in_file:
    # skip 2 lines, grab N_X, grab N_Y
    [in_file.next() for _ in range(2)]
    N_x_values = int(in_file.next().strip())
    N_y_values = int(in_file.next().strip())

    for line in in_file:
        line = line.strip().split(' ')
        data.append(map(float, line))

data = np.array(data)
data = data.reshape(np.prod(data.shape))
x_cutoff = N_x_values
y_cutoff = N_y_values
x = data[:x_cutoff]
y = data[x_cutoff:y_cutoff]
z = data[y_cutoff:].reshape(N_x_values, N_y_values)

rawDescription: Python reading X and Y values and assigning to Z specific X Y pairs


code:
{'position': u'1.', 'point': u'6', 'team': u'Chievo'}
{'position': u'1.', 'point': u'6', 'team': u'Torino'}
{'position': u'1.', 'point': u'6', 'team': u'Inter'}
{'position': u'1.', 'point': u'6', 'team': u'Sassuolo'}
{'position': u'1.', 'point': u'6', 'team': u'Palermo'}
{'position': u'6.', 'point': u'4', 'team': u'Sampdoria'}
{'position': u'6.', 'point': u'4', 'team': u'Roma'}
{'position': u'8.', 'point': u'3', 'team': u'Atalanta'}
{'position': u'8.', 'point': u'3', 'team': u'Genoa'}
{'position': u'8.', 'point': u'3', 'team': u'Fiorentina'}
{'position': u'8.', 'point': u'3', 'team': u'Udinese'}
{'position': u'8.', 'point': u'3', 'team': u'Milan'}
{'position': u'8.', 'point': u'3', 'team': u'Lazio'}
{'position': u'14.', 'point': u'1', 'team': u'Napoli'}
{'position': u'14.', 'point': u'1', 'team': u'Verona'}
{'position': u'16.', 'point': u'0', 'team': u'Bologna'}
{'position': u'16.', 'point': u'0', 'team': u'Juventus'}
{'position': u'16.', 'point': u'0', 'team': u'Empoli'}
{'position': u'16.', 'point': u'0', 'team': u'Frosinone'}
{'position': u'16.', 'point': u'0', 'team': u'Carpi'}

rawDescription: Scrapy crawled 0 pages

description: Scrapy crawled 0 pages


code: a = [0 for x in range(9)]

rawDescription: Sudoku Neural Network

description: Sudoku Neural Network


code: combos = set(tuple(sorted(item)) for item in combos)

rawDescription: Extracting Unique String Combinations from List of List in Python


code: f = lambda count: [(random() - 0.5, random() - 0.5) for _ in range(count)]

rawDescription: Pythonic way to write a for loop that doesn't use the loop index


code:
def detail(request, product_id):
    p = get_object_or_404(Product, pk=product_id)
    f = QuestionForm()
    return render_to_response('products/detail.html', {
        'title' : p.title,
        'product': p,
        'action': reverse("question", args=[p.pk,]),
        'form' : f},
    context_instance = RequestContext(request))

rawDescription: Pass current product_id to a Model in Django


code:
line = ['The', 'cat', 'chased', 'the', 'dog','the','dog']
from collections import Counter
output = {}
for i, item in enumerate(line):
    print(i, item, len(line))
    if i != len(line) - 1:
        output.setdefault(item.lower(),Counter()).update(Counter({line[i+1]:1}))
print(output)

rawDescription: Making a dictionary for value in a dictionary in Python


code:
Example
it = upload_in_chunks(__file__, 10)
r = requests.post("http://httpbin.org/post", data=IterableToFileAdapter(it))

# pretty print
import json
json.dump(r.json, sys.stdout, indent=4, ensure_ascii=False)

rawDescription: Progress of Python requests post

description: Progress of Python requests post


code:
route = triangle # This will not work, because in python copy is done by reference
route = triangle[:] #This will also not work, because triangle is a list of list
                    #and individual list would be copied with reference

rawDescription: Finding the Maximum Route in a given input


code:
uniq=[]
for i in l:                           # O(n), n being the size of l
    if not (i in uniq or tuple([i[1], i[0], i[2]]) in uniq): # O(n)
            uniq.append(i)                                   # O(1)

uniq

rawDescription: filter out "reversed" duplicated tuples from a list in Python

description: Filter out "reversed" duplicated tuples from a list in Python


rawDescription: How do I serialize a Python dictionary into a string, and then back to a dictionary?

description: Serialize a Python dictionary into a string, and then back to a dictionary


rawDescription: Python: How to evaluate a part of each item in a list, and append matching results?


rawDescription: Vectorized element assignment involving comparisons between matrices in Numpy


code:
def value_to_time(val):
    if val == 'now':
        return -11
    if val.endswith('min'):
        return -11 + int(val[:-3])
    hours, minutes = map(int, val.split(':'))
    return hours * 60 + minutes

sorted(lst, key=value_to_time)

rawDescription: Python - sorting a tuple, characters over numbers


code:
def callback(item):
    phrase = item.split('-')
    first = phrase[0].rjust(3, '0')
    second = ''.join(filter(str.isdigit, phrase[1])).rjust(3, '0')
    word = ''.join(filter(str.isalpha, phrase[1]))
    return first + second + word

rawDescription: Sorting with two digits in string - Python


code:
with open('host.txt', 'r') as inf:
    lines = inf.readlines()
    hostlist = [ln.split() for ln in lines]

rawDescription: Automating SSH using Python

description: Automating SSH using Python


code: {{ daily_obj.total_crores }}

rawDescription: Divide option in django model query

description: Divide option in django model query


code: Data = namedtuple("Data", next(reader))

rawDescription: What is the pythonic way to read CSV file data as rows of namedtuples?


code:
#Add this imports
import StringIO
import base64

@devices_blueprint.route('/devices/test/')
def test():

    img = StringIO.StringIO()
    y = [1,2,3,4,5]
    x = [0,2,1,3,4]

    plt.plot(x,y)
    plt.savefig(img, format='png')
    img.seek(0)

    plot_url = base64.b64encode(img.getvalue())

    return render_template('test.html', plot_url=plot_url)

rawDescription: How to render and return plot to view in flask?

description: Render and return plot to view in flask


code:
from timeit import timeit
# Test 1
test = """
my_list = []
for i in xrange(50):
    my_list.append(0)
"""
timeit(test)
# Test 2
test = """
my_list = []
for i in xrange(50):
    my_list += [0]
"""
timeit(test)
# Test 3
test = "my_list = [0 for i in xrange(50)]"
timeit(test)
# Test 4
test = "my_list = [0] * 50"
timeit(test)

rawDescription: Best and/or fastest way to create lists in python


code:
s='ABABABABABABABABABABABABABABABABABAB'
s.split('AB')
s.split('ABA')
s.split('ABAB')

rawDescription: Boolean expression with strings

description: Boolean expression with strings


code: sshChild.sendline(cmdrun + '\r')

rawDescription: pexpect: Retrieve log from command run over ssh tunnel

description: Pexpect: Retrieve log from command run over ssh tunnel


rawDescription: Python equivalent to "find -type f"

description: Python equivalent to "find -type f"


code:
string = "I see a tall tree outside. A man is under the tall tree"
string.count("tall tree")
string = "The see a stall tree outside. A man is under the tall trees"
string.count("tall tree")
string = "I would like to install treehouses at my yard"
string.count("tall tree")

rawDescription: NLTK count frequency of sub phrase

description: NLTK count frequency of sub phrase


code: df = df.merge(counts, left_on=['full_name'], right_index=True)

rawDescription: Pandas create column containing a row count


code:
# b = g = None
boys = 'Jim','Jeff'
girls = 'Bonnie', 'Buffy'
[(b,g) for b in boys if b[-1] not in g for g in girls]

rawDescription: Positioning of conditional statement within a python list comprehension with multiple iterables


code:
from pyparsing import *

expr   = Forward()
factor = Forward()
term   = Forward()

iand   = Literal("AND").suppress()
ior    = Literal("OR").suppress()
ieq    = Literal("=").suppress()
lpar   = Literal("(").suppress()
rpar   = Literal(")").suppress()
ident  = Word(alphas)
atom   = ident | lpar + expr + rpar

factor << Group(atom + ZeroOrMore(ieq + atom))("equal")
term   << Group(factor + ZeroOrMore(iand + term))("and")
expr   << Group(term  + ZeroOrMore(ior + expr))("or")

rawDescription: Filtering objects matching a given logical formula


code:
from subprocess import check_output

out  = check_output(["python", "2ndpythonscript.py" ,"input_variable" ,"output_variable"])

rawDescription: Calling a python script which has input Fields


rawDescription: Android turn 3 sequence byte[] to int[]

description: Android turn 3 sequence byte[] to int[]


code:
final = [final[index] + reduce(lambda x, y: x + y,
                               list(message[i:i+2] for i in
                                    range(index,
                                          len(message),
                                          2 * len(final))))
         for index in range(len(final))]

rawDescription: Assigning N number of elements from a flat list, itterativly to each member of a matrix


code:
class EnhancedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
    def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None, delay=0, utc=0, maxBytes=0):
        """ This is just a combination of TimedRotatingFileHandler and RotatingFileHandler (adds maxBytes to TimedRotatingFileHandler)  """
        logging.handlers.TimedRotatingFileHandler.__init__(self, filename, when, interval, backupCount, encoding, delay, utc)
        self.maxBytes=maxBytes

    def shouldRollover(self, record):
        """
        Determine if rollover should occur.

        Basically, see if the supplied record would cause the file to exceed
        the size limit we have.

        we are also comparing times
        """
        if self.stream is None:                 # delay was set...
            self.stream = self._open()
        if self.maxBytes > 0:                   # are we rolling over?
            msg = "%s\n" % self.format(record)
            self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature
            if self.stream.tell() + len(msg) >= self.maxBytes:
                return 1
        t = int(time.time())
        if t >= self.rolloverAt:
            return 1
        #print "No need to rollover: %d, %d" % (t, self.rolloverAt)
        return 0

    def doRollover(self):
        """
        do a rollover; in this case, a date/time stamp is appended to the filename
        when the rollover happens.  However, you want the file to be named for the
        start of the interval, not the current time.  If there is a backup count,
        then we have to get a list of matching filenames, sort them and remove
        the one with the oldest suffix.
        """
        if self.stream:
            self.stream.close()
        # get the time that this sequence started at and make it a TimeTuple
        t = self.rolloverAt - self.interval
        if self.utc:
            timeTuple = time.gmtime(t)
        else:
            timeTuple = time.localtime(t)
        dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
        if self.backupCount > 0:
            cnt=1
            dfn2="%s.%03d"%(dfn,cnt)
            while os.path.exists(dfn2):
                dfn2="%s.%03d"%(dfn,cnt)
                cnt+=1
            os.rename(self.baseFilename, dfn2)
            for s in self.getFilesToDelete():
                os.remove(s)
        else:
            if os.path.exists(dfn):
                os.remove(dfn)
            os.rename(self.baseFilename, dfn)
        #print "%s -> %s" % (self.baseFilename, dfn)
        self.mode = 'w'
        self.stream = self._open()
        newRolloverAt = self.computeRollover(currentTime)
        while newRolloverAt <= currentTime:
            newRolloverAt = newRolloverAt + self.interval
        #If DST changes and midnight or weekly rollover, adjust for this.
        if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
            dstAtRollover = time.localtime(newRolloverAt)[-1]
            if dstNow != dstAtRollover:
                if not dstNow:  # DST kicks in before next rollover, so we need to deduct an hour
                    addend = -3600
                else:           # DST bows out before next rollover, so we need to add an hour
                    addend = 3600
        newRolloverAt += addend
        self.rolloverAt = newRolloverAt

    def getFilesToDelete(self):
        """
        Determine the files to delete when rolling over.

        More specific than the earlier method, which just used glob.glob().
        """
        dirName, baseName = os.path.split(self.baseFilename)
        fileNames = os.listdir(dirName)
        result = []
        prefix = baseName + "."
        plen = len(prefix)
        for fileName in fileNames:
            if fileName[:plen] == prefix:
                suffix = fileName[plen:-3]
                if self.extMatch.match(suffix):
                    result.append(os.path.join(dirName, fileName))
        result.sort()
        if len(result) < self.backupCount:
            result = []
        else:
            result = result[:len(result) - self.backupCount]
        return result

rawDescription: The logging.handlers: How to rollover after time or maxBytes?


code:
if cell.is_constant():
    return Constant(cell.const)
else:
    for v in known_variables:
        if self.bindings[v] is cell:
            return v
    else:
        raise CannotSimplify

rawDescription: Pythonic ways to use 'else' in a for loop


code:
for NoOfGamesPlayed in range(NoOfGamesInMatch):
    while NoOfGamesInMatch!=NoOfGamesPlayed:
        PlayerOneWinsGame=(input('Did Player One win the game (enter Y or N)?'))

        # Keep the if/else inside the while loop
        if PlayerOneWinsGame=='Y':
            PlayerOneScore = PlayerOneScore + 1
        else:
            PlayerTwoScore = PlayerTwoScore + 1

rawDescription: Simple Python Program - unsure with While loop


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


code:
mask = ((1 << end) - 1) - ((1 << start) - 1)
result = (number & mask) >> start

rawDescription: Getting a specific group of binary numbers in an Int?


code:
pattern = r'SKART\.analytics\["category"\] = "(\w+)";'
response.xpath('//script[@type="text/javascript+gk-onload"]').re(pattern)

rawDescription: Scrapy and Xpath to extract data from javascript code


code: a

rawDescription: How to extract a list of elements given by their indices from a numpy array efficiently?

description: Extract a list of elements given by their indices from a numpy array efficiently


code:
class amodel(models.Model):
    file = models.FileField(blank=True, null=True)

rawDescription: How to make FileField in django optional?

description: Make FileField in django optional


code:
class DummyObject():
    def __init__(self):
        pass
    def __getattr__(self, name):
        return (lambda *x: None)

logger = logger or DummyObject()

rawDescription: Implementing an optional logger in code

description: Implementing an optional logger in code


rawDescription: List of all available matplotlib backends


code:
def filetimestamp(fullname):
    return os.stat(fullname).st_ctime

rawDescription: Python dealing with dates and times

description: Python dealing with dates and times


code:
import csv
from itertools import islice
with open('file.txt', 'r') as f:
    next(f) # skip header
    r = csv.reader(f, delimiter=" ")
    out = []
    for row in iter(lambda: list(islice(r, 4)),[]):
        out.append(dict((int(r[0]), map(int,r[1:])) for r in row ))

rawDescription: Populating dictionary from text file PYTHON


code:
import sys
unicode_chars = list(map(chr, range(sys.maxunicode+1)))
[x for x in unicode_chars if len(x.lower()) == 0]

rawDescription: Can a string ever get shorter when converted to upper/lowercase?


code:
class Round(models.Model):
    number = models.IntegerField()
    round_type = models.CharField(max_length=1, default="n", choices=CHOICES)
    tournament = models.ForeignKey(Tournament)
    players = models.ManyToManyField(Player, related_name="rounds")
    winner = models.ForeignKey(Player, null=True, related_name="round_winner")

rawDescription: Modelling a swiss tournament in Django

description: Modelling a swiss tournament in Django


code:
from random import randint

number = randint(0, 9)
print("Write will create %d random numbers" % number)

rawDescription: How do i make it say: "Write will create (random number goes here) random numbers

description: Make it say: "Write will create (random number goes here) random numbers


code:
association_table = db.Table('association',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('friend_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True)
    password = db.Column(db.String(30))
    email = db.Column(db.String(45), unique=True)
    friends = db.relationship("User",
                secondary=association_table,
                backref='added_by',
                primaryjoin=id == association_table.c.user_id,
                secondaryjoin=id == association_table.c.friend_id)

rawDescription: Adding data to related table with SQLAlchemy


code:
st="Does this text contain hits or matches"
re.findall(r'[this]{4}', st)

rawDescription: Python Regex: set combinations of prefix length


code: url(r'^test/getFile', 'getFile')

rawDescription: generating a file with django to download with javascript/jQuery

description: Generating a file with django to download with javascript/jQuery


rawDescription: set the value of a django HiddenInput widget to another object's id rendered in the template

description: Set the value of a django HiddenInput widget to another object's id rendered in the template


code: part1, part2 = foo.rsplit('_', 1)

rawDescription: Splitting string with multiple delimiters in python


code:
while True:
    self.check_pause()
    if self.pause:
        continue
    # Main loop of program goes here.

rawDescription: Python: interrupt execution with key and run again


code:
from pathlib import Path
Path(r'c:\python34\lib').resolve()
str(Path(r'c:\python34\lib').resolve())

rawDescription: How can I get the proper capitalization for a path?

description: Get the proper capitalization for a path


code:
dict((k, n / float(len(unique_items))) \
    for (k, n) in zip(unique_items, num_appearances))

rawDescription: how to calculate ratio on some condition in pandas dataframe

description: Calculate ratio on some condition in pandas dataframe


code: line = "TROGA_"+line.split("_", 1)[1]

rawDescription: Replace part of a matched string in python


code:
import numpy as np

H, W = 5, 5
x = np.add.accumulate(np.random.randint(-1, 2, size=(H,1)), axis=0)
y = np.add.accumulate(np.random.randint(-1, 2, size=(1,W)), axis=1)
out = x + y
print(out)

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


code:
print(["please print my variable", x, " and another:", y])
print([x])

rawDescription: Why would Python's variable length arguments be used over passing in a list/dictionary?


rawDescription: extract info from a string

description: Extract info from a string


code: ModelX.objects.raw("""SELECT DISTINCT ....... FROM x WINDOW w .....""")

rawDescription: Limit queryset results based on model field, are there better ways?


rawDescription: Numpy: Convert values in a 1-D array based upon dictionary


rawDescription: Merge multiple dataframes with non-unique indices


code:
from enum import Enum

class Planet(Enum):
    MERCURY = (3.303e+23, 2.4397e6)
    VENUS   = (4.869e+24, 6.0518e6)
    EARTH   = (5.976e+24, 6.37814e6)
    MARS    = (6.421e+23, 3.3972e6)
    JUPITER = (1.9e+27,   7.1492e7)
    SATURN  = (5.688e+26, 6.0268e7)
    URANUS  = (8.686e+25, 2.5559e7)
    NEPTUNE = (1.024e+26, 2.4746e7)

    # universal gravitational constant
    G = Constant(6.67300E-11)

    def __init__(self, mass, radius):
        self.mass = mass       # in kilograms
        self.radius = radius   # in meters
    @property
    def surface_gravity(self):
        return self.G * self.mass / (self.radius * self.radius)

print(Planet.__dict__['G'])             # Constant(6.673e-11)
print(Planet.G)                         # 6.673e-11
print(Planet.NEPTUNE.G)                 # 6.673e-11
print(Planet.SATURN.surface_gravity)    # 10.44978014597121

rawDescription: Is it possible to define a class constant inside an Enum?


rawDescription: Tuple type content python

description: Tuple type content python


code:
def combinations(list1, list2):
    return ([opt1, opt2, opt3]
            for i,opt1 in enumerate(list1)
            for opt2 in list1[i+1:]
            for opt3 in list2)

rawDescription: Testing all combinations in Python

description: Testing all combinations in Python


code:
def input(a, b, c) :
    m = min(a,b,c)
    M = max(a,b,c)
    return a+b+c-m-M

rawDescription: Middle value using python 3

description: Middle value using python 3


code:
pants = []
pants.append(Leather_Pants(NPC))
pants.append(Leather_Pants(chests[5]))
pants[1].pickup(PC)

rawDescription: Creating dynamic variables for a class from within the class


code:
from crypt import crypt
crypt("abcdefg","aa")

rawDescription: What is Go's equivalent to Python's crypt.crypt?


code:
@property
def Teacher(self):
    return self.Class.Teacher

rawDescription: Get attribute of object from relationship in sqlalchemy


code:
for i, val in enumerate(lst):
    if text in val:
        desired = [ lst[ j%n] for j in range(i+1, i+1+x)]

rawDescription: Iterate through a List Multiple times Cyclically starting from the Matching Index


code:
import urllib3, certifi
http = urllib3.PoolManager(ca_certs=certifi.where())
html = http.request('GET', url).read()
soup = BeautifulSoup(html, "html5lib")

rawDescription: What is the practical difference between these two ways of making web connections in Python?


code:
from main import socketio

@socketio.on('connect', namespace='/namespaceOne')
def test_connectOne():
    print('new connection')

@socketio.on('connect', namespace='/namespaceTwo')
def test_connectTwo():
    print('new connection')

rawDescription: How to handle dynamic decorators in python easily?

description: Handle dynamic decorators in python easily


code:
r1 = re.compile(r'SO ON')
r2 = re.compile(r'WHATEVER AND (%s)*' % r1.pattern)

rawDescription: Nested Regular Expression in Python for

description: Nested Regular Expression in Python for


code:
import yaml
yaml.safe_dump({'items': ['test', 'test2']}, default_flow_style=False)
yaml.safe_dump({'items': ['test', 'test2']})

rawDescription: How can I print [] without string in Python in YAML file

description: Print [] without string in Python in YAML file


rawDescription: List conversion/transformation

description: List conversion/transformation


rawDescription: How to add column to numpy array

description: Add column to numpy array


code: print(dict(character=count))

rawDescription: Is there a way to export data from a Counter object to a CSV file?


code:
word = input("\nPlease enter a word : ")
length = 1
pos = 0

for i in range(length, len(word)):
    for j in range(pos, len(word)):
        print (j)
        print (i+j)
        print(word[j:i+j])
        print ("------------")

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


code:
xx = x[..., None, :]
yy = y[..., None, :]
np.concatenate((xx, yy, xx, yy), axis=2).shape
np.concatenate((xx, yy, xx, yy), axis=2)

rawDescription: "stacking" arrays in a new dimension?

description: "stacking" arrays in a new dimension


code:
date = datetime.date(2016, 8, 21)
date.strftime('%d/%m/%Y')

rawDescription: Python3 convert Julian date to standard date


rawDescription: Fetching a IP from text file using python


code:
class LevelMap():
    def __init__(self, level_array=tilemap):
        self.level_array = level_array

        # Go through every row in the map...
        for row in range(MAPHEIGHT):
            # ... and every column...
            for column in range(MAPWIDTH):
                # ...and make a square at that location.
                Square(row, column, tilemap[row][column])

map = LevelMap(level_array=[])
# change the tile at (0, 1) to rocky:
map.level_array[1][0].change_terrain_to("rocky")

rawDescription: Assigning unique names to each square in a game map


code:
def remove_employee(self, employee_id):
    for employee in self._employees:
        if employee.get_employee_id() == employee_id:
            self._employees.remove(employee)

rawDescription: Search a list containing class objects and remove the class object that matches an instance variable of class object


code: node *= factor

rawDescription: Python: Changing Values in a Dictionary Tree Structure


code:
from pandas import DataFrame
df = DataFrame({"first": ["John", "Jane"], "last": ["Smith", "Jones"]})
df
df["first"] + " " + df["last"]

rawDescription: How can we join two columns of a numpy array into a single column, separating the values by a space?


code:
border_threshold_R = 4
border_threshold_G = 4
border_threshold_B = 4

mid_pixels = []
top_border_height = 0
bottom_border_height = 0

rawDescription: Detect if image has border using PIL

description: Detect if image has border using PIL


rawDescription: cmap to rgba in Matplotlib

description: Cmap to rgba in Matplotlib


code:
from itertools import tee, islice, izip_longest
def get_next(some_iterable, window=1):
    items, nexts = tee(some_iterable, 2)
    nexts = islice(nexts, window, None)
    return izip_longest(items, nexts)

rawDescription: Python for-loop look-ahead

description: Python for-loop look-ahead


code:
import uuid
my_uuid = uuid.uuid4()
my_uuid
str(my_uuid)

rawDescription: Django package to generate random alphanumeric string


code: next(x for x in lst if ...)

rawDescription: Python: Find in list

description: Python: Find in list


code:
class Test(object):
    def __repr__(self):
        repr_template = ("<{0.__class__.__module__}.{0.__class__.__name__}"
                         " object at {1}: name={0.name}, isValid={0.isValid}>")

        return repr_template.format(self, hex(id(self)))

rawDescription: Extending __str__() rather than replacing it


code:
class ViewAB(object):
    pass

sqlalchemy.orm.mapper(ViewAB, ab_view_sel)

rawDescription: Mapping a 'fake' object in SQLAlchemy

description: Mapping a 'fake' object in SQLAlchemy


code:
class DB():
    def __init__(self,database_name):
        db = MySQLdb.connect('localhost', 'user', 'pswrd', database_name)
        self.cur = db.cursor()

    def lookup_value(self,user_name):
        query = "SELECT COUNT(*) FROM x_user_%s"
        self.cur.execute(query, (user_name,))
        self.result = self.cur.fetchone()
        return self.result

rawDescription: How do I use a MySQLdb connect object on imported function

description: Use a MySQLdb connect object on imported function


rawDescription: Add zeros to a float after the decimal point in Python


code:
import linecache

w = 'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'
l = linecache.getline("Aberdeen2005.txt",5)
m = [d in l for d in w]
c = '2005','2016' # years (optional)

if any(y in l for y in c): # check for years (optional)

    if any(x in l for x in w):
        r = [i for i,v in enumerate(m,0) if v]
        l = l.replace(' '+w[r[0]],'')

    with open("dates.txt", "a") as article_dates:
        article_dates.write(l)

linecache.clearcache()

rawDescription: Date list in text

description: Date list in text


code: rddData = rddData.repartition(200)

rawDescription: Dataproc Pyspark job only running on one node


code:
import matplotlib.pyplot as plt
import csv

rawDescription: Plot large data in the specified format using python


code:
for comb in itertools.combinations(lists, n):
    print(comb)

rawDescription: How to generate a permutation of list of lists in python

description: Generate a permutation of list of lists in python


code:
p in 'blablafoo+*bar123'
'foo+*bar foo+*bar'.count(p)

rawDescription: How to escape special regex characters in a string?

description: Escape special regex characters in a string


code:
def average_column (csv):
    f = open(csv,"r")
    average = 0
    Sum = 0
    row_count = 0
    for row in f:
        for column in row.split(','):
            n=float(column)
            Sum += n
        row_count += 1
    average = Sum / len(column)
    f.close()
    return 'The average is:', average

rawDescription: Python - Calculate average for every column in a csv file


rawDescription: How to use index as a key in Python?

description: Use index as a key in Python


rawDescription: Merge multiple lists of dictionaries and rename the key


code:
dates, vals = zip(*data)
s = pd.Series(vals, index=dates)

rawDescription: python key value list to panda series

description: Python key value list to panda series


code:
import urlparse
from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.selector import HtmlXPathSelector
from TOSpider.items import TOSpiderItem

class MySpider(BaseSpider):
    name = "TOSpider"
    allowed_domains = ["http://nowtoronto.com/"]
    start_urls = ["http://www.nowtoronto.com/music/listings/"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        listings = hxs.select("//div[starts-with(@class, 'listing-item')]")

        for listing in listings:
            item = NowTorontoItem()
            item["eventArtist"] = listing.select("span[@class='listing-body']/div[@class='List-Body']/span[@class='List-Name']/text()").extract()
            item["eventTitle"] = listing.select("span[@class='listing-body']/div[@class='List-Body']/span[@class='List-Body-Emphasis']/text()").extract()
            item["eventHolder"] = listing.select("span[@class='listing-body']/div[@class='List-Body']/span[@class='List-Body-Strong']/text()").extract()
            item["eventDetails"] = listing.select("span[@class='listing-body']/div[@class='List-Body']/text()").extract()

            # instead of returning all items at the end,
            # you can use yield with an item in each iteration
            yield item

            # and you can also yield a Request()
            # so that scrapy enqueues a new page to fetch
            detail_url = listing.select("div[@class='listing-readmore']/a/@href")
            if detail_url:
                yield Request(detail_url.extract()[0], callback=self.parse_details)

    def parse_details(self, response):
        hxs = HtmlXPathSelector(response)
        # and here you parse
        # ,
        # ,
        # ,
        # ,
        # ,
        # ,
        #  and  ...
        #
        # and return a item

rawDescription: Increasing the functionality of my Scrapy spider - Following internal links


rawDescription: python numpy left join recarray with duplicated key value

description: Python numpy left join recarray with duplicated key value


code:
myDict["Objective A"] = MyClass.FuncA
myDict["Objective B"] = MyClass.FuncB

rawDescription: How can I associate dictionary keys with functions?

description: Associate dictionary keys with functions


code:
def get_queryset(self):
    query_set = super(WorkoutList, self).get_queryset()

rawDescription: unbound method get_queryset() must be called with WorkoutList instance as first argument (got nothing instead)

description: Unbound method get_queryset() must be called with WorkoutList instance as first argument (got nothing instead)


rawDescription: trouble extracting elements to list from string

description: Trouble extracting elements to list from string


rawDescription: How to enforce GET request using urllib.urlopen?

description: Enforce GET request using urllib.urlopen


rawDescription: How can I use boto to stream a file out of Amazon S3 to Rackspace Cloudfiles?

description: Use boto to stream a file out of Amazon S3 to Rackspace Cloudfiles


code:
page = models.Page.load(title)

if request.GET.get('rev'):
  query = db.Query(models.Revision)
  query.filter('name =', title).order('created')
  rev = request.GET.get('rev')
  rev_page = query.fetch(1, int(rev))
  page.content = rev_page.content

rawDescription: Storing wiki revisions on Google App Engine/Django - Modifying This Existing Code


rawDescription: Double loops for "concatenation of subarrays in bigger array"


code: a = list(r)

rawDescription: Splitting a string into a list

description: Splitting a string into a list


code:
pastpresent = np.array([[0, 2], [0, 6]])
nlayers = 10

rawDescription: Slicing different rows of a numpy array differently


code:
import random

# int
x = random.randint(0, 1)  # 0 or 1(both incl.)

# float excl. 1.0
x = random.random()  # float from [0,1)

rawDescription: How do I generate random numbers from [0,1]?

description: Generate random numbers from [0,1]


code:
f = open('yourcsv.csv', mode='r')

content = f.readlines()

rawDescription: Python clustering from .csv file as input


code:
from collections import OrderedDict

results = OrderedDict

with open('somefile.txt') as f:
   for line in f:
      line = line.strip()
      if line:
         value, key = line.split(',')
         key = key.split('_')[0] # returns var1 from var1_val1
         results.setdefault(key, []).append(value)

for k,v in results.iteritems():
    print('{} {}'.format(k, ' '.join(v)))

rawDescription: Iterating through file multiple times (Python)


code:
from collections import defaultdict
import urllib
import urlparse

# parse the url into parts
parsed = urlparse.urlparse('http://somesite.com/blog/posting/?id=6&name=Bill')

# and parse the query string into a dictionary
qs = urlparse.parse_qs(parsed.query, keep_blank_values=0, strict_parsing=0)

# this makes a new dictionary, with same keys, but all values changed to "foobar"
foozsified = { i: 'foobar' for i in qs }

# make them back to a query string: id=foobar&name=foobar
quoted = urllib.urlencode(foozsified, doseq=True)

# the original parsed result is a named tuple and cannot be changed,
# make it into a list
parsed = list(parsed)

# replace the 4th element - the query string with our new
parsed[4] = quoted

# and unparse it into a full url
print(urlparse.urlunparse(parsed))

rawDescription: Use urlparse library to iterate through url param


code:
for index, question in enumerate(questions):
    print ("Question {}: ".format(index+1))
    print (question)
    #asks for the answer from the user
    ans = int(input())
    #compares the users input to the answer
    if ans == eval(question):
        print ("Well done, you got it correct")
        #if correct grants a point to the overall score
        score = score + 1

rawDescription: How could I loop a code involving a list


rawDescription: Create new pandas timeseries dataframe from other dataframe


code:
class MyModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = self.model.all_objects.get_queryset()
        ordering = self.get_ordering(request)
        if ordering:
            qs = qs.order_by(*ordering)
        return qs

rawDescription: In Django, how do I gracefully add a queryset filter to a large group or all members of an object?


code:
def addword(theIndex, word, pagenumber):
    try:
        theIndex[word].append(pagenumber)
    except KeyError:
        theIndex[word] = [pagenumber]

rawDescription: python backports for some methods

description: Python backports for some methods


code:
dicMyDictionary = {"michael":"jordan", "kobe":"bryant", "lebron":"james"}
print(dicMyDictionary)

rawDescription: Dictionary all for one

description: Dictionary all for one


code:
import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

rawDescription: Is there any way to kill a Thread in Python?


rawDescription: How to capture query string parameter in form view?

description: Capture query string parameter in form view


code:
ss = str(lesk(sent, 'be', 'v'))
re.findall("'([^']*)'",ss)

rawDescription: I am having problems doing Word Sense Disambiguation in Python using Lesk algorithm


code:
a = A()
# First let's try simple access (no method call)
a.real_method # The method that is actually defined in the class
a.imaginary_method # Some method that is not defined
# Now let's try to call each of these methods
a.real_method(1, 2, x=3, y=4)
a.imaginary_method(1, 2, x=3, y=4)
# Now let's try to access the x attribute, just to make sure that 'regular' attribute access works fine as well
a.x

rawDescription: Instance of Python class that responds to all method calls


code: buffer.writelines(line + '\n' for line in mylist)

rawDescription: Is there a simple way to make lists behave as files (with ftplib)


code:
MEDIA_URL = 'https://bucket-name.s3.amazonaws.com/media/'
STATIC_URL = 'https://bucket-name.s3.amazonaws.com/static/'

rawDescription: Proper way to handle static files and templates for Django on Heroku


code: x['eggs'] if 'eggs' in x else x.get('spam')

rawDescription: Is there something better than dict.get(<thing>, dict.get(<other>))?


rawDescription: Datetime and Timestamp equality in Python and Pandas


rawDescription: PyQt4 : How can i toggle the "Stay On Top" behavior?


code:
import random

sequences = []
order = [1, 0] * 10

while len(sequences) < 10:
    random.shuffle(order)

    if order in sequences:
        continue

    sequences.append(order[:])

rawDescription: Limit the number of repeats in pseudo random python list


rawDescription: Most efficient way to create a dictionary of empty lists in Python?


code:
activity.shape == (len(vertices) // 3,)
start_colors.shape == (3,)
end_colors.shape == (3,)

rawDescription: fastest way to iterate in python

description: Fastest way to iterate in python


code:
import itertools

def everywhere(seq, width):
    for locs in itertools.product(range(width), repeat=len(seq)):
        output = [[] for _ in range(width)]
        for elem, loc in zip(seq, locs):
            output[loc].append(elem)
        yield output

rawDescription: How to bin all subsets of a python list into n bins

description: Bin all subsets of a python list into n bins


code:
def decorator(arg):
    def wrap(klass): ...
    return wrap

rawDescription: How to add parameters to Django class based generic view decorators?

description: Add parameters to Django class based generic view decorators


code:
x = np.arange(1,11)
x
width = .5
x + width/2

rawDescription: Plotting bar chart in python

description: Plotting bar chart in python


rawDescription: why python requires us to use from statement when we have already loaded a module using import

description: Why python requires us to use from statement when we have already loaded a module using import


code:
class AttrDict(dict):
    def __init__(self, *args, **kw):
        super(AttrDict, self).__init__(*args, **kw)
        self.__dict__ = self

foo = AttrDict()
foo.bar = 'baz'
foo
foo.bar

rawDescription: Using Python to create a dictionary with setters and getters


code:
def next_string(s):
    if len(s) == 0:
        return '1'
    head = s[0:-1]
    tail = s[-1]
    if tail == 'Z':
        return next_string(head) + '1'
    if tail == '9':
        return head+'A'
    if tail == 'H':
        return head+'J'
    if tail == 'N':
        return head+'P'
    return head + chr(ord(tail)+1)

rawDescription: Python: Alphanumeric Serial Number with some rules


code:
import argparse

class MappedParser(argparse.ArgumentParser):
    mapping = {} #backup if you don't use def_mapping

    def def_mapping(self,**options):
        self.mapping = options

    def parse_args(self,args=None,namespace=None):
        result = argparse.ArgumentParser.parse_args(self,args,namespace)
        for name,options in self.mapping.items(): #by default this is is empty so the loop is skipped
            if name in result:
                key = getattr(result,name)
                if key in options:
                    replace_with = options[key]
                    setattr(result,name,replace_with)
                else:
                    self.error("option {name!r} got invalid value: {key!r}\n must be one of {valid}".format(name=name,key=key,valid=tuple(options.keys())))
                    return #error should exit program but I'll leave this just to be safe.
        return result

rawDescription: argparse: map user input to defined constant

description: Argparse: map user input to defined constant


code:
def startbars(query_name, commodity_name):

    assert query_name in INNOVOTABLE_FIELD_NAMES

    ## TODO: Replace with proper SQL query
    query = """ SELECT wbcode, Year, """+query_name+"""
             FROM innovotable WHERE commodity='"""+commodity_name+"""' and

             """+query_name+""" != 'NULL' """
    rows = cursor.execute(query)

    mapYearToWbcodeToField = {}
    nc = []
    global h_list
    h_list = {}

    for row in rows:
        n = float(row[2])
        wbCodeToField = mapYearToWbcodeToField.setdefault(int(row[1]),{})
        wbCodeToField[str(row[0])] = n
        nc.append(n)

    constant = 8.0 / max(nc)

    for (an_year,wbCodeToField) in mapYearToWbcodeToField.iteritems():
        if an_year < 1961 or an_year > 2031:
            continue

        for (wbCode,value) in wbCodeToField.iteritems():
            if wbCode not in result:
                continue

            skey = wbCode+str(an_year)
            h_list[skey] = constant * value

rawDescription: Optimize two simple nested loops

description: Optimize two simple nested loops


code:
def readFile(fileName, keys):
    result = {}
    class_ = ''
    with open(fileName, "rb") as opened_infile_A:
        for line in opened_infile_A:
            items = line.split()
            class_, feat, value = items[:3]
            keys.add(feat)
            result[feat] = float(value)
    return (class_, result)

def sumVectors(classB_infile, classA_infile, outfile):
    keys = set()

    classA, class_dictA = readFile(classA_infile, keys)
    classB, class_dictB = readFile(classB_infile, keys)

    with open(outfile, "wb") as output_file:
        for key in keys:
            weightA = class_dictA[key] if key in class_dictA else 0
            weightB = class_dictB[key] if key in class_dictB else 0
            weight = weightA + weightB
            outstring = "\t".join([classA + "-" +  classB, key, str(weight)])
            output_file.write(outstring + "\n")

rawDescription: summing vectors in Python

description: Summing vectors in Python


code:
stringA, stringB = 'abcdefg', 'hijklmn'
not set(stringA).isdisjoint(stringB)
stringA, stringB = 'dog', 'abcdefg'
not set(stringA).isdisjoint(stringB)

rawDescription: Doing "if string a contains any letter in string b" with Python


code:
a=str(raw_input('Enter The String To revers'))
lst.append(a) #adding input to a list in each iteration

rawDescription: enter n numbers to control the enter of the map or array

description: Enter n numbers to control the enter of the map or array


code:
class Info(object):
    @property
    def version(self):
        return 3
    def __getitem__(self,key):
        if hasattr(self,key.lower()):
            return getattr(self,key.lower())

rawDescription: Python decorator class to transform methods to dictionary items


code:
#!/usr/bin/python

import argparse

def run(p):

    """ Execute base on the arguments """
    if p.get('create', False) is True:
        # do something
        return True

    elif p.get('find', False) is True:
        # do something
        return True
    else:
        return False

def main():

    parser = argparse.ArgumentParser(prog='ipush',
                   description='Utility to push the last commit and email the color diff')
    parser.add_argument('--find', action="store_true",
                       help="find the user details")
    parser.add_argument('--create', action='store_true',
                       help="creating the database")

    p = parser.parse_args()

    argument = vars(p)

    if run(argument) is False:
        parser.print_usage()

if __name__ == '__main__':
    main()

rawDescription: accessing ArgumentParser variable with environment variable

description: Accessing ArgumentParser variable with environment variable


rawDescription: binary to hex dictionary

description: Binary to hex dictionary


code:
import numpy as np
dx = 2.
dy = 2.
N = 5
centers = np.mgrid[dx/2:N*dx:dx, dy/2:N*dy:dy]

rawDescription: Dividing a square into N smaller squares and finding center coordinates of the N smaller squares


code:
for i, item in enumerate(cl):
    if item.get_xdata().mean()>0:
        bp[0].text(item.get_xdata().mean(), item.get_ydata().mean(), str(i), va='center', ha='center')

rawDescription: Styling of Pandas groupby boxplots

description: Styling of Pandas groupby boxplots


code:
if M>0:
    number1 = Fibo(M-1)
    number0 = Fibo(M)

rawDescription: python - High time consumption and low efficiency in programming challenge

description: Python - High time consumption and low efficiency in programming challenge


code:
b_row, b_col = np.vstack([np.unravel_index(b, A.shape) for b in B]).T
A[b_row, b_col] = 0
A

rawDescription: Python: multidimensional array masking

description: Python: multidimensional array masking


code: count = random_list.count(9)

rawDescription: If there any way to add this code to a function?


code: product_list = db.GqlQuery("SELECT * FROM Post")

rawDescription: templating in python with GAE using GQL

description: Templating in python with GAE using GQL


rawDescription: Assigning the same value to different positions in a list in python


rawDescription: Turning a list of dictionaries into a list of lists


code:
def write_data_to_file(filename, data):
    myfile = open(filename,'a')
    myfile.write(repr(data))
    myfile.write('\n')
    myfile.close()

rawDescription: If I have three different text file how do I read them then sort them by average?


code:
for link in soup.find_all("a", class_ = "img-link"):
    for img in link.find_all("a", src=True):  # searching for img with src attribute
        print(img["src"])

rawDescription: BeatifulSoup HTML getting src link

description: BeatifulSoup HTML getting src link


code:
for attr in ('description', 'title', 'etc'):
    setattr(book, attr, None)
book.save()

rawDescription: Delete Multiple Django Model Attributes

description: Delete Multiple Django Model Attributes


code: zip(A, B)

rawDescription: Compare List with different number of items


code: image *= 255.0/image.max()    # Uses 1 division and image.size multiplications

rawDescription: How to normalize a NumPy array to within a certain range?

description: Normalize a NumPy array to within a certain range


code: import wx

rawDescription: Can we change background color of checkbox text in WxPython?


code:
from itertools import chain
s =  [8,2,0,1]
s1 = sorted(s)
list(chain(*(((x,y),(y,x)) for (x,y) in zip(s1, s1[1:]) if y-x == 1)))

rawDescription: How to iterate each element in list with all the others

description: Iterate each element in list with all the others


rawDescription: Eliminating series of .replace() calls in Python


rawDescription: Creating your own contour in opencv using python


code: [dict(i) for i in i_set - a_set]

rawDescription: Finding difference between two list of dictionary in Python


code:
A
B

rawDescription: Limit which classes in a .py file are importable from elsewhere


code:
class MIMEUTF8QPText(email.mime.nonmultipart.MIMENonMultipart):
  def __init__(self, payload):
    email.mime.nonmultipart.MIMENonMultipart.__init__(self, 'text', 'plain',
                                                      charset='utf-8')

    utf8qp=email.charset.Charset('utf-8')
    utf8qp.body_encoding=email.charset.QP

    self.set_payload(payload, charset=utf8qp)

rawDescription: Encode MIMEText as quoted printables

description: Encode MIMEText as quoted printables


rawDescription: Equivalent of os.getpardir()?

description: Equivalent of os.getpardir()


rawDescription: Python - finding same elements in three lists (ignoring empty list)


code:
re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)

rawDescription: Case insensitive Python regular expression without re.compile


code:
from django.db.models import F, Max

destroyedStatus = Status.objects.get(description="destroyed")
clients_destroyed_items = StorageItem.objects.annotate(
    last_change_date=Max("itemstatushistory__date")).filter(client=client,
    itemstatushistory__status=destroyedStatus,
    itemstatushistory__date=F("last_change_date"))

rawDescription: Query for items using filter for most recent entry in a related table


code:
WWWW
2
77777
54
M
888
90
6.7
100
No
yyy
kk
888
zz
F
too
yy
8.8
123
xxx
yyy
pp

rawDescription: How do I align data vertically in python?

description: Align data vertically in python


code:
from scapy.all import *

def packet_handler(pkt) :
    # if packet has 802.11 layer, and type of packet is Data frame
    if pkt.haslayer(Dot11) and pkt.type == 2:
            # do your stuff here
            print(pkt.show())

sniff(iface="mon0", prn=packet_handler)

rawDescription: Wireless Data Packet Capturing with help of scapy


code:
{country for country, timezones in country_timezones.items()
 if timezone in timezones}

rawDescription: How to convert timezone to country code in Python?

description: Convert timezone to country code in Python


rawDescription: Flattening nested loops / decreasing complexity - complementary pairs counting algorithm


code:
l = ['db6ad7246abf74cb845baa60e6fe45dacf897612    HEAD',
     '1fc347b17201054d8b5b9593efc1925918f04940    refs/heads/develop',
     '63b1a5b5901250651a162814b085c88c96835e3a    refs/heads/feature-dm',
     '8d72969f3b1ef5b16792b1cca5c65262d78b8dc2    refs/heads/feature/breedtest',
     '0ca9346d1f5b46f77f41a89aeb11998cbb83c007    refs/heads/feature/fedortest',
     '147bea618187c11927bfe83f1d8b52591f3b734c    refs/heads/feature/frontend-autumn14',
     'd5e5d4d75dddd46a5068ca621ce8e74e68bdca4e    refs/heads/feature/socket-testing',
     '03e70c846a84688ccbf78ca1159f410e577e1ee5    refs/heads/feature/youtracktest',
     'db6ad7246abf74cb845baa60e6fe45dacf897612    refs/heads/master',
     '787580497c0b41ca040c60bd7906ab598f891a43    refs/heads/master-old',
     '33a553135eb4341046702adaa762791b38456daf    refs/pull/67/head',
     '10c4c172ba0479dac8eefba674395d09d9d4b061    refs/pull/67/merge']

rawDescription: What is the most pythonic way to extract branch names from a remote-ls list?


rawDescription: timedelta csv pandas

description: Timedelta csv pandas


code:
from itertools import takewhile, izip_longest
from operator import itemgetter
a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
c = [10, 11, 12]
somezip(a,b)
somezip(a,c)
somezip(b,c)

rawDescription: Is there a middle ground between `zip` and `zip_longest`


rawDescription: Python class global not set

description: Python class global not set


code:
alpha = 2.0
a0 = np.array([1, 2, 3, 4])
n = 5
a0 * (alpha**np.arange(n).reshape(-1, 1))

rawDescription: Trying to vectorize iterative calculation with numpy


code:
from distutils.core import setup
import py2exe

setup(console=['hello.py'])

rawDescription: I need a stand alone python interpreter/compiler!


code:
l = [['F', 'G', 'C'], ['S', '3', '7'], ['C', '3', 'D']]
[[item for item in sublist if not item.isdigit()] for sublist in l]

rawDescription: Python, remove all numbers from sublist

description: Python, remove all numbers from sublist


code:
handle = Entrez.efetch(db="nucleotide", id=key, retmode="xml") # retmode as 'xml' , db='nucleotide'
features = Entrez.read(handle)[0]
sequence = features['GBSeq_sequence'] # this is your sequence!

rawDescription: Access sequence element from fasta record using Biopython Entrez


code: x = [set(a) for a in x]

rawDescription: Python set Union and set Intersection operate differently?


code:
def create_grid(grid):
    y = 0
    size = LENGTH * WIDTH
    table = ''
    while y < size:
        table += '|'.join(grid[y:y+WIDTH]) + '\n'
        y += WIDTH

    return table

rawDescription: Python: Using two while loops to create grid. No for loops


code:
import csv
from pathlib import Path

HERE = Path(__file__).parent
DATA_PATH = HERE / '../data/test.csv'

with DATA_PATH.open('rU') as file_in:
    log=csv.reader(file_in, delimiter='\xfe', quotechar="'")
    for row in log:
        print(row)

rawDescription: Python csv new line character in field

description: Python csv new line character in field


code:
for name in names_list:
  def update(name):
    names_objs[name].update_value(2)
  events2.push(partial(update, name))

rawDescription: Passing objects around an event queue in Python


code:
class quantizer:
    def __init__(self, total, limit):
        self.total = total
        self.limit = limit
        self.index = float(0)
        self.step = float(total) / float(limit)
    def __iter__(self):
        return self
    def next(self):
        if self.index >= self.total:
            raise StopIteration
        result = int(round(self.index))
        self.index += self.step
        return result

rawDescription: bash evenly choose 10 numbers

description: Bash evenly choose 10 numbers


rawDescription: numpys argsort, sorting column based on another one

description: Numpys argsort, sorting column based on another one


code:
mapTree = {
    'number': lambda x: x**x,
    'string': lambda x: x[1:]
}
otype = 'number'
mapTree[otype](2)
otype = 'string'
mapTree[otype]('foo')

rawDescription: What does "lambda" mean in Python, and what's the simplest way to use it?


code:
@reversable
def my_decorator(f):
    def wrapper(x):
        return f(x + 1)
    return wrapper

rawDescription: Is it possible to use reflection to examine a function's decorators in Python 2.5?


code:
exp2 = re.compile(exp)
unmatched = []
prev_match_end = 0
for match in exp2.finditer(s):
    unmatched.append(s[prev_match_end: match.start()])
    prev_match_end = match.end()

# Deal with unmatched text after last match:
unmatched.append(s[prev_match_end:])

rawDescription: retrieving substrings which are not matched by re.findall

description: Retrieving substrings which are not matched by re.findall


code:
def get_cyclics(p, k):
  found = set()      # set of tuples we have seen so far
  todo = [tuple(p)]  # list of tuples we still need to explore
  n = len(p)
  while todo:
    x = todo.pop()
    for i in range(n - k + 1):
      perm = ( x[:i]                    # Prefix
             + x[i+1:i+k] + x[i:i+1]    # Rotated middle
             + x[i+k:]                  # Suffix
             )
      if perm not in found:
        found.add(perm)
        todo.append(perm)
  for x in found:
    print(x)

rawDescription: Generate all permutations of cyclic shift of length K in a list of length N efficiently


code:
plt.draw() # you need this to get the edge color
lines = np.array(surf2.get_edgecolor())
surf2.set_edgecolor(lines*np.array([0,0,0,0])+1) # make lines white, and keep alpha==1. It's an array of colors like this: [r,g,b,alpha]

rawDescription: Applying colormaps to custom axis in Matplotlib 3D surface


code:
for sprite in sprites:
    sprite.timer = pygame.Clock()

rawDescription: Pygame sprites timer

description: Pygame sprites timer


rawDescription: Drop values below group means with Pandas DataFrame


rawDescription: How do you sort multiple columns of a CSV file using python?

description: Sort multiple columns of a CSV file using python


code:
def staticroot(debug=False):
    root = my_domain_map[cherrypy.request.headers['Host']]
    cherrypy.request.toolmaps['tools']['staticdir']['root'] = root
cherrypy.tools.staticroot = cherrypy.Tool(
    staticroot, point='before_handler', priority=30)

rawDescription: Delaying declaring static files/folders with CherryPy


rawDescription: Extract a value out of n

description: Extract a value out of n


rawDescription: progress bar properties python2.72 pywinauto

description: Progress bar properties python2.72 pywinauto


code:
from collections import Iterable

class AliasDefaultDict():
    def __init__(self, default_factory, initial=[]):
        self.aliases = {}
        self.data = {}
        self.factory = default_factory
        for aliases, value in initial:
            self[aliases] = value

    @staticmethod
    def distinguish_keys(key):
        if isinstance(key, Iterable) and not isinstance(key, str):
            return set(key)
        else:
            return {key}

    def __getitem__(self, key):
        keys = self.distinguish_keys(key)
        if keys & self.aliases.keys():
            return self.data[self.aliases[keys.pop()]]
        else:
            value = self.factory()
            self[keys] = value
            return value

    def __setitem__(self, key, value):
        keys = self.distinguish_keys(key)
        if keys & self.aliases.keys():
            self.data[self.aliases[keys.pop()]] = value
        else:
            new_key = object()
            self.data[new_key] = value
            for key in keys:
                self.aliases[key] = new_key
            return value

    def __repr__(self):
        representation = defaultdict(list)
        for alias, value in self.aliases.items():
            representation[value].append(alias)
        return "AliasDefaultDict({}, {})".format(repr(self.factory), repr([(aliases, self.data[value]) for value, aliases in representation.items()]))

rawDescription: 2d dictionary with many keys that will return the same value


code:
@app.route('/', methods=['GET', 'POST'])
def home_page():
    app.logger.debug("I'm a debugging message going to file {}!".format(
        app.logger.baseFilename))
    return "This is a test home page."

rawDescription: Two Flask Instances, One Console Message


code:
def build_tree(node):
    return [node,[build_tree(child) for child in get(node)]]

rawDescription: Building a tree "backwards"

description: Building a tree "backwards"


code:
hammer : {'nails': 2, 'screwdriver': 1}
nails : {'screws': 1, 'hammer': 2, 'screwdriver': 1}
screwdriver : {'screws': 1, 'nails': 1, 'hammer': 1}
screws : {'nails': 1, 'screwdriver': 1}

rawDescription: Optimize algorithm for creating a list of items rated together, in Python


code:
csum
n

rawDescription: Fast Numpy calculation of a slight variation of the repeat and choose functions


code:
expression = "math.sin(v['x']) * v['y']"
exp_as_func = eval('lambda: ' + expression)

rawDescription: Python: Way to speed up a repeatedly executed eval statement?


code:
query = ("INSERT INTO `python`.`UDP` (`Packet`, `Destination`, `Source`, `Protocol`, "
         "`Version`, `Header_Length`, `TTL`, `Protocol_UDP`, `Target`, `Source_Port`, "
         "`Destination_Port`, `Length`) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?))")

rawDescription: Python formatting string escape

description: Python formatting string escape


rawDescription: Loading arrays from npz files in pythhon


code:
def get_widget_by_id(id): pass  # your code here

def get_widget_by_name(name): pass  # your code here

rawDescription: Best way to require exactly one of a set of keyword arguments in Python?

description: Require exactly one of a set of keyword arguments in Python


code:
import sys
_opath = sys.path[:] #get a copy of whatever sys.path is at this point

#do imports

sys.path = _opath

rawDescription: Loading modules that change sys.path

description: Loading modules that change sys.path


code:
import numba
import numpy as np

@numba.jit
class name(object):
    @numba.object_(numba.double[:], numba.double)
    def solve(self, x, a):
        y = np.empty(x.shape[0], dtype=np.float64)
        z = np.empty(x.shape[0], dtype=np.float64)
        for k in xrange(x.shape[0]):
            y[k] = x[k] * a
            z[k] = x[k] + a

        return y, z

rawDescription: Python numba.jit types

description: Python numba.jit types


code:
class Speech(models.Model):
    location = models.ForeignKey(Location)
    speaker = models.CharField(max_length=100)
    date = models.DateField()

    class Meta:
        unique_together = ('location', 'date')

rawDescription: django save data in database only when certain conditions are met

description: Django save data in database only when certain conditions are met


code:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Firefox()
driver.get("Your URL HERE")

rawDescription: How can I locate a onmouseover element using Selenium in Python?

description: Locate a onmouseover element using Selenium in Python


code:
import math
[name for name, val in math.__dict__.iteritems() if callable(val)]
['pow',
 'fsum',
 'cosh',
 'ldexp',
 ...]

rawDescription: How to iterate through a module's functions

description: Iterate through a module's functions


code:
ts = ts.str.replace(r'(\d\d):(\d\d)$', r'\1\2')
ts
ts.map(lambda t: dt.datetime.strptime(t, '%d/%m/%y %H h %M min %S s %z'))

rawDescription: Convert dataframe with odd timestamp to timeseries with pandas


rawDescription: NumPy: Vectorize finding closest value in an array for each element in another array


code: rules.lower() == rulesa.lower()

rawDescription: Python - Ignore letter case

description: Python - Ignore letter case


code: brands['Suzuki']

rawDescription: Good practice default values

description: Good practice default values


code:
from myapp.models import object_a, object_b, Other
a = object_a()
a.foo = 'test'
a.bar = 'value'
a.save()
b = object_b()
b.foop = 'random'
b.barp = 'values'
b.save()

rawDescription: Django Releationship between multiple fields


code:
df = pd.read_csv("test.csv")
df
df.loc[:,"value1":"value3"] = df.loc[:,"value1":"value3"].div(df.sum(axis=1), axis=0)
df

rawDescription: Pandas sum across columns and divide each cell from that value


code:
from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(X, y)

rawDescription: Generating numpy arrays for scikit linear regression model


code:
animations = {
    action : {
        direction : (
            (duration, (i * len(directions) + j, x)) for x in frames
        ) for j, direction in enumerate(directions)
    } for i, action in enumerate(actions)
}

rawDescription: How to find the iteration index in this loop

description: Find the iteration index in this loop


code:
import operator
sorted(my_list, key=operator.itemgetter(2), reverse=True)

rawDescription: How to sort a list of tuples by the alphabetical ordering of one of its elements

description: Sort a list of tuples by the alphabetical ordering of one of its elements


rawDescription: Python lists with irregular format

description: Python lists with irregular format


code: ret[line.strip()] = parse_message_to_tree_helper(buf, index)

rawDescription: converting a string to a tree structure in python

description: Converting a string to a tree structure in python


rawDescription: Render template located in a unregistered folder in Django


code:
[i for i, (o, n) in enumerate(izip_longest(old, new))
                          if o != n and i not in ignore]

rawDescription: Optimise comparison between two lists, giving indices that differ


rawDescription: Comparing 2 numpy arrays

description: Comparing 2 numpy arrays


code:
import sys
from Tkinter import *

def assign(value):
    global x
    x = value
    mGui.destroy()

mGui = Tk()
mGui.geometry("500x100+500+300")
mGui.title("Attribute Selection Window")

frame1 = Frame(mGui)
frame1.pack()

mLabel = Label(frame1, text = "Please select one of the following attributes to assign to the selected Convwks feature:").grid(row=0, column=0)

frame2 = Frame(mGui)
frame2.pack()

mButton = Button(frame2, text = "CON", command = lambda: assign("CON")).grid(row=0, column=0, padx=10)
mButton = Button(frame2, text = "MS", command = lambda: assign("MS")).grid(row=0, column=1, padx=10)
mButton = Button(frame2, text = "DRN", command = lambda: assign("DRN")).grid(row=0, column=2, padx=10)
mGui.mainloop()     #FOR WINDOWS ONLY

rawDescription: Using tkinter to assign a global variable and destroy the gui


code:
def wrapper(param1, *stuff, **kargs):
 print(param1)
 print(stuff)
 print(args)
wrapper(3, 4, 5, foo=2)

rawDescription: Preserving argument default values while method chaining


code: sorted_pairs = sorted(sorted(map.iteritems()), key=operator.itemgetter(1), reverse=True)

rawDescription: Sorting a dictionary by its value, and then its key if values are equal then outputting a list


code:
for files in zip_files:
    with zipfile.ZipFile(files, 'r') as myzip:
        dfs = []
        for logfile in myzip.namelist():
            list1, list2 = [], []
            with myzip.open(logfile) as f:
                for line in f:
                    try:
                        parsed = json.loads(line[:-2])
                    except ValueError as e: # Presumably we only wish to catch json value errors
                        pass
                    else:
                        if ("key1" in parsed
                            and "val1" in parsed['key1']['key2']
                            and "val2" in parsed['key3']):
                            list1.append(parsed['key1'])
                            list2.append(parsed['key3'])
            # Build a temporary dataframe to filter the duplicates:
            tmp = pd.DataFrame(list2).join(pd.DataFrame(list1))
            tmp['col1'] = tmp['col1'].apply(lambda x: ','.join(str(i) for i in x))
            tmp.drop_duplicates(inplace=True)
            dfs.append(tmp)

        # Write only once
        pd.concat(dfs, ignore_index=True).to_csv(csvout, header=None, index=False)

rawDescription: More Efficient way to parse JSON and convert to CSV in Python


code: new_list = [list2[k] for k in list1]

rawDescription: Convert list of list into one big list pyhton


rawDescription: What is the syntax to insert one list into another list in python?


code:
# Obtain a sliced version of df1, showing only
# the columns and rows shared with the df4
df1_sliced = \
    result.loc[result.index.isin(df4.index),
               result.columns.isin(df4.columns)]
df4_sliced = \
    df4.loc[df4.index.isin(df1.index),
            df4.columns.isin(df1.columns)]

# Obtain a mask of the conflicts in the current segment
# as compared with all previously loaded data.  That is:
# NaN NaN = False
# NaN 2   = False
# 2   2   = False
# 2   3   = True
# 2   NaN = True
data_conflicts = (pd.notnull(df1_sliced) &
                  (df1_sliced != df4_sliced))

if data_conflicts.any().any():
    raise AssertionError("Data from this segment conflicted "
                         "with previously loaded data:\n",
                         data_conflicts)

rawDescription: Pandas concatenate, with no duplicate indices or columns


code:
d = {}
for line in data:
    key, value = line.split(':')
    d[key] = value

rawDescription: Parsing a generic data file in python

description: Parsing a generic data file in python


code:
from nltk import Tree
parsed_tree = Tree('ROOT', [Tree('S', [Tree('NP', [Tree('NN', ['Tsunami']), Tree('NNS', ['earthquakes'])]), Tree('VP', [Tree('VBP', ['have']), Tree('ADVP', [Tree('RB', ['also'])]), Tree('VP', [Tree('VBN', ['been']), Tree('VP', [Tree('VBN', ['linked']), Tree('PP', [Tree('TO', ['to']), Tree('NP', [Tree('NP', [Tree('DT', ['the']), Tree('NN', ['presence'])]), Tree('PP', [Tree('IN', ['of']), Tree('NP', [Tree('NP', [Tree('DT', ['a']), Tree('JJ', ['thin']), Tree('NN', ['layer'])]), Tree('PP', [Tree('IN', ['of']), Tree('S', [Tree('VP', [Tree('VBN', ['subducted']), Tree('NP', [Tree('NP', [Tree('JJ', ['sedimentary']), Tree('NN', ['rock'])]), Tree('PP', [Tree('IN', ['along']), Tree('NP', [Tree('NP', [Tree('NP', [Tree('DT', ['the']), Tree('JJS', ['uppermost']), Tree('NN', ['part'])]), Tree('PP', [Tree('IN', ['of']), Tree('NP', [Tree('DT', ['the']), Tree('NN', ['plate']), Tree('NN', ['interface'])])])]), Tree(',', [',']), Tree('UCP', [Tree('RB', ['as']), Tree('S', [Tree('VP', [Tree('VBZ', ['is']), Tree('VP', [Tree('VBN', ['thought']), Tree('S', [Tree('VP', [Tree('TO', ['to']), Tree('VP', [Tree('VB', ['be']), Tree('ADJP', [Tree('JJ', ['present']), Tree('PP', [Tree('IN', ['in']), Tree('NP', [Tree('NP', [Tree('NNS', ['areas'])]), Tree('PP', [Tree('IN', ['of']), Tree('NP', [Tree('JJ', ['significant']), Tree('NN', ['topography'])])])])])]), Tree('PP', [Tree('IN', ['at']), Tree('NP', [Tree('NP', [Tree('DT', ['the']), Tree('NN', ['top'])]), Tree('PP', [Tree('IN', ['of']), Tree('NP', [Tree('DT', ['the']), Tree('JJ', ['oceanic']), Tree('NN', ['crust'])])])])])])])])])])]), Tree(',', [',']), Tree('CC', ['and']), Tree('SBAR', [Tree('WHADVP', [Tree('WRB', ['where'])]), Tree('S', [Tree('NP', [Tree('NN', ['propagation'])]), Tree('VP', [Tree('VBD', ['was']), Tree('PP', [Tree('IN', ['in']), Tree('NP', [Tree('DT', ['an']), Tree('JJ', ['up-dip']), Tree('NN', ['direction'])])]), Tree(',', [',']), Tree('ADVP', [Tree('RB', ['possibly'])])])])])])])])]), Tree('S', [Tree('VP', [Tree('VBG', ['reaching']), Tree('NP', [Tree('DT', ['the']), Tree('NN', ['seafloor'])])])])])])])])])])])])])]), Tree('.', ['.'])])])
np = [" ".join(i.leaves()) for i in parsed_tree.subtrees() if i.label() == 'NP']
np

rawDescription: Get entities from NLTK.tree result

description: Get entities from NLTK.tree result


code:
class HelperMethods:
    @staticmethod
    def obj_to_dict(object):
        return_data = {}
        for property, value in vars(object).iteritems():
            return_data[property] = value

        return return_data['_data']

    @staticmethod
    def obj_to_list(objects):
        return_data = []
        for object in objects:
            return_data.append(HelperMethods.obj_to_dict(object))
        return return_data

rawDescription: Django-Tastypie-MongoEngine, How To Serialize Data - Create Response Method When Using prepend_urls


code:
import numpy as np
f = lambda x : x * np.cos(x-4)

rawDescription: Python: Finding multiple roots of nonlinear equation


code:
class MyModelAdmin(admin.ModelAdmin):
    ...
    class Media:
        js = ('show-copy-btn.js',)
        # above path is equivalent to /static/copy-to-clipboard.js
        # if your file in /static/js/ folder, the path above should
        # be 'js/show-copy-btn.js'

rawDescription: How to make "Copy to clipboard" button/link in django admin for selected field?

description: Make "Copy to clipboard" button/link in django admin for selected field


code: zeroth_ifd, exif_ifd, gps_ifd = pyxif.load(exif_data)

rawDescription: Write EXIF-data from TIF (read with exifread) to JPEG-file using PIL (Pillow)


code:
def factory(QClass, cls_name, signal_type):
    return type(cls_name, (QClass,), {'signal': pyqtSignal(signal_type)})

MySlider = factory(QSlider, 'MySlider', int)
self.sld = MySlider(Qt.Horizontal)
self.sld.signal.connect(self.on_signal)

rawDescription: PyQt5 signal-slot decorator example

description: PyQt5 signal-slot decorator example


code:
a + a
a + l

rawDescription: gotchas where Numpy differs from straight python?

description: Gotchas where Numpy differs from straight python


code:
from pyspark.sql.functions import col, sum, when

a_count = sum(when(col("grade") == "A", col("count")))
b_count = sum(when(col("grade") == "B", col("count")))

data.groupBy("name").agg((a_count / b_count).alias("ratio"))

rawDescription: Perform a groupBy on a dataframe while doing a computation in Apache Spark through pyspark


code:
rpmMax = rpmMaxSet.get()
rpmMin = rpmMinSet.get()
rpmPoint = rpmPointSet.get()
newrpmMax = rpmMax- rpmMin
result = rpmPoint / newrpmMax

rawDescription: Making a Tkinter calculator that gives back percent at a given point in a interval


code: sum(bytearray("abcdefgh"))

rawDescription: Python sum of ASCII values of all characters in a string


code:
'foo' in 'blah blah'
'foo' in 'blah foo blah'

rawDescription: Python: search through values of dict for regex


code:
list_pairs = permutations(d.values(), 2)
item_pairs = chain.from_iterable(product(lst1, lst2) for lst1, lst2 in list_pairs)
distances = [dist(e1, e2) for e1, e2 in item_pairs]

rawDescription: Finding Interfaces

description: Finding Interfaces


code:
from pylab import *
origin = 'lower'

delta = 0.025

x = y = arange(-3.0, 3.01, delta)
X, Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10 * (Z1 - Z2)

nr, nc = Z.shape

CS = contourf(
    X, Y, Z,
    levels = linspace(Z.min(), Z.max(), len(x)),
    ls = '-',
    cmap=cm.bone,
    origin=origin)

CS1 = contour(
    CS,
    levels = linspace(Z.min(), Z.max(), len(x)),
    ls = '-',
    cmap=cm.bone,
    origin=origin)

show()

rawDescription: How to visualize scalar 2D data with Matplotlib?

description: Visualize scalar 2D data with Matplotlib


code:
# coding: UTF-8
from datetime import datetime
from decimal import Decimal

from literalquery import literalquery

def test():
    from sqlalchemy.sql import table, column, select

    mytable = table('mytable', column('mycol'))
    values = (
        5,
        u'snowman: ☃',
        b'UTF-8 snowman: \xe2\x98\x83',
        datetime.now(),
        Decimal('3.14159'),
        10 ** 20,  # a long integer
    )

    statement = select([mytable]).where(mytable.c.mycol.in_(values)).limit(1)
    print(literalquery(statement))

if __name__ == '__main__':
    test()

rawDescription: SQLAlchemy: print the actual query

description: SQLAlchemy: print the actual query


rawDescription: Mimic curl in python

description: Mimic curl in python


rawDescription: Switching positions of two strings within a list


code:
import re
a = 'foooooooo baaaar'
reg = re.compile( r"(.)\1\1{2,}")
reg.sub(r'\1\1', a)

rawDescription: Python how to eliminate 3 or more consequent letter


code:
from django.contrib.auth.signals import user_logged_in

class UserProfile(models.Model):
    ...
    login_count = models.PositiveIntegerField(default=0)

def login_user(sender, request, user, **kwargs):
    user.userprofile.login_count = user.userprofile.login_count + 1
    user.userprofile.save()

user_logged_in.connect(login_user)

rawDescription: how to count how many times a user logs in?

description: Count how many times a user logs in


code:
context_id = statusbar.get_context_id("progress_message")
statusbar.push(context_id, "Almost done...")

rawDescription: How do I add children to a StatusBar in Glade3?

description: Add children to a StatusBar in Glade3


code:
def has_repeats(L):
    if len(L) <= 1:
        return False
    if L.index(L[-1]) != len(L) - 1:
        return True
    return has_repeats(L[:-1])

rawDescription: Python recursive no 'in' work around

description: Python recursive no 'in' work around


code:
import c
import b
print("Inside A")

rawDescription: Python - I have to reimport modules when treating a script as a module


code: print (j.__name__)

rawDescription: How to find out if variable item contains specific words in Python?

description: Find out if variable item contains specific words in Python


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

N = 7
x = np.arange(1, N+1)
a = 1.1
weights = x ** (-a)
weights /= weights.sum()
bounded_zipf = stats.rv_discrete(name='bounded_zipf', values=(x, weights))

sample = bounded_zipf.rvs(size=10000)
plt.hist(sample, bins=np.arange(1, N+2))
plt.show()

rawDescription: Sampling from a bounded domain zipf distribution


code:
from random import normalvariate

def normal_choice(lst, mean=None, stddev=None):
    if mean is None:
        # if mean is not specified, use center of list
        mean = (len(lst) - 1) / 2

    if stddev is None:
        # if stddev is not specified, let list be -3 .. +3 standard deviations
        stddev = len(lst) / 6

    while True:
        index = int(normalvariate(mean, stddev) + 0.5)
        if 0 <= index < len(lst):
            return lst[index]

rawDescription: Select one element from a list using python following the normal distribution


code:
import pylab as pl
import numpy as np

D = 2

M1 = np.array([0.0, 0.0])
M2 = np.array([1.0, 1.0])

C1 = np.array([[2.0, 0.4], [0.4, 1.0]])
C2 = np.array([[1.0, 0.6], [0.6, 2.0]])

X, Y = np.mgrid[-2:2:100j, -2:2:100j]
points = np.c_[X.ravel(), Y.ravel()]

invC = np.linalg.inv(C1)
v = points - M1
g1 = -0.5*np.sum(np.dot(v, invC) * v, axis=1) - D*0.5*np.log(2*np.pi) - 0.5*np.log(np.linalg.det(C1))
g1.shape = 100, 100

invC = np.linalg.inv(C2)
v = points - M2
g2 = -0.5*np.sum(np.dot(v, invC) * v, axis=1) - D*0.5*np.log(2*np.pi) - 0.5*np.log(np.linalg.det(C2))
g2.shape = 100, 100

fig, axes = pl.subplots(1, 3, figsize=(15, 5))
ax1, ax2, ax3 = axes.ravel()
for ax in axes.ravel():
    ax.set_aspect("equal")

ax1.pcolormesh(X, Y, g1)
ax2.pcolormesh(X, Y, g2)
ax3.pcolormesh(X, Y, g1 > g2)

rawDescription: Plotting a Discriminant Function for Normal Densities via Matplotlib


rawDescription: Python: create nested dictionary from parent-child mappping


code:
import operator

auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))

rawDescription: Good ways to sort a queryset? - Django

description: Good ways to sort a queryset? - Django


code: foo,bar|baz,spam

rawDescription: Pipe delimiter file, but no pipe inside data


code: averages_dct = {'zor': 15.5, }

rawDescription: I need to know how to sort my dictionary on python by aveage scores with students with multi-ple scores?


code:
yield scrapy.Request("http://www.ebay.com/sch/Cars-Trucks-/6001/i.html?_pgn="+str(i)+"&_skc=50&rt=nc",
                     callback=self.parse,
                     dont_filter=True)

rawDescription: Why does python scrapy yields duplicated items in my code?


rawDescription: How to just keep punctuation with a string in python?

description: Just keep punctuation with a string in python


code: class_1_average = {key: sum(value)/len(value) for key, value in class_1.items()}

rawDescription: working out an average of the values in a dictionary

description: Working out an average of the values in a dictionary


code:
import __future__

code_to_execute = compile(
    code_to_execute_in_string, '', 'exec',
    flags=__future__.print_function.compiler_flag)

rawDescription: Customize compile function in python?

description: Customize compile function in python


code:
import pyximport
pyximport.install()
from fib import cython_fib # import like a normal python import
cython_fib(20)

rawDescription: Can I compile with Cython through a normal Python script?

description: Compile with Cython through a normal Python script


rawDescription: Pandas DatetimeIndex vs to_datetime discrepancies


code:
# export2
with open('userdata_exported.csv', 'w') as f:
    writer = csv.writer(f)
    rows = ([key] + [value for item in values.items() for value in item]
            for key, values in data.items())
    writer.writerows(rows)

rawDescription: Importing/Exporting a nested dictionary from a CSV file


code: df.groupby(['id', 'category']).sum()

rawDescription: Flatten / Remove hierarchical column headers


code:
from collections import defauldict
a = {}
a['notexist']
b = defaultdict(int)
b['notexist']

rawDescription: Python Counter doesn't count

description: Python Counter doesn't count


code: probabilities

rawDescription: Sorting a complex datastructure

description: Sorting a complex datastructure


rawDescription: Rolling standard deviation using parts of data in dataframe with Pandas


code:
import base64

def getData(request,key):
    forum = Topic.get(key)
    picData = forum.creator.portfolio_set
    pictureSrc = ''
    if picData:
        picture = picData[0].userpic
        pictureSrc = "data:image;base64,%s"%base64.b64encode(picture)

    return render_to_response(request,"forum.html",{"forum":forum,"pic":pictureSrc })

rawDescription: Rendering dynamic images with google app engine


code:
edited = []
for i in range(len(factors)):
    if i%2:#for odd indices
        edited.append(factors[i])
    else:
        edited.append(-factors[i])

rawDescription: add a character in front of every element in a list

description: Add a character in front of every element in a list


code:
dictFromJSON = {
"dark" : {
   "web1.example.com" : "failure message"
},
"contacted" : {
   "web2.example.com" : 1
}
}

rawDescription: Parsing nested key from dict (generated from json)


rawDescription: How do I print a key without value from a dictionary that has multiple keys

description: Print a key without value from a dictionary that has multiple keys


code:
# Emit a warning if numpy is too old
majver, minver = [float(i) for i in _num.version.version.split('.')[:2]]

rawDescription: What is `scipy.i`?

description: What is `scipy.i`


code: df.index.hour == 8

rawDescription: Python pandas: how to get hour from timestamp in dataframe?


rawDescription: PyQt: Activate QListWidget Item

description: PyQt: Activate QListWidget Item


code:
mydata = jsondata['results'][0]['address_components']
types = ['locality', 'administrative_area_level_1']
geonames = filter(lambda x: len(set(x['types']).intersection(types)), mydata)

rawDescription: How to reverse geocode serverside with python, json and google maps?

description: Reverse geocode serverside with python, json and google maps


code:
j = 0
l2 = []
for i in range(len(l)):
    if condition(l[i]):
        l[j] = l[i]
        j += 1
    else:
        l2.append(l[i])
del l[j:]

rawDescription: python list.iteritems replacement

description: Python list.iteritems replacement


code:
from itertools import chain
dol_values = set(chain.from_iterable(dol.itervalues()))
dol_values
[tup + (True,) if tup[0] in dol_values else tup for tup in lot]

rawDescription: complicated list and dictionary lookup in python

description: Complicated list and dictionary lookup in python


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

rawDescription: Calculating year over year growth by group in Pandas


code: x2 = np.pad(x[:-2], (2, 0), mode='constant', constant_values=(np.nan,))

rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code: re.sub(r'[^\s]+', lambda m: f(m.group(0)), s)

rawDescription: What's the most pythonic way to apply a function on every word in a string with multiple types of white space characters?


code:
import time

i = '*'
while True:
    print('{}\r'.format(i), end='')
    i = ' ' if i=='*' else '*'
    time.sleep(0.5)

rawDescription: Make a blinking busy indicator on python shell


rawDescription: python - how to get the data from an plt.imshow()?

description: Python - how to get the data from an plt.imshow()


code:
x_roots
y_roots

rawDescription: Python Pandas MatPlotLib Find The Intersection Of Two Lines (One Curved, One Straight)


code:
b = ["b", "z", "a"]
reduce(lambda x,y: (x in a) and (y in a), b)

rawDescription: Python 2.7: Using reduce to verify that elements are in a list


code: numbers = re.findall('(?P<number>\d+\.\d+)', str(self.lostfeatures))

rawDescription: Python strip() function - remove characters before/after string


code:
exclude = ('q','tap')
info = [i for i in info if not i[1].startswith(exclude)]

rawDescription: Somewhat complex list comprehension

description: Somewhat complex list comprehension


code: lambda s: datetime.strptime(s[-11:-1], '%m/%d/%Y')

rawDescription: sorting a list containing dates as a substring

description: Sorting a list containing dates as a substring


code:
dir(rec)
rec.levelno
rec.levelname

rawDescription: How to get the level of the logging record in a custom logging.Handler in Python?

description: Get the level of the logging record in a custom logging.Handler in Python


rawDescription: Python web scraping - print only part of url


rawDescription: Order tuple elements

description: Order tuple elements


code: two_tier_dict_init(tier1, tier2, lambda: "I am shared but immutable")

rawDescription: Why are values of a two-level dictionary all pointing to the same object in Python 2.7?


code:
import traceback
def what():
   traceback.print_stack()

def hey():
   what()

hey()

rawDescription: Getting a python traceback without an exception


code:
import datetime as DT
from dateutil import parser
datestring = "2009-01-10"
date = parser.parse(datestring)
epoch = DT.datetime(1970, 1, 1)
timestamp = (date - epoch).total_seconds()
print(timestamp)

rawDescription: parse a date to utc unixtime

description: Parse a date to utc unixtime


code: s = "|CLL23|STR. CALIFORNIA|CLL12|AV. PHILADELFIA 438|CLL10|AV. 234 DEPTO 34|"

rawDescription: Split String with Python Regexp

description: Split String with Python Regexp


code:
model = CheckableDirModel()
tree = QtGui.QTreeView()
tree.setModel(model)

rawDescription: PyQt4 Local Directory view with option to select folders


rawDescription: Get the latest files from Location using Python


code:
def replace_words ( input_string ):
    replacement_lists = { \
        "Electronics" : ["Computer", "CD Player", "Camera", "Coffee Grinder"],
        "Baked Goods" : ["Cheesecake", "Muffin","Cookie"] }

    output_string = input_string
    for type_of_thing, list_of_things in replacement_lists.iteritems():
        for thing in list_of_things:
            output_string = output_string.replace(thing, type_of_thing)

    return output_string

input_names = [ \
"Coffee Cup.jpg",
"Computer Disks.docx",
"Muffins.jar",
"CD Player Maintenance.lzma",
"Cookie Monster's 101 Types of Cookie.pdf" ]

output_names = [replace_words(x) for x in input_names]

rawDescription: Renaming files according to a set of rules


code:
from concurrent.futures import ProcessPoolExecutor

def Processor(data_entry):
    return data_entry*2

def perform_distributed_processing(dbList, threads, processor_factory):
    with ProcessPoolExecutor(processes=threads) as executor:
        yield from executor.map(processor_factory, dbList)

if __name__ == '__main__':
    # Use this as a substitute for the database in the example
    dbList = [i for i in range(300)]
    for result in perform_distributed_processing(dbList, 8, Processor):
        print(result)

rawDescription: Multiprocessing with python3 only runs once


code:
elements
vars(elements[0])

rawDescription: Python xml Trying to show a if statement on a tag


code:
import json

with open('data.json', 'r') as f:
    data = json.load(f)

data['person']['name'] = 'JSON!'

with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)

rawDescription: how to Change dictionary values in python file

description: Change dictionary values in python file


rawDescription: A faster strptime?

description: A faster strptime


rawDescription: Square matrix length of path in Python

description: Square matrix length of path in Python


code: stats = crawler.stats.get_stats()

rawDescription: How to get stats from a scrapy run?

description: Get stats from a scrapy run


code:
v.release_keycode(66)  # toggles capslock
v.release_keycode(66)  # toggles back again capslock

rawDescription: Anybody know how to toggle caps lock on/off in Python?


code: global clearscreen

rawDescription: Complete a task during certain time frames within a python script


rawDescription: Matplotlib 3D Scatter Plot with Colorbar


rawDescription: How to pass raw data from controller into javascript?

description: Pass raw data from controller into javascript


code: fig.suptitle(r'H$_{two}$ Emission from GJ832')

rawDescription: Force LaTeX font to match default matplotlib font


code:
Story.objects.create(..., type="bf") # ID 1
Story.objects.create(..., type="bf")
Story.objects.create(..., type="cm")
Story.objects.create(..., type="dl")

Story.objects.all() # [ID 1, ID 2, ID 3, ID 4]
BeforeCommitedStory.objects.all() # [ID 1, ID 2]
CommitedStory.objects.all() # [ID 3]
DeletedStory.objects.all() # [ID 4]

rawDescription: How to create sort of DB View in Django (derived models without any db table)

description: Create sort of DB View in Django (derived models without any db table)


code:
from tkinter import *
import tkinter as tk
from tkinter.ttk import Combobox,Treeview,Scrollbar

class MainMenu(Frame):
    def __init__(self, master):
        """ Initialize the frame. """
        super(MainMenu, self).__init__(master)
        self.grid()
        self.create_GUI()

    def create_GUI(self):
        frame1 = tk.LabelFrame(self, text="frame1", width=300, height=130, bd=5)
        frame1.grid(row=0, column=0, columnspan=3, padx=8)
        #the frame is not needed but it is a good thing to use as can group
        #parts of your interface together

        self.text1 = Entry(frame1)
        #note if you were not using frames would just put self here
        self.text1.grid(row = 1, column = 0)

        self.text2 = Label(frame1, text = "",height = 10)
        self.text2.grid(row = 2 , column = 0)

        self.text3 = Entry(frame1)
        self.text3.grid(row = 3, column = 0)

root = Tk()
root.title("hi")
root.geometry("500x500")
root.configure(bg="white")
app = MainMenu(root)
root.mainloop()

rawDescription: How to make Tkinter button to be placed in particular position?

description: Make Tkinter button to be placed in particular position


code: f = interpolate.UnivariateSpline(x, y)

rawDescription: how to interpolate points in a specific interval on a plot formed by loading a txt file in to scipy program?

description: Interpolate points in a specific interval on a plot formed by loading a txt file in to scipy program


code:
class BaseClass(object):
    __metaclass__ = ABCMeta

    @abstractproperty
    def property1(self):
        pass

    @abstractproperty
    def property2(self):
        pass

    @abstractproperty
    def property3(self):
        pass

    @abstractmethod
    def abstract_method(self):
        pass

    def concrete_method(self):
        return self.property1 + self.property2

rawDescription: Implementing Abstract Properties in Python


code: return lambda x: all( [ f(x) for f in f_array ] )

rawDescription: Can you dynamically combine multiple conditional functions into one in Python?

description: Dynamically combine multiple conditional functions into one in Python