code:
import a

class B:
    def bar(self):
        return a.A()

rawDescription: How to avoid circular imports in Python?

description: Avoid circular imports in Python


code:
ConsomRatio = {}
ConsomRation["DAP_Local"] = {"Ammonia":"0.229", "Amine":"0.0007"}
ConsomRatio["MAP11_52"] = {"Ammonia":"0.138", "Fuel":"0.003"}

print(ConsomRatio["DAP_Local"]["Ammonia"])

rawDescription: Dicts in Python

description: Dicts in Python


code:
class BackgroundGenerator(threading.Thread):
    def __init__(self, generator):
        threading.Thread.__init__(self)
        self.queue = Queue.Queue(1)
        self.generator = generator
        self.daemon = True
        self.start()

    def run(self):
        for item in self.generator:
            self.queue.put(item)
        self.queue.put(None)

    def next(self):
            next_item = self.queue.get()
            if next_item is None:
                 raise StopIteration
            return next_item

rawDescription: Python generator pre-fetch?

description: Python generator pre-fetch


code:
server_list, good_list, bad_list = ["gmail.com", "yahoo.com"], [], []
with open("email.txt") as in_file:
    for email_address in in_file:
        email_address = email_address.rstrip()
        if any(email_address.endswith(server) for server in server_list):
            bad_list.append(email_address)
        else:
            good_list.append(email_address)

rawDescription: Python: check if string is in any items in a list?


code:
def findLogData(log_Files, searchForData, folderPath, resultsFile, span = (3,2)):
##    resultFile = open(resultsFile, "w")
##    lineCounter = 0
##    logLines = []

##        datalookUp = open(folderPath + "\\" + file,'r', encoding='UTF-8')
##        log = datalookUp.readlines()
    nbrOfLinesOver, nbrOfLinesUnder = span
    with open(resultsFile, 'w') as resultFile:
        for filename in log_Files:
            #filename = folderPath + "\\" + file
            with open(filename,'r', encoding='UTF-8') as f:
                log = f.readlines()

            for lineCounter, line in enumerate(log):
    ##            lineCounter += 1
    ##            logLines.append(str(line))

                for stringToFind in searchForData:
                    if stringToFind in line:
                        slinceStart = min(0, lineCounter - nbrOfLinesUnder)
                        slinceEnd = max(len(log), lineCounter + nbrOfLinesOver + 1)
##                        resultFile.writelines(logLines[slinceStart:slinceEnd])
                        resultFile.writelines(log[slinceStart:slinceEnd])

##    resultFile.close()
##    datalookUp.close()

rawDescription: Searching logs, outputting lines before and after match


rawDescription: Convert a Date in String Format to a datetime.date


code:
def isOdd(num):
     return not (num/2.0).is_integer() and type(num) in [int, long]

rawDescription: How would I check if a number is odd in python without using modulo or a library?


code:
# extract desired columns where marker is NaN
joined[pd.isnull(joined['marker'])][df1.columns]

rawDescription: pandas - filter dataframe by another dataframe by row elements

description: Pandas - filter dataframe by another dataframe by row elements


code:
new_reds   = griddata(points, reds,   (data[:, :, 0], data[:, :, 1]), method='linear')
new_greens = griddata(points, greens, (data[:, :, 0], data[:, :, 1]), method='linear')
new_blues  = griddata(points, blues,  (data[:, :, 0], data[:, :, 1]), method='linear')

new_colors = numpy.dstack([new_reds, new_greens, new_blues])
new_colors[numpy.isnan(new_colors)] = 0.5

rawDescription: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b


code:
string = [(", max(" + c + ") as " + c) for c in masterDF.columns]
string = "".join(string)
string

rawDescription: Update a Pyspark DF Column based on an Array in another column


code:
obj_1 = cs.segmentTrace(0., mat_a, mat_b)
obj_3 = obj_1.insert()

rawDescription: C to Python interface - Trying to pass structs


code:
class HardwareDeviceA(AddressableHardware):
    reg1 = RegisterDescriptor(10, 2)
    reg2 = RegisterDescriptor(20, 3)

    def __init__(self, base_address):
        AddressableHardware.__init__(self, base_address)

class HardwareDeviceB(AddressableHardware):
    reg1 = RegisterDescriptor(10, 4)

    def __init__(self, base_address):
        AddressableHardware.__init__(self, base_address)

rawDescription: Python - hardware handling, how to efficiently implement hardware registers as a property in an object


code:
for bid in json_doc['bids']:
    self.bids.insert_order(bid[2], Decimal(bid[1]), Decimal(bid[0]), initial=True)

rawDescription: what do the brackets mean around this python line?

description: What do the brackets mean around this python line


rawDescription: How to extract only numbers from input file. Numbers can be float/int

description: Extract only numbers from input file. Numbers can be float/int


code:
class ScrapySpider(Spider):
    name = 'live_function'

    def start_requests(self):
        yield Request('some url', callback=self.non_stop_function)

    def non_stop_function(self, response):
        for url in ['url1', 'url2', 'url3', 'more urls']:
            # changed
            yield Request(url, callback=get_perform_and_pause_deferred(10, self.second_parse_function))

        yield Request('some url', callback=self.non_stop_function)  # Call itself

    def second_parse_function(self, response):
        pass

rawDescription: Scrapy: non-blocking pause

description: Scrapy: non-blocking pause


code: "none" != None

rawDescription: Regarding the use of filter()

description: Regarding the use of filter()


code:
import numpy as np
from statsmodels.base.model import GenericLikelihoodModel

from scipy.stats import gamma
shape = 12; loc = 0.71; scale = 0.0166
data = gamma.rvs(shape, loc=loc, scale=scale, size=1000)
params = gamma.fit(data) # params close to but not the same as (shape, loc, scale)
# HOW TO ESTIMATE/GET ERRORS FOR EACH PARAM?

print(params)
print('\n')

class Gamma(GenericLikelihoodModel):

    nparams = 3

    def loglike(self, params):
        return gamma.logpdf(self.endog, *params).sum()

res = Gamma(data).fit(start_params=params)
res.df_model = len(params)
res.df_resid = len(data) - len(params)
print(res.summary())

rawDescription: How to get error estimates for fit parameters in scipy.stats.gamma.fit?

description: Get error estimates for fit parameters in scipy.stats.gamma.fit


code:
def addClientButtonClicked(self, edit, validator):
    print("ip=", edit.text())
    print(validator.validate(edit.text(), 0))

rawDescription: Checking QValidator's state

description: Checking QValidator's state


code: position = [char if char == letter else '_' for char in word]

rawDescription: How to get my program to check for more than one letter in a word

description: Get my program to check for more than one letter in a word


code: df

rawDescription: Pandas multiple index with multiple aggregate functions


code:
def process_command(var1, var2, var3, var4):
  if var3 == ":help":
    reply = 'Help command received.'
  elif var3 == ':status':
    reply = 'Status command received.'
  elif var3 == ':start':
    reply = 'Start command received.'
  elif var3 == ':stop':
    reply = 'Stop command received.'
  elif var3 == ':shutdown':
    reply = 'Shutdown command received.'
  else:
    reply = '%s command unknown.\nSend :help for a list of commands.' % msg

rawDescription: Why is IF: not properly evaluating this variable?


code:
def writeMatrix(matrix):
    ones = [[i for i,num in row if num==1] for row in matrix]
    with open('path/to/file', 'w') as outfile:
        for row in ones:
            outfile.write(' '.join(str(i) for i in row))
            outfile.write('\n')

rawDescription: Writing the content of a list on a text file


code: self.image = self.image.resize((self.w/2, self.h), PIL.Image.ANTIALIAS)

rawDescription: python Tkinter occupy image equally to other widget

description: Python Tkinter occupy image equally to other widget


code:
rows = []
# ... create an iterator
for row in iterator:
    process(row)
# ... use rows

rawDescription: Python Iterators from CSV module...help me understand how to use this, please?


rawDescription: BeautifulSoup find links that meet criteria


code:
regex = '|'.join(ListEmployee).lower()
import re
[l for l in ListSentence if re.search(r'\b(%s)\b' % regex, l.lower())]

rawDescription: How can I use regex to search inside sentence -not a case sensitive

description: Use regex to search inside sentence -not a case sensitive


code:
url.split('/')
url.split('/')[2]

rawDescription: Get data between two '/' using re module


code:
string
int
list
dictionary
date

rawDescription: How to convert the following scala code to python

description: Convert the following scala code to python


code:
import matplotlib as mpl
import matplotlib.pyplot as plt
import datetime

rawDescription: How to make a histogram from this nc file?

description: Make a histogram from this nc file


rawDescription: Regular Expression to match string inside parentheses


rawDescription: Python encode url with special characters


code:
@register.filter
def divide(value, arg):
    try:
        return float(value) / float(arg)
    except (TypeError, ZeroDivisionError):
        return None

rawDescription: Calculate two values and calculate difference in percentage in Django


code: return a if conditional else b

rawDescription: Which Python Conditional Return Statement Is The Most Pythonic?


rawDescription: iterating through a nested dictionary in python

description: Iterating through a nested dictionary in python


rawDescription: Solving a physics equation in Python

description: Solving a physics equation in Python


code:
class C(P):
    def __init__(self, c, **kwargs):
        super(C, self).__init__(**kwargs)
        self.c = c

obj = C(3, a=1, b=2)
print(obj.a, obj.b, obj.c) # 1 2 3

obj = C(a=1, b=2, c=3)
print(obj.a, obj.b, obj.c) # 1 2 3

rawDescription: Passing arguments to superclass constructor without repeating them in childclass constructor


code:
subprocess.check_output(
    '/usr/bin/wc -l A-Z*/A-Z*.F* </dev/null',
    shell=True)

rawDescription: Correct incantation of subprocess with shell=True to get output and not hang


code:
if agecorrect in yes:
    print("Yes, I was right!")
elif agecorrect in no:
    realage=int(input("So your real age on your next birthday will be? "))
    print("So you're actually going to be",realage,"? Good to know!")
else:
    print("I don't understand... I asked for a yes or no answer.")

rawDescription: python if statements with strings

description: Python if statements with strings


code:
def f(x):
    return x*2

for i in range(10):
    y = f(i)

rawDescription: In Python, are function-level assignments evaluated at each function call?


rawDescription: Python: How to call a class when something is done


code:
USER='zzzzzzzz'
PASS='xxxxxxxx'
HOST='yyyyyyyy'
MYDB='wwwwwwww'

rawDescription: Connecting python program to mysql safely


code: nodes = [[Node() for j in range(cols)] for i in range(rows)]

rawDescription: 2D array of objects in Python

description: 2D array of objects in Python


code: PyString_FromStringAndSize(s+i, j-i)

rawDescription: What's the runtime of Python's strip()?

description: What's the runtime of Python's strip()


code:
@asyncio.coroutine
def do_work():
    test_repo = TestRepository()

    yield from test_repo.some_init()
    try:
        res = yield from test_repo.get_by_lim_off(
                page_size=int(length),
                offset=start,
                customer_name=customer_name,
                customer_phone=customer_phone,
                return_type=return_type
            )
    finally:
        yield from test_repo.do_persistence()
        yield from test_repo.fetch_data()

rawDescription: Persist and fetch data in with block

description: Persist and fetch data in with block


code:
# add to path
import sys
sys.path.append(r'C:\path\to\assembly\dir')

# reference the assembly
import clr
clr.AddReferenceToFile(r'Groceries.dll')

from Groceries import *
chocolate = ChocolateMilk()
print(chocolate)

rawDescription: How to invoke C#/.NET namespace in IronPython?

description: Invoke C#/.NET namespace in IronPython


code: print ("The area is {}".format(area))

rawDescription: How to write a program in python 3.3.4 that works out the area of a rectangle?

description: Write a program in python 3.3.4 that works out the area of a rectangle


code:
[
    (Allow, self.owner_id, ALL_PERMISSIONS),
    (Allow, '__ADMIN__', ALL_PERMISSIONS),
    (Allow, 'creator',  ('VIEWER', 'ANALYST', 'MANAGER', 'CREATOR')),
    (Allow, 'manager',  ('VIEWER', 'ANALYST', 'MANAGER')),
    (Allow, 'analyst',  ('VIEWER', 'ANALYST')),
    (Allow, 'viewer',   ('VIEWER')),
    DENY_ALL
]

rawDescription: Having trouble with "fine-grained" Pyramid ACL


rawDescription: Adding key for average values in nested dictionary lists


code:
from numpy.random import beta
from random import gauss

def choice(seq):
        return seq[int(beta() * len(seq))]

rawDescription: Changing Python's Random Sampling Algorithm


code: a = [i for i in range(1e12)]

rawDescription: Python: itertools.product consuming too much resources


code:
from nltk.corpus import wordnet as wn
wn.synsets('black bear')
wn.synsets('black_bear')

rawDescription: How to determine multiword A is a B in wordnet?

description: Determine multiword A is a B in wordnet


rawDescription: Trying to iterate over specific column in python array


code:
print(s.hypernyms())
Out[16]: [Synset(u'canine'), Synset(u'domestic animal')]
print(s.hypernyms()[0].synonyms)
Out[17]: [u'canine', u'canid']

rawDescription: Replacement by synsets in Python pattern packatge


rawDescription: Version number comparison

description: Version number comparison


code:
blob_key = BlobKey.all().get()
if blobstore.get(blob_key):
    self.send_blob(blobstore.BlobInfo.get(blob_key),
        content_type = 'text/csv', save_as=True)    # False to mangle file name
else:
    self.error(404)

rawDescription: GAE Python - Task to save CSV to same Blobstore element daily


code:
bmpinfo = dataBitMap.GetInfo()
bmpstr = dataBitMap.GetBitmapBits(True)
im = Image.frombuffer(
    'RGB',
    (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
    bmpstr, 'raw', 'BGRX', 0, 1)

rawDescription: PIL and Bitmap from WinAPI

description: PIL and Bitmap from WinAPI


code: url = tree.find('.//original').text

rawDescription: Get specifics elements of a xml output in python


code:
preprocessed_events = [(e['date_event'], e['event_name']) for e in events]
preprocessed_events.sort()

rawDescription: Structure to store and retrieve date information between two specific dates


code:
import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.standard_b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)

rawDescription: Get content of protected web pages using Python


code:
root.bind("+", some_function)
root.bind("-", some_function)
root.bind("*", some_function)
root.bind("/", some_function)
root.bind("=", some_function)

rawDescription: Python Keystroke / Mouseclick Refference, codes list?


code:
li=[]
for x in 'catty':
   for y in 'pot':
      li.append(x+y)

li==[x+y for x in 'catty' for y in 'pot']

rawDescription: Python list comprehension for loops

description: Python list comprehension for loops


code:
s = "4 2 66"
a, b, n = map(int, s.split())
a
b
n

rawDescription: If I have a string "4 2 66" how can i get the ints 4, 2, 66 in python?


code:
def callback(evt):
    handling_widget = evt.widget
    parent_of_handling_widget = handling_widget.master
    # or evt.widget.master
    parent_of_handling_widget.destroy()

rawDescription: How to access a button's parent in Tkinter without writing class?

description: Access a button's parent in Tkinter without writing class


code: new_Z2 = np.hstack((Z2, Z1[unsorted_insert, 1:]))

rawDescription: Matching elements in numpy array

description: Matching elements in numpy array


rawDescription: Python Pandas isin return index

description: Python Pandas isin return index


rawDescription: python split a unicode string by 3-bytes utf8 character

description: Python split a unicode string by 3-bytes utf8 character


code: m = re.findall(r'TEST\s\((?:\d+\s?)*\)', str)

rawDescription: Parenthesized repetitions in Python regular expressions


rawDescription: Why set a bound method to python object create a circular reference?


code:
n = self._min_samples_context
return {c:ls for c,ls in by_context.items() if len(ls) >= n}

rawDescription: Improve performance of this python function


code:
from itertools import chain
list(OrderedDict.fromkeys(chain.from_iterable(a)))

rawDescription: How to create a list only with a unique element using this list?

description: Create a list only with a unique element using this list


rawDescription: get all decimal places after division

description: Get all decimal places after division


code:
#! /usr/bin/python3.3

import sys
from PyQt4 import QtGui
from mainWindow import MainWindow

def main():
    app = QtGui.QApplication (sys.argv)
    m = MainWindow ()
    m.show ()
    sys.exit (app.exec_ () )

if __name__ == '__main__':
    main ()

rawDescription: Connecting two different widgets together on qt with python through a button


code:
out = defaultdict(dict)
for name, phonenumber in phone.items():
    out[name]['phone'] = phonenumber
for name, address in addr.items():
    out[name]['address'] = address

rawDescription: Merge two dictionaries while sharing the keys


code:
import base64
'0x' + base64.b16encode(b'\xb5\x1a'[::-1]).decode('ascii')

rawDescription: How can I convert a bytestring array in a hex string in Python 3.4?

description: Convert a bytestring array in a hex string in Python 3.4


rawDescription: Using variables in Stored procedures with Python and MySQL


code:
if not a or b:
   print('foo')

rawDescription: Python: Check second variable if first variable is True?


code:
x = np.linspace(1, 20, 1000)
plt.plot(x, f(x))
plt.show()

rawDescription: maximum of a function on a specified domain in iPython

description: Maximum of a function on a specified domain in iPython


code:
from pyspark.sql.functions import udf, col
from pyspark.sql.types import *

schema = StructType([
    StructField("indices", ArrayType(IntegerType())),
    StructField("values",  ArrayType(DoubleType()))
])

df.withColumn("top", udf(f, schema)(col("vec_column")))

rawDescription: rdd.toDF() changes float to None

description: Rdd.toDF() changes float to None


code:
"This hasn't got double quotes " 'but "this has"'
"This isn't " 'a """very""" "attractive" approach'

rawDescription: Does Python have an equivalent of Perl's qq?


code:
customer1: [item1, item3, item8, ...]
customer2: [item7, item8, item74, ...]

rawDescription: Efficient algorithm to generate an N*N matrix


rawDescription: How would I handle the event of a thread finishing in python?


code:
d = {"Age": 20, "Nickname": "Jim", "Name": "Fred", "Height": 180}
d.keys()

rawDescription: Python: Finding the keys in an unfamiliar json object


code:
class MasterBlock(object):
    instances = []
    def __new__(cls, *args, **kwargs):
        instance = super(MasterBlock, cls).__new__(cls, *args, **kwargs)
        instance.instances.append(instance)
        return instance

    def main(self):
        print('in main of', self.__class__.__name__)  # for testing purposes

class RandomA(MasterBlock):
    def __init__(self):
        pass
    # inherit the main function

class AnotherRandom(RandomA):  # works for sub-subclasses, too
    def __init__(self):
        pass
    # inherit the main function

a=RandomA()
b=AnotherRandom()
c=AnotherRandom()

for instance in MasterBlock.instances:
    instance.main()

rawDescription: Listing all instance of a class

description: Listing all instance of a class


code:
class UserProfile( models.Model ) :
    user       = models.OneToOneField( User )
    user_types = models.ManyToManyField( UserType, null = True, blank = True )

    def has_role(self, role):
        return self.user_types.filter(name=role).count() == 1

    def has_roles(self, roles):
        return self.user_types.filter(name__in=roles).count() == len(roles)

rawDescription: Check for multiple values in a M2M relationship in Django


code:
def fun(u, t, a, b, c):
    x = u[0]
    y = u[1]
    z = u[2]
    dx_dt = a(t) * x + y * z # A change on this line: a -> a(t)
    dy_dt = b * (y - z)
    dz_dt = - x * y + c * y - z
    return [dx_dt, dy_dt, dz_dt]

rawDescription: Solving a system of odes (with changing constant!) using scipy.integrate.odeint?


code:
writer = ExcelWriter('output.xlsx')
df1.to_excel(writer,'Sheet1')
df2.to_excel(writer,'Sheet2')
writer.save()

rawDescription: Show to_csv data in separate tabs with sep ='\t' does not work


rawDescription: Aggregate text keys-values python defaultdict


code:
values = MyModel.objects.filter(a='1').values('id','a','choicefield')
name = MyModel.CHOICES_DICT[values[0]['choicefield']]

rawDescription: Get full label name of ChoiceField in QuerySet values list


code: myfoo(*extras, **vars(args))

rawDescription: Unpacking arguments from argparse

description: Unpacking arguments from argparse


code:
def flatten(items):
    for elem in items:
        if sum(isinstance(i, list) for i in elem) == 0 or sum(isinstance(i, list) for i in elem[0]) == 0:
            yield elem
        else:
            for sub_elem in elem:
                yield sub_elem

print (list(flatten(DictofCoordinates.values())))
[[1, 1], [[3, 3], [3, 3], [3, 3]], [[2, 2], [2, 2], [2, 2]], [[41, 41], [41, 41]], [[42, 42], [42, 42]]]

rawDescription: recursively exploding a list of list to "atomic list"

description: Recursively exploding a list of list to "atomic list"


code:
class Person:
    @property
    def age(self): return self.__age

    @age.setter
    def age(self, value):
        if value < 0: raise Exception('Age out of bounds.')
        self.__age = value

p = Person ()
p.age = 14
print (p.age)
p.age = -34

rawDescription: Python Classes Best Practices

description: Python Classes Best Practices


code:
from collections import namedtuple

Candidate = namedtuple('Candidate', ['start', 'subseq_index', 'dist'])
Match = namedtuple('Match', ['start', 'end', 'dist'])

def find_near_matches(subsequence, sequence, max_l_dist=0):
    prev_char = None
    candidates = []
    for index, char in enumerate(sequence):
        for skip in range(min(max_l_dist+1, len(subsequence))):
            candidates.append(Candidate(index, skip, skip))
            if subsequence[skip] == prev_char:
                break
        new_candidates = []
        for cand in candidates:
            if char == subsequence[cand.subseq_index]:
                if cand.subseq_index + 1 == len(subsequence):
                    yield Match(cand.start, index + 1, cand.dist)
                else:
                    new_candidates.append(cand._replace(
                        subseq_index=cand.subseq_index + 1,
                    ))
            else:
                if cand.dist == max_l_dist or cand.subseq_index == 0:
                    continue
                # add a candidate skipping a sequence char
                new_candidates.append(cand._replace(dist=cand.dist + 1))
                # try skipping subsequence chars
                for n_skipped in range(1, max_l_dist - cand.dist + 1):
                    if cand.subseq_index + n_skipped == len(subsequence):
                        yield Match(cand.start, index + 1, cand.dist + n_skipped)
                        break
                    elif subsequence[cand.subseq_index + n_skipped] == char:
                        # add a candidate skipping n_skipped subsequence chars
                        new_candidates.append(cand._replace(
                            dist=cand.dist + n_skipped,
                            subseq_index=cand.subseq_index + n_skipped,
                        ))
                        break
        candidates = new_candidates
        prev_char = char

rawDescription: Get position of subsequence using Levenshtein-Distance


rawDescription: Django filter many-to-many with contains


code:
import time
import threading
import concurrent.futures
import random
import logging

logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-0s) %(relativeCreated)d - %(message)s')

x = [0.1, 0.1, 0.2, 0.4, 1.0, 0.1, 0.0]

mydata = threading.local()

def do_work(secs):
    if 'session' in mydata.__dict__:
        logging.debug('re-using session "{}"'.format(mydata.session))
    else:
        mydata.session = random.randint(0,1000)
        logging.debug('created new session: "{}"'.format(mydata.session))
    time.sleep(secs)
    logging.debug('slept for {} seconds'.format(secs))
    return secs

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    y = executor.map(do_work, x)

print(list(y))

rawDescription: Python 3 concurrent.futures and per-thread initialization


code:
response=urllib2.urlopen('http://www.tigerdirect.com/applications/Category/guidedSearch.asp?CatId=17&cm_sp=Masthead-_-Computers-_-Spot%2002')
stuff=response.read()
laptops= re.findall(r'
.*?
',stuff)
len(laptops)

rawDescription: Why does this code not work? Python RE (regular expression)


code: [mk_row(d[0]) for d in dd]

rawDescription: python: unpacking an array of dictionaries in a matrix

description: Python: unpacking an array of dictionaries in a matrix


rawDescription: Working on Dictionary of Classes in Python


code:
def decorator(number):
    def inner(f):
        def decorator_f(*args, **kwargs):
            result = f(*args, **kwargs)
            #make some manipulation on result
            return result
        return decorator_f
    return inner

rawDescription: How to change function return value with decorators in python?

description: Change function return value with decorators in python


code:
import base64

# Separate the metadata from the image data
head, data = img_data.split(',', 1)

# Get the file extension (gif, jpeg, png)
file_ext = head.split(';')[0].split('/')[1]

# Decode the image data
plain_data = base64.b64decode(data)

# Write the image to a file
with open('image.' + file_ext, 'wb') as f:
    f.write(plain_data)

rawDescription: Downloading Image Data URIs from Webpages via BeautifulSoup


code:
import os
import shutil
import tempfile
from contextlib import contextmanager
from subprocess import Popen, PIPE

@contextmanager
def named_pipe():
    dirname = tempfile.mkdtemp()
    try:
        path = os.path.join(dirname, 'named_pipe')
        os.mkfifo(path)
        yield path
    finally:
        shutil.rmtree(dirname)

with named_pipe() as path:
    p = Popen(["pram_axdnull", str(kmer), input_filename, path],
              stdout=PIPE) # read from path
    with open(path, 'wb') as wpipe:
        kmer_proc = Popen(["generate_kmers", str(kmer)],
                          stdout=wpipe) # write to path
    output = p.communicate()[0]
    kmer_proc.wait()

rawDescription: Bash style process substitution with Python's Popen


code: ordered = sorted(lst, key=lambda d: [2,3,1,4].index(int(d['id'])))

rawDescription: reordering list of dicts arbitrarily in python

description: Reordering list of dicts arbitrarily in python


rawDescription: create a Python dictionary when reading a file

description: Create a Python dictionary when reading a file


code:
from django import template

register = template.Library()

@register.simple_tag
def get_sum(a, b):
    return a+b

rawDescription: How do I pass custom variable values to the django admin interface?

description: Pass custom variable values to the django admin interface


code:
with open('data1.txt','a') as f,open('data1.txt') as f1:
    lines=[x.strip() for x in f1]        #read the lines
    num=len(lines)+1
    f.write("{0}.{1:22s}{2}\n".format((num),name,ha))

rawDescription: I want to enumerate a text from a file using python


code:
SC = SimpleClass()
SC.new_attr.add('test')
SC.new_attr   #this returns a string, not a user-defined class
SC.new_attr.add('new value')

rawDescription: Method that applies to instance of a class in python // Apply a method to an instance of a class in python


code:
from Crypto.Cipher import AES
from urllib import quote

# Note that for AES the key length must be either 16, 24, or 32 bytes
encryption_obj = AES.new('abcdefghijklmnop')
plain = "Testing"

# The plaintext must be a multiple of 16 bytes (for AES), so here we pad it
# with spaces if necessary.
mismatch = len(plain) % 16
if mismatch != 0:
  padding = (16 - mismatch) * ' '
  plain += padding

ciph = encryption_obj.encrypt(plain)

# Finally, to make the encrypted string safe to use in a URL we quote it
quoted_ciph = quote(ciph)

rawDescription: django, python and link encryption

description: Django, python and link encryption


code:
class shade:
    def __init__(self, light):
        self.light=light

    @property
    def darkness(self):
        return 100 - self.light

    @darkness.setter
    def darkness(self, value):
        self.light = 100 - value

rawDescription: How do you change the value of one attribute by changing the value of another? (dependent attributes)

description: Change the value of one attribute by changing the value of another? (dependent attributes)


code: "".join("1" if (x&y) else "0" for y in pot)

rawDescription: Python: What's the best way to send status bits and timestamps with PySerial


code:
a = A()
a.login
a.logout
a.version = '2.0'
a.logout

rawDescription: python global decorator for class attributes

description: Python global decorator for class attributes


code: lst_names = [os.path.join(full_subdir_name, n) for n in os.listdir(full_subdir_name)]

rawDescription: Python--read files, save the file names and access to these files


code: sortedRunnerData = sorted(runnerData, key=lambda data: data[1])

rawDescription: Python Lists/ Tuples in terms of sorting


code:
if __name__ == "__main__":
    s = spin()
    s.cursor_invisible()
    s.start()
    a = raw_input("")
    s.stop()
    s.cursor_visible()

rawDescription: implementing a spinner type object in a class as a subprocess

description: Implementing a spinner type object in a class as a subprocess


code:
############################################################################
# MySQL example! where MySQL doesn't support timeones with it's DATETIME type!
############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

rawDescription: remove pytz timezone

description: Remove pytz timezone


code:
def f(x):
    return x+2

def test_equal():       # py.test looks for functions that start with test_
    assert f(3) == 5

rawDescription: lightweight unit testing in python

description: Lightweight unit testing in python


rawDescription: Shortening random number generators in Python


code:
r = requests.post('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
r.headers['content-type']
r.encoding
r.text
r.json

rawDescription: How to post a file to django WITHOUT using html form

description: Post a file to django WITHOUT using html form


code: electronDensity = eval(vName)

rawDescription: How to pass string as variable name assignment

description: Pass string as variable name assignment


code: [dic[n] for n in number.split()]

rawDescription: Convert a set of numbers into a word

description: Convert a set of numbers into a word


rawDescription: python setuptools install_requires is ignored when overriding cmdclass

description: Python setuptools install_requires is ignored when overriding cmdclass


code: sorted(nice.items(), key=lambda itm: map(int,itm[::-1]),reverse=True)

rawDescription: Python : Displaying a sorted dictionary by more than one condition


code:
def foo(bar):
    return bar

rawDescription: How to import members of modules within a package

description: Import members of modules within a package


code:
def increment(x): return x + 1
def sayHiBefore(func, *args, **kwargs):
    print('Hi')
    return func(*args, **kwargs)

print(sayHiBefore(increment, 1))

rawDescription: Passing Python function with no argument


code:
from celery import bootsteps
from celery.bin import Option

app.user_options['worker'].add(
    Option('--username', dest='api_username', default=None, help='API username.')
)

app.user_options['worker'].add(
    Option('--password', dest='api_password', default=None, help='API password.')
)

class CustomArgs(bootsteps.Step):

    def __init__(self, worker, api_username, api_password, **options):
        # store the api authentication
        APITask.auth = (api_username, api_password)

app.steps['worker'].add(CustomArgs)

rawDescription: Initializing a worker with arguments using Celery


code:
def evens(stream):
    for n in stream:
        if n % 2 == 0:
            yield print("Inside evens") or n

rawDescription: Generator expressions vs yield

description: Generator expressions vs yield


code:
starting_number = 5

def modify_starting_number(starting_number):
    starting_number = starting_number * 2
    return starting_number

print (starting_number)

rawDescription: counting number with 3 csvs python

description: Counting number with 3 csvs python


code:
from bokeh.palettes import Spectral6
p.image(image=[d],x=[0],y=[0],dw=[360], dh=[180], palette=Spectral6)

rawDescription: Plot showing up black in Bokeh

description: Plot showing up black in Bokeh


code:
import struct
foo, bar, kaka = struct.unpack("BBB", '\x06\x06\x06')
struct.pack("BBB", foo, bar+1, kaka+5)

rawDescription: Hex data from socket, process and response


code: [name for name, count in zip(names, numbers) for _ in range(count)]

rawDescription: Multiplying strings in a list by numbers in another list (Python)


code: check_time = BaseTests.check_time

rawDescription: import only a class static method

description: Import only a class static method


code:
CC = {}

for step in range(len(Nodes['time'])):
    for key in CoordComboSort.keys():
        CC[Nodes['time'][step]] = {key : CoordComboSort[key][step] for key in CoordComboSort.keys()}

rawDescription: Updating a Dictionary within Python

description: Updating a Dictionary within Python


rawDescription: Python, lil_matrix : set the diagonal to be a power of a number


rawDescription: How to .write() two items, a zero and an iterator in Python?


code:
def connectToSiteFunction(ip):
    url = 'http://{}/path/to/page.html'.format(ip)
    # now open url as normal

rawDescription: open a site every 15 seconds with different IP

description: Open a site every 15 seconds with different IP


rawDescription: Split list based on first character - Python


code:
a = 'a'
b = 'b'

temp_tuple = b, a # tuple packing
print(temp_tuple) # ('b', 'a')

a, b = temp_tuple # tuple unpacking
print(a) # 'b'
print(b) # 'a'

rawDescription: How does a comma followed by a variable assignment concatenate?


rawDescription: list.reverse does not return list?

description: List.reverse does not return list


code: cbar = plt.colorbar(CF, ticks=lvls, format='%.4f')

rawDescription: matplotlib contour plot: proportional colorbar levels in logarithmic scale

description: Matplotlib contour plot: proportional colorbar levels in logarithmic scale


code:
def make(name='', street='', city='', state='', zip='', count=0):
    dic[count]=User(name=name, street=street, city=city, state=state, zip=zip)

rawDescription: Python: Accessing object attributes from objects stored in a dictionary


code:
from urllib import parse
path = parse.urlparse('http://localhost:8000/dashboard/').path

rawDescription: How to compare Referer URL in Django Request to another URL using reverse()?

description: Compare Referer URL in Django Request to another URL using reverse()


code:
import re

print('passed:', re.search('passed number">(\d+)', data).group(1))
print('zero:', re.search('zero number">(\d+)', data).group(1))
print('failed:', re.search('zero number">(\d+)', data).group(1))
print('Rate:', re.search('suite">(\d+)', data).group(1))

passed: 271
zero: 0
failed: 0
Rate: 98

rawDescription: Parse HTML file using Python without external module


code:
[('ABC12346', {'serial_num': 'ABC12346', 'site_location': 'Europe'}),
 ('SER12345', {'serial_num': 'SER12345', 'site_location': 'North America'}),
 ('SER12346', {'serial_num': 'SER12346', 'site_location': 'North America'}),
 ('ABC12345', {'serial_num': 'ABC12345', 'site_location': 'South America'}),
 ('SER12347', {'serial_num': 'SER12347', 'site_location': 'South America'})]

rawDescription: Sort Dictionary of Dictionaries on multiple child dictionary values


rawDescription: How to specify a unicode and other escaped literals to Python 2.x ConfigParser

description: Specify a unicode and other escaped literals to Python 2.x ConfigParser


code:
from importlib import import_module

module = import_module('library.oakalleyit')
getattr(module, 'some_function_name')()

rawDescription: Pythonic way to import module whose name is only known at runtime?


code:
def find_gene(uniprot):
    pattern = 'mutation_directory/*_{}_MutationOutput.txt'.format(uniprot)
    return glob.glob(pattern)[0]

rawDescription: How to find a specific file in Python

description: Find a specific file in Python


code:
# modified part
GPIO.output(4, GPIO.HIGH)
while (GPIO.input(22) ==  GPIO.HIGH):
    pass
# end modification

rawDescription: How to stop loop partially?

description: Stop loop partially


code:
['A /cloudos-ui/branches/bare_metal (from /cloudos-ui/branches/rc4g1build:9930)',
 'M /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/templates/flavors/_edit.html',
 'M /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/forms.py',
 'M /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/tables.py',
 'M /cloudos-ui/branches/bare_metal/misc/cosmos/packaging/DEBIAN/control',
 'M /cloudos-ui/branches/bare_metal/src/horizon/openstack_dashboard/dashboards/admin/flavors/templates/flavors/_create.html',
 'M /cloudos-ui/branches/bare_metal/misc/skyline/packaging/DEBIAN/control',
 'M /cloudos-ui/branches/bare_metal/misc/cosmos/scripts/create_cosmos_installer.sh',
 'M /cloudos-ui/branches/bare_metal/misc/skyline/scripts/create_skyline_installer.sh']

rawDescription: searching a substring in a python list and then removing it from the list

description: Searching a substring in a python list and then removing it from the list


code:
from numpy.random import randint
from numpy import cos, sin, radians, cumsum
import numpy as np
import matplotlib.pyplot as plt

N = 100   # Size of square as a multiple of the step size.
NSteps = 5000   # Number of steps in simulation.
x_start = 0   # x coordinate of starting location. Origin is at centre of square
y_start = 0   # y coordinate of starting location. Origin is at centre of square

# get all of the angles
angles = radians(randint(low=0, high=361, size=NSteps))

# get (unwrapped) positions
x = cumsum(cos(angles)) + x_start
y = cumsum(sin(angles)) + y_start

# find where the position crosses the boundary
x_wraps = np.where(np.diff((x + N/2) // N))[0]
y_wraps = np.where(np.diff((y + N/2) // N))[0]

# do the wrapping
x = x - N * ((x + N/2)//N)
y = y - N * ((y + N/2)//N)

rawDescription: Problems plotting a 2D random walk with Python


code:
import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/temp/myapp.log',
                    filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')

rawDescription: Printing to screen and writing to a file at the same time


rawDescription: An inheritance example in Python

description: An inheritance example in Python


code: (version, counter, Element)

rawDescription: Having only 5 elements per XML component python


code:
hours = pd.Series(index=x.index)
minutes = pd.Series(index=x.index)
for tz in ['America/Los_Angeles', 'Europe/London' ]:

   local = df.index.tz_convert(tz)
   x[(tz,'tz')] = local

   mask = x[(tz,'sales1')].notnull() & x[(tz,'sales2')].notnull()
   hours.iloc[mask.values] = local.hour[mask.values]
   minutes.iloc[mask.values] = local.minute[mask.values]

x = x.sortlevel(axis=1)

rawDescription: calculate mean sales per minute accross 24-hour cycles as per local-time (HH:MM)

description: Calculate mean sales per minute accross 24-hour cycles as per local-time (HH:MM)


rawDescription: For loop behavior in python

description: For loop behavior in python


code:
class main(pyglet.window.Window):
    def __init__ (self):
        super(main, self).__init__(800, 800, fullscreen = False)
        self.x, self.y = 0, 0
        self.sprites = {}
        self.batches = {}
        self.subgroups = {}

        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def render(self):
        self.clear()

        for batch_name, batch in self.batches.items():
            batch.draw()

        for sprite_name, sprite in self.sprites.items():
            sprite._draw()

        self.flip() # This updates the screen, very much important.

    def run(self):
        while self.alive == 1:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze.
            # Basically it flushes the event pool that otherwise
            # fill up and block the buffers and hangs stuff.
            event = self.dispatch_events()

x = main()
x.run()

rawDescription: Pyglet Image Rendering

description: Pyglet Image Rendering


code:
df3 = df2.copy()
df3["File"] = np.repeat(df1.File.values, df1.Repeated.values)
df3

rawDescription: Python Pandas multiple occruences of a row in dataframe 1 into new column of dataframe 2


code:
base = "Charol(l)ais (cattle)"
words = []
start = 0
for i, c in enumerate(base):
    if c == "(":
        words.append((base[start:i],))
        start = i + 1
    elif c == ")":
        words.append((base[start:i], ""))
        start = i + 1
if start < len(base):
    words.append((base[start:],))

rawDescription: Python: How to produce only in sequence combinations from a list of string parts, with use being optional


code:
while text.find(":{") > -1:
    index = text.find(":{")
    if text[index-2:index]=="fb":
        text = text[:index-2] + "<b>" + text[index+2:] #insert <b>
        text = text.replace("}","</b>",1) # replace one.
    # else if fi, fv, etc.

rawDescription: Generate html from plain text with formatting markers in Python 3


rawDescription: Efficient algorithm to solve (m choose x) = n in python


code:
a = ...
sum(map(collections.Counter, a.values()), collections.Counter())

rawDescription: Summing dictionaries in a large dictionary


code:
def nbest(self, score_fn, n):
    """Returns the top n ngrams when scored by the given function."""
    return [p for p,s in self.score_ngrams(score_fn)[:n]]

rawDescription: How to get PMI scores for trigrams with NLTK Collocations? python

description: Get PMI scores for trigrams with NLTK Collocations? python


rawDescription: Overridden vs. virtual class methods in Python


code:
mylist=[]
with open('x.dat') as f:
   for line in f:
       #apply int to the items of `str.split` to convert them into integers
       x, y = [float(z) for z in line.split()[:2]]
       mylist.append(Point(x, y))

rawDescription: PYTHON - reading single row from a file

description: PYTHON - reading single row from a file


code: unique_a = np.unique(b).view(a.dtype).reshape(-1, a.shape[1])

rawDescription: Find unique rows in numpy.array

description: Find unique rows in numpy.array


code: set('harpy') & set('happy')

rawDescription: Python- Replace all occurrences of letter at specific position on a string


code:
g.index = g.index.swaplevel(1, 2)
g

rawDescription: Multi-Index Sorting in Pandas

description: Multi-Index Sorting in Pandas


code:
import os
import signal
import sys

def kill_yourself_now():
    sig = signal.CTRL_C_EVENT if sys.platform == 'win32' else signal.SIGINT
    os.kill(os.getpid(), sig) # raise KeyboardInterrupt in the main thread

rawDescription: Timeout function in Python

description: Timeout function in Python


code:
import re
data = 'Schedule (1) GEORGE JETSON\n\nPRESIDENT X X 0 O O\n\n(2) BILL CLINTON\n\nVICE PRESIDENT X X 0 0 0\n\n(3)'
re.search(r'Schedule \(1\).*?\(2\)', data, flags=re.DOTALL)
re.search(r'Schedule \(1\).*?\(2\)', data, flags=re.DOTALL).group()

rawDescription: Returning characters after regex has found match in python


code:
from __future__ import division
import math
import urlparse
import urllib

import tornado.web

def update_querystring(url, **kwargs):
    base_url = urlparse.urlsplit(url)
    query_args = urlparse.parse_qs(base_url.query)
    query_args.update(kwargs)
    for arg_name, arg_value in kwargs.iteritems():
        if arg_value is None:
            if query_args.has_key(arg_name):
                del query_args[arg_name]

    query_string = urllib.urlencode(query_args, True)
    return urlparse.urlunsplit((base_url.scheme, base_url.netloc,
        base_url.path, query_string, base_url.fragment))

class Paginator(tornado.web.UIModule):
    """Pagination links display."""

    def render(self, page, page_size, results_count):
        pages = int(math.ceil(results_count / page_size)) if results_count else 0

        def get_page_url(page):
            # don't allow ?page=1
            if page <= 1:
                page = None
            return update_querystring(self.request.uri, page=page)

        next = page + 1 if page < pages else None
        previous = page - 1 if page > 1 else None

        return self.render_string('uimodules/pagination.html', page=page, pages=pages, next=next,
            previous=previous, get_page_url=get_page_url)

rawDescription: Can tornado handle pagination?

description: Can tornado handle pagination


code:
dict(enumerate(set(key for key in itertools.chain(x, y)), 1))
dict(enumerate((key for key in itertools.chain(x, y)), 1))

rawDescription: Merging dictionaries using a counter

description: Merging dictionaries using a counter


code:
pointsTable = [
    (0, 0),
    (0.3, 1),
    (0.5, 2),
    (0.7, 2.5),
    (0.9, 3)
    ]

def calculate_quality_points(tp, tn, fp, fn):
    q = get_quality_score(tp, tn, fp, fn)
    return get_quality_points(q)

def get_quality_score(tp, tn, fp, fn):
    return float(tp + tn) / (tp + tn + 10 * fp + fn)

def get_quality_points(q):
    i = 0
    if q < 0 or q > 1:
        return -1
    for i in range(len(pointsTable) - 1):
        if q >= pointsTable[i][0] and q < pointsTable[i + 1][0]:
            return pointsTable[i][1]
    return pointsTable[len(pointsTable) - 1][1]

rawDescription: how can i make a filter quality score?

description: Make a filter quality score


code: pivot = high

rawDescription: Quick Sort is not returning expected results - Python3


code:
from collections import Counter
import random

Counter(random.choice(['H', 'T']) for _ in range(100))

rawDescription: Tallying the outcome of a coin flip

description: Tallying the outcome of a coin flip


code:
import re

io = [
    ('my name is (?P<name>\w+)', 'Hi there, {name}'),
]

string = input('> ')
for regex, output in io:
    match = re.match(regex, string)
    if match:
        print(output.format(**match.groupdict()))
        break

rawDescription: How do I use regular expressions in Python with placeholder text?

description: Use regular expressions in Python with placeholder text


code:
class PostViewSet(viewsets.ReadOnlyModelViewSet):
    serializer_class = PostSerializer

    def get_queryset(self):
        keyword = self.request.query_params.get('tag', '')
        queryset = Post.objects.filter(tag__iexact=keyword)
        return queryset

rawDescription: Django rest framework - how to make case insensitive viewset search


code:
nx.draw(G)
fig = plt.gcf()
fig.set_size_inches((10, 10))
plt.show()

rawDescription: Large networkx graph for nearest neighbors figure


rawDescription: Python Generator returning stop iteration?


rawDescription: can one function be overwritten by calling another?

description: Can one function be overwritten by calling another


rawDescription: How to formally insert URL space (%20) using Python?

description: Formally insert URL space (%20) using Python


code: m = [[(float('inf') if j else 0) for j in range(max_v + 1)] for _ in range(len(weights) + 1)]

rawDescription: 0/1 Knapsack with integer values and irrational weights?


code:
#!/usr/bin/env python
from pyprocessing import *

S = 20
W = 5
H = 5

# data = [[0] * W] * H #trouble
data = []
for y in xrange(H):
    data.append([])
    for x in xrange(W):
        data[y].append(0)

def setup():
    size(W*(S),H*(S))

def draw():
    background(0)
    for y in xrange(H):
        for x in xrange(W):
            fill(data[x][y] * 255)
            rect(x*S,y*S,S,S)

def mouseDragged():
    for y in xrange(H):
        for x in xrange(W):
            xs = x * S
            ys = y * S
            if (mouse.x >= xs) and (mouse.x <= (xs+S)) and (mouse.y >= ys and mouse.y <= (ys+S)):
                if key.pressed:
                    data[x][y] = 0
                else:
                    data[x][y] = 1

run()

rawDescription: How correctly draw boxes in pyprocessing?


rawDescription: How to pass a Numpy array into a cffi function and how to get one back out?

description: Pass a Numpy array into a cffi function and how to get one back out


code:
userFirstName = raw_input('What is the user first name?')
userLastName =  raw_input('What is the user last name?')

rawDescription: Python For In Loop Matrix for User Input


code:
import itertools

class Radio:
    def __init__(self):
        self.stations = itertools.cycle(["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"])
        self.current_station = next(self.stations)

    def seek(self):
        print("Currently tuned to", self.current_station)
        print("Seeking...")
        self.current_station = next(self.stations)
        print("Now tuned to", self.current_station)

rawDescription: I need some help starting of this radio program


code:
def view(request):
    ...
    data = {}
    for c in student_courses:
        data[c.course_title] = c.grade

    # Populate form
    form = GradesForm(request.POST, **data)
    ...

rawDescription: How to populate lists of objects with WTForms?

description: Populate lists of objects with WTForms


code: result = max(gen, key=len)

rawDescription: Finding the largest/smallest object in a python generator/list


code:
class MyDeleteView(DeleteView):
    success_url = reverse('list')

    def get(self, *a, **kw):
        return self.delete(*a, **kw)

rawDescription: Delete items from ListView in Django 1.5


code: del request.session['flag']

rawDescription: Django settings

description: Django settings


rawDescription: Efficient algorithm for matrix calculation


rawDescription: finding widgets on a grid (tkinter module)

description: Finding widgets on a grid (tkinter module)


code:
b = B(1)
del b.x

rawDescription: A property's `fdel` method is not invoked when `__delattr__` is overridden


rawDescription: How to handle links containing space between them in Python

description: Handle links containing space between them in Python


rawDescription: NumPy: 2D array from a list of arrays and scalars


code: {item for item in iterable}

rawDescription: What's the pythonic idiom for making a simple list out of a list of instances?


code:
from collections import Counter
from operator import attrgetter

class Record(object):
    def __init__(self, **kwargs):
        for key, value in kwargs.iteritems():
             setattr(self, key, value)

records = [Record(uid='001', url='www.google.com', status=200),
           Record(uid='002', url='www.google.com', status=404),
           Record(uid='339', url='www.ciq.com',    status=200)]

def count_attr(attr, records):
    """ Returns Counter keyed by unique values of attr in records sequence. """
    get_attr_from = attrgetter(attr)
    return Counter(get_attr_from(r) for r in records)

for attr in ('status', 'url'):
    print('{!r:>8}: {}'.format(attr, count_attr(attr, records)))

rawDescription: Python how to use Counter on objects according to attributes


rawDescription: .fillna column if two cells are empty in Pandas


code:
import foo
print(foo.__doc__)

rawDescription: How to display Python file header description

description: Display Python file header description


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
# Make random number generation consistent between runs
np.random.seed(5)

def main():
    numlines, numpoints = 2, 3
    lines = np.random.random((numlines, numpoints, 2))

    fig, ax = plt.subplots()
    for line in lines:
        # Add "num" additional segments to the line
        segments, color_scalar = interp(line, num=20)
        coll = LineCollection(segments)
        coll.set_array(color_scalar)
        ax.add_collection(coll)
    plt.show()

def interp(data, num=20):
    """Add "num" additional points to "data" at evenly spaced intervals and
    separate into individual segments."""
    x, y = data.T
    dist = np.hypot(np.diff(x - x.min()), np.diff(y - y.min())).cumsum()
    t = np.r_[0, dist] / dist.max()

    ti = np.linspace(0, 1, num, endpoint=True)
    xi = np.interp(ti, t, x)
    yi = np.interp(ti, t, y)

    # Insert the original vertices
    indices = np.searchsorted(ti, t)
    xi = np.insert(xi, indices, x)
    yi = np.insert(yi, indices, y)

    return reshuffle(xi, yi), ti

def reshuffle(x, y):
    """Reshape the line represented by "x" and "y" into an array of individual
    segments."""
    points = np.vstack([x, y]).T.reshape(-1,1,2)
    points = np.concatenate([points[:-1], points[1:]], axis=1)
    return points

if __name__ == '__main__':
    main()

rawDescription: Matplotlib: How to colorize a large number of line segments as independent gradients, efficiently


code:
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect(worker_addr)
socket.send('message')
msg = socket.recv()

rawDescription: 0mq one-to-many connection

description: 0mq one-to-many connection


code:
def get_queryset(self):
    return Submission.objects.extra(
    select={'total': 'IFNULL((SELECT SUM(vote_value) ' + \
        'FROM submissions_vote ' + 'WHERE submissions_vote.submission_id = ' + \
        'submissions_submission.id), ' + '0)',
    'has_voted': 'CASE WHEN %d IN (SELECT voter_id FROM submissions_vote WHERE ' + \
        'submissions_vote.submission_id = submissions_submission.id) THEN 1 ELSE 0 END'
    }, select_params=(self.request.user.pk,)).order_by('-total')

rawDescription: Django querysets and foreign keys

description: Django querysets and foreign keys


code:
for atype in e.findall('type'):
    print(atype.get('foobar'))

rawDescription: How do I parse XML in Python?

description: Parse XML in Python


code: hours = [time.strptime(format(i % 2400, '04.0f'), "%H%M") for i in a]

rawDescription: Parse hours without leading zeroes by strptime in Python


rawDescription: How to un-pad a string/number with zeros

description: Un-pad a string/number with zeros


rawDescription: Generic function that accept a table and column name and returns all the primary key values that matches a filter value given


code: pthread_create(pthread_id, NULL, thread_entrance, NULL);

rawDescription: Python threads in C

description: Python threads in C


code:
x = 300
y = 300
lParam = y << 15 | x
lParam & 0x7FFF # x
lParam >> 15 # y

rawDescription: Python win32api SendMesage

description: Python win32api SendMesage


code:
import numpy as np
x = np.arange(-10, 10, 0.1)
y = x**3
np.interp(5.05, x, y)
5.05**3

rawDescription: extract value of a numeric array function in numpy

description: Extract value of a numeric array function in numpy


code: df1.join(df2, how='inner')

rawDescription: Merge on single level of MultiIndex

description: Merge on single level of MultiIndex


code:
from pip._vendor import pkg_resources

def get_version(package):
    package = package.lower()
    return next((p.version for p in pkg_resources.working_set if p.project_name.lower() == package), "No match")

rawDescription: How to check version of python package if no __version__ variable is set

description: Check version of python package if no __version__ variable is set


code:
def index(request):
    objects = Blog.objects.order_by('-pub_date')
    return render(request, 'layout.html', {'blogs': objects})

rawDescription: django views : passing a dictionarry

description: Django views : passing a dictionarry


rawDescription: Why can't I change a list in a method?

description: Why can't I change a list in a method


code: re.findall('db\[(\d+)\]',"any string coming from db[090876]")

rawDescription: How to extract a number from a string in python

description: Extract a number from a string in python


code:
import ghostscript

args = ['gs', #it seems not to matter what is put in 1st position
        '-dSAFER',
        '-dBATCH',
        '-dNOPAUSE',
        '-sDEVICE=png16m',
        '-r100',
        '-sOutputFile=calendar.png',
        'calendar.pdf']

ghostscript.Ghostscript(*args)

rawDescription: Producing a printable calendar with Python


code:
from paste.script import command

class NewXxx(command.Command):
    usage = "PREFIX"
    summary = "some command"
    group_name = "my group"

rawDescription: Global paster command not found in virtualenv


code: next == "left" or "Left"

rawDescription: The CLI seems to ignore my function and go to another! (Python)


code:
def is_number(s):
    """ From your solution. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def func(i1, i2):
    return lambda str: is_number(str[i1:i2].strip())

if __name__ == '__main__':
    result = []
    with open('in.txt') as fin:
       result = filter(func(0,10), fin)
    with open('out.txt', 'w') as fout:
        for s in result:
            fout.write(s)

rawDescription: How to pick lines containg numbers in given positions on the line with python

description: Pick lines containg numbers in given positions on the line with python


code:
class TestFoo(unittest2.TestCase):

    a = inject.attr('a', A)

    def __init__(self, *n, **kw):
        unittest2.TestCase.__init__(self, *n, **kw)
        self.unit_scope = inject.reqscope

    def setUp(self):
        self.foo = Foo()
        self.unit_scope.register()

    def tearDown(self):
        self.unit_scope.unregister()

    ...

rawDescription: How to get per-testcase scoping for dependency injected objects in Python?

description: Get per-testcase scoping for dependency injected objects in Python


code:
a = numpy.random.RandomState(4)
a.rand(5)

rawDescription: python vs octave random generator

description: Python vs octave random generator


code:
def count_users(selectedTown=None):
    filters = {"gender": "M"}
    if selectedTown is not None:
        filters["town"] = selectedTown
    return User.objects.filter(**filters).count();

rawDescription: When querying a Django model, is there a way to match every string in a field


code:
ar = ...
x = da.from_array(ar, chunks=(1, arr.shape[1]))
x.map_blocks(function, *args)
states = x.compute()

rawDescription: Parallelize loop over numpy rows

description: Parallelize loop over numpy rows


code:
lst = ['abc', '\n', 'def', 'ghi', '\n', 'jkl']
[i for i, val in enumerate(lst) if val == '\n']

rawDescription: Index of \n in Python list

description: Index of \n in Python list


code:
from collections import defaultdict
unique_dict = {}
tmp_dict = defaultdict(list)

for key, value in your_current_dict.items():
    tmp_dict[value].append(key)

for value, keys in tmp_dict.items():
    unique_dict.update(zip(keys, [value] * len(keys)))

rawDescription: multiple keys in python dictionary, is possible?

description: Multiple keys in python dictionary, is possible


code:
class User(models.Model):
     addresses = generic.GenericRelation( Addres )
     name = models.CharField()

rawDescription: Django creating relation one-to-many

description: Django creating relation one-to-many


rawDescription: Python procedure for changing an object

description: Python procedure for changing an object


rawDescription: Chi Square Test of Independence in Python


rawDescription: Using the Ansible Python API, how can I get access to task level outputs in my code?


code:
class FooSpider(BaseSpider):
    yet = False

    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):
        from_crawler = super(FooSpider, cls).from_crawler
        spider = from_crawler(crawler, *args, **kwargs)
        crawler.signals.connect(spider.idle, signal=scrapy.signals.spider_idle)
        return spider

    def idle(self):
        if not self.yet:
            self.crawler.engine.crawl(self.create_request(), self)
            self.yet = True

rawDescription: Scrapy: How to manually insert a request from a spider_idle event callback?


code:
def clear_something(modeladmin, request, queryset):
    queryset.update(field=0)
    for a in queryset:
        B.objects.filter(f=a).delete()

rawDescription: Custom Django admin action, remove entries related by ForeignKey


code:
s = '08:04:10 Current Track Playing = AB034214 Skinny Genes - Eliza Doolittle'
s_clean = s[:33] + s[42:]
s_clean

rawDescription: Deleting Mix of Numbers and Letters

description: Deleting Mix of Numbers and Letters


code:
import types

def f(x, y=2):
    return x,y

g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__,
                       argdefs=f.__defaults__,
                       closure=f.__closure__)
print(f(1))
print(g(1))
assert f is not g

rawDescription: How to create a copy of a python function

description: Create a copy of a python function


code:
def pcolor_mask_geoms(cube, geoms, transform):
    path = Path.make_compound_path(*geos_to_path(geoms))
    im = iplt.pcolormesh(cube)
    im.set_clip_path(path, transform=transform)
    try:
        im._wrapped_collection_fix.set_clip_path(path, transform)
    except AttributeError:
        pass

rawDescription: Mask cube with features

description: Mask cube with features


rawDescription: Slicing Python lists vs Slicing R vectors


code:
import Tkinter
import urllib

def updateCheck(self):
    update = False

    updateWindow = Tkinter.Toplevel()
    updateWindow.title(string="Update Checker")
    updateWindow.resizable(False, False)

    #Gets downloaded version
    versionSource = open('version.txt', 'r')
    versionContents = versionSource.read()

    #gets newest version
    updateSource = urllib.urlopen("http://www.suturesoft.com/Updates/craftbook.txt")
    updateContents = updateSource.read()

    #checks for updates
    for i in range(0,20):
        if updateContents[i] != versionContents[i]:
            dataLabel = Tkinter.Label(updateWindow,text="\n\nThere are data updates availible.\n\n")
            dataLabel.pack()
            update = True
            break
    for i in range(22,42):
        if updateContents[i] != versionContents[i]:
            versionLabel = Tkinter.Label(updateWindow,text="\n\nThere are version updates availible.\n\n")
            versionLabel.pack()
            update = True
            break
    if update == False:
        versionLabel = Tkinter.Label(updateWindow,text="\n\nYou are already running the most up to date version.\n\n")
        versionLabel.pack()

rawDescription: python - Check for updates for a program

description: Python - Check for updates for a program


code:
import sys
from contextlib import contextmanager

@contextmanager
def capturinglines(output=None):
    "Captures lines of output to a list."
    from cStringIO import StringIO

    try:
        output = [] if output is None else output
        stringio = StringIO()
        out, err = sys.stdout, sys.stderr
        sys.stdout, sys.stderr = stringio, stringio
        yield output
    finally:
        sys.stdout, sys.stderr = out, err
        output.extend(stringio.getvalue().splitlines())
        stringio.close()

rawDescription: How to make a class that acts like a string?

description: Make a class that acts like a string


code: mylist = [function1, function2]

rawDescription: Is there a way to append the name of a function to a list automatically?


code:
new_index, indexer = df.index.reindex(['mean', 'std', '50%'], level=1)
df = df.reindex(index=new_index)
print(df)

rawDescription: Pandas Multi-Index rendering

description: Pandas Multi-Index rendering


rawDescription: Pandas: apply a function to a multiindexed series


code: x[tuple(v)] = 7

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

description: Use index as a key in Python


code: output = other_func()

rawDescription: How to return a single value instead of a tuple?

description: Return a single value instead of a tuple


code: text = u"Áno"

rawDescription: Method isupper unicode friendly

description: Method isupper unicode friendly


code:
dct = lst[0]
{'applicationName': "ATM Monitoring",
                     'roamingDrop': "",
                     'noOfCustomer': None,
                     'ipAddress': "192.168.1.1",
                      'url': "www.google.co.in",}

rawDescription: python one liner code for two nested for loop

description: Python one liner code for two nested for loop


code: plt.fill_between(xdata, 0, ydata)

rawDescription: Matplotlib fill_between() workaround

description: Matplotlib fill_between() workaround


code:
class ProgrammingCategory(models.Model):
    name = models.CharField(max_length=200)

class ProgrammingLanguage(models.Model):
    category = models.ForeignKey(ProgrammingCategory, related_name='languages')
    name = models.CharField(max_length=300)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    planguages = models.ManyToManyField(ProgrammingLanguage)

rawDescription: Django options field with categories

description: Django options field with categories


code:
results = dict()
for k in features.keys():
    results[k] = dict()
    for m in classifiers.keys():
        print(len(features[k]))
        results[k][m] = classifiers[m].fit(features[k], 'species', iris)

rawDescription: What's wrong here? accidentally referencing an existing instance instead of making a new one


code:
binary_string = struct.pack('2f', 1,2)
binary_string
numpy.frombuffer(binary_string, dtype=np.dtype('complex64'))

rawDescription: Python: unpacking string of floats to complex numbers


code:
sonnets = "SONNET 1\n\nFrom fairest creatures we desire increase, That thereby beauty's rose might never die, But as the riper should by time decease, His tender heir might bear his memory: But thou, contracted to thine own bright eyes, Feed'st thy light's flame with self-substantial fuel, Making a famine where abundance lies, Thyself thy foe, to thy sweet self too cruel. Thou that art now the world's fresh ornament And only herald to the gaudy spring, Within thine own bud buriest thy content And, tender churl, makest waste in niggarding. Pity the world, or else this glutton be, To eat the world's due, by the grave and thee.\n\nSONNET 2\n\nWhen forty winters shall beseige thy brow, And dig deep trenches in thy beauty's field, Thy youth's proud livery, so gazed on now, Will be a tatter'd weed, of small worth held: Then being ask'd where all thy beauty lies, Where all the treasure of thy lusty days, To say, within thine own deep-sunken eyes, Were an all-eating shame and thriftless praise. How much more praise deserved thy beauty's use, If thou couldst answer 'This fair child of mine Shall sum my count and make my old excuse,' Proving his beauty by succession thine! This were to be new made when thou art old, And see thy blood warm when thou feel'st it cold."
L=[{'title':title, 'content': content} for title, content in zip(*[iter(sonnets.split("\n\n"))]*2)]
L[0]['title']
L[0]['content']
L[1]['title']
L[1]['content']

rawDescription: how do i create a list of dict in python with the data been read from a text file?

description: Create a list of dict in python with the data been read from a text file


rawDescription: Python regex for unicode capitalized words


code:
{
    u'_id': ObjectId('50f99b4a9f956a1924000000'),
    u'foo': Binary('YWpza2xkZmpha2xzZGpma2xhc2RqZg==', 0)
}

rawDescription: Python & MongoDB - How to find by BinData type


code: blackList = [line.strip().lower() for line in file]

rawDescription: Applying changes to elements in array

description: Applying changes to elements in array


code: event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE,fill = color, width=linesize, tag="line")

rawDescription: Python tkinter delete event.widget.create_line


code: ts = np.array(t, dtype=dt)

rawDescription: ValueError while trying to convert an array of strings to an array with mixed given dtypes


code:
(('VUVV', 'DDRV'), 'DDVG')
# you will get
('VUVV', 'DDRV', 'DDVG') # == ('VUVV', 'DDRV')+ ('DDVG',)

rawDescription: Nested dictionary

description: Nested dictionary


code:
details = site.select('//*[@id="detailFacts"]/div[1]|div[2]/div[2]//text()').extract()
item['details'] = next(s for s in details if s)  # getting first not-empty item from the list

rawDescription: Scrapy xpath how to

description: Scrapy xpath how to


code:
if infile is None:
  infile = open(filename, 'r')
with infile:
  data = infile.read()

rawDescription: "Initializing" a constant containing a file in python?


code:
def method1(name):
    def wrapper(greeting):
        return greeting + name
    return wrapper

def method2(method, question):
    output = method(greeting = 'Hello ')
    return output + ', ' + question

method2(method1(name = 'Sam'), 'How are you?')

rawDescription: What is the best way to pass a method (with parameters) to another method in python


code:
from collections import defaultdict
method_dict = defaultdict(lambda: do_exit)

# Try this
method_dict["do_quit"]()

rawDescription: elegant way of setting multiple methods to equal another method

description: Elegant way of setting multiple methods to equal another method


code:
fig, ax2 = plt.subplots(1, 1)

im = rand(400, 400)
ax2.imshow(im, interpolation='none', extent=[-1, 1, -1, 1])

rawDescription: Fits image input to a range in plot - Python


code:
from itertools import islice
my_list = [1, 2, 3, 4]
for item in islice(my_list, len(my_list) - 1):
    print(item)

rawDescription: loop until list element N-1

description: Loop until list element N-1


code:
for func in registry.get(eventname, ()):
    func()

rawDescription: Is this possible with decorators?

description: Is this possible with decorators


code:
df = pd.DataFrame(['a c', 'b d'], columns=['foo'])
df['bar'] = df['foo'].str.split(' ').str.join('-')
print(df)

rawDescription: Efficiently adding a new column to a Pandas DataFrame with values processed from an existing column?


code:
g = df.groupby(['source', 'id'])
g.apply(lambda x : x[x['time'] > (x['time'].iloc[-1] - dt.timedelta(7))])

rawDescription: pandas groupby X,Y and select last week of X1 and X2 (which have diff frequency)

description: Pandas groupby X,Y and select last week of X1 and X2 (which have diff frequency)


rawDescription: Converting a string to a datetime

description: Converting a string to a datetime


code:
# Keep the last copy with a given link but order not preserved in result
kept_last = {x.link: x for x in nonuniquelist}.values()

# Keep the first copy with a given link but order not preserved in result
kept_first = {x.link: x for x in reversed(nonuniquelist)}.values()

rawDescription: It's possibile to use set function on a object basing only one attribute?


code:
import numpy as np
import scipy.sparse as sparse

N, M = 70000, 80000
A = sparse.rand(N, M, density=0.001).tocsr()
B = sparse.rand(1, M, density=0.001).tocsr()

rawDescription: Add scipy sparse row matrix to another sparse matrix


rawDescription: Python regex removing word with regex

description: Python regex removing word with regex


rawDescription: Check if element are in same paragraph (Beautiful soup)


code:
if search in skus:
    skus[search].displaySKU()

rawDescription: Can't get python to read/display my variable


rawDescription: Read .nc (netcdf) files using python

description: Read .nc (netcdf) files using python


code:
def basicConfig():
    _acquireLock()
    try:
        if len(root.handlers) == 0:
            h = StreamHandler(None)
            handlers = [h]
            dfs = None
            style = '%'
            fs = kwargs.get("format", _STYLES[style][1])
            fmt = Formatter(fs, dfs, style)
            for h in handlers:
                if h.formatter is None:
                    h.setFormatter(fmt)
                root.addHandler(h)
    finally:
        _releaseLock()

rawDescription: Python StringIO is not correctly capturing data from stderr


rawDescription: Select integers from a given range

description: Select integers from a given range


code:
import example
factory = example.SpamFactory()
spam = factory.make("a" * 21)
spam.x
spam.x *= 2
spam.x
factory.consume(spam)
spam.x = 100

rawDescription: Boost.Python: How to expose std::unique_ptr


code:
values = xw.Range(1, 'Named range').value
values[1][1] = 'yes'
xw.Range(1, 'Named range').value = values

rawDescription: How assign value to one cell in named range by using xlwings?


rawDescription: Select row prior as.freq() occurance

description: Select row prior as.freq() occurance


code:
df
df.iloc[:, 0] == df.iloc[:, 2]

rawDescription: Column to Column match using pandas or numpy in Python


code:
iterables = [['bar', 'baz', 'foo', 'qux'], pd.Index([datetime.date(2014, 10, 3)])]
columns = pd.MultiIndex.from_product(iterables)
df.columns = columns

rawDescription: How can I keep this Pandas column type as datetime when using MultiIndex?

description: Keep this Pandas column type as datetime when using MultiIndex


code:
out = []
for ll in l:
    obj = Generic()
    for attr, val in ll:
        setattr(obj, attr, val)
    out.append(obj)

rawDescription: Python create list of objects from list of 2 elements lists


rawDescription: Grouping model objects in Django

description: Grouping model objects in Django


rawDescription: numpy sum antidiagonals of array

description: Numpy sum antidiagonals of array


code:
for matchingdiv in tree.xpath('div[contains(@class,"cont")]'):
    # skip those without a h3 > a setup.
    link = matchingdiv.xpath('.//h3//a')
    if not link:
        continue

    # grab the `p` text and of course the link.

rawDescription: Iterating Over Elements and Sub Elements With lxml


code:
import get_foo, get_bar, get_baz

commands = dict(foo=get_foo.foo, bar=get_bar.bar, baz=get_baz.baz)

def call_command(cmd):
    return commands[cmd]()

rawDescription: best practices: dynamic method execution in python

description: Best practices: dynamic method execution in python


code:
output = ['a', 'b', 'c', 'd', 'e',]

# format each column (len(a)) with a width of 10 spaces
width = [10]*len(a)

# write it out, using the join() function
with open('output_example', 'w') as f:
    f.write(''.join('%*s' % i for i in zip(width, output)))

rawDescription: How do i format the ouput of a list of list into a textfile properly?

description: Format the ouput of a list of list into a textfile properly


code:
class Instrument(models.Model):
    name = models.CharField(max_length=100)

class Musician(models.Model):
    firstname = models.CharField(max_length=100)
    instrument = models.ForeignKey(Instrument)

rawDescription: Python / Django : emulating a multidimensional layer on a MySQL database


code:
def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    bar = Bar()
    bar.show()
    sys.exit(app.exec_())

rawDescription: multiple classes in PyQt4

description: Multiple classes in PyQt4


rawDescription: Python HTML table scrape (Print)

description: Python HTML table scrape (Print)


code: first != 5 or second != 5 or third != 5

rawDescription: Python nested loops issues

description: Python nested loops issues


rawDescription: How to parse optional arguments using python argparse?

description: Parse optional arguments using python argparse


rawDescription: Numpy operation of arrays with different size


code:
from __future__ import print_function
print('a','b',sep='\t')

rawDescription: python : comma in print as "\t"

description: Python : comma in print as "\t"


code:
# Assumes msb first, lsb last, bits is iterable of integers in [0,1]
def bits2int(bits):
    v = 0
    for b in bits:
        v <<= 1
        v += b
    return v

rawDescription: Python dynamic bit manipulation example

description: Python dynamic bit manipulation example


code:
def wfsc_combined(self):
    output = []
    output.append("%s\t%s\t%s" % (self.name[0], self.subnet[0], self.gateway[0]))
    for ip in range(100,110):
        output.append("192.168.1.%d" % ip)
    return '\n'.join(output)

rawDescription: Python - List and Loop in one def

description: Python - List and Loop in one def


rawDescription: 2to3 range(...) -> list(range(...))

description: 2to3 range(...) -> list(range(...))


rawDescription: Python Tuple Comparison not working for multiple less than, more than


code:
def Person_Link(self):
    return "<a href='/admin/sweetspotModel/persons/%s/' target='_blank'>Person Details<a/>" % self.contactid.contactid
Person_Link.allow_tags = True

rawDescription: Django Admin Panel. Display and Edit Parent Fields in Child's Object (ModelAdmin.inlines reverse)


code:
def wrapper(fn, params, keyword_params):
    return fn(*params, **keyword_params)

def myfunc(a, b, c=0):
    return (a + b)/c

wrapper(myfunc, (2, 5), {'c': 3})

rawDescription: How do I call a function with arbitrary parameters from another function?

description: Call a function with arbitrary parameters from another function


rawDescription: Making a sequence of tuples unique by a specific element


code:
import pandas as pd
import numpy as np
np.random.seed(1)

def setup(regular=True):
    N = 10
    x = np.arange(N)
    a = np.arange(N)
    b = np.arange(N)

    if regular:
        timestamps = np.linspace(0, 120, N)
    else:
        timestamps = np.random.uniform(0, 120, N)

    df = pd.DataFrame({
        'Category': [True]*N + [False]*N,
        'Time': np.hstack((timestamps, timestamps)),
        'Value': np.hstack((a,b))
        })
    return df

df = setup(regular=False)
df.sort(['Category', 'Time'], inplace=True)

rawDescription: Customizing rolling_apply function in Python pandas


code:
if kind in fix_targets:
    for col_index in fix_targets[kind]:
        data[col_index] += "0000"

rawDescription: Optimal way to replace characters in large string with Python?


code:
lst = [a,d,e,g,h,j]
nm_lst = ['a', 'b', 'd', 'e', 'h', 'j']
for i,nm in zip(lst,nm_lst):
    pickle.dump(i,open('{0}.p'.format(nm),'wb'))

rawDescription: How to assign pickle name dynamically in Python?

description: Assign pickle name dynamically in Python


code: presents = re.split(r'\s*,\s*', presents)

rawDescription: re.findall - Getting a list of items from a comma delimited string

description: Re.findall - Getting a list of items from a comma delimited string


rawDescription: Extracting text from XML node with minidom


code:
import heapq

k_keys_sorted = heapq.nlargest(k, dictionary)

rawDescription: finding top k largest keys in a dictionary python

description: Finding top k largest keys in a dictionary python


code: pixelpoints = cv2.findNonZero(mask)

rawDescription: How to efficiently locate and save pixels with a certain value using OPENCV?

description: Efficiently locate and save pixels with a certain value using OPENCV


code:
def removekey(d, key):
    r = dict(d)
    del r[key]
    return r

rawDescription: Delete an element from a dictionary

description: Delete an element from a dictionary


code:
# pylung.py
def deutsch():
    import os
    os.durchlaufe = os.walk
    # etc...

rawDescription: Replace object with another in the entire process / become in Python


code:
list1 = [(12, "AB", "CD"), (13, "EF", "GH"), (14, "IJ", "KL")]
next(i for i,x in enumerate(list1) if 13 in x)

rawDescription: How do I return the index of a group of values from a list for a specific value in the group?

description: Return the index of a group of values from a list for a specific value in the group


code:
(rfft[0] * rfft[0].conj() +
 2 * np.sum(rfft[1:] * rfft[1:].conj())).real / len(y)

rawDescription: (numpy) Wrong amplitude(?) of FFT'd array?


code: result = {k: int(v) for k, v in zip("abcdefgh", match.groups())}

rawDescription: Dictionary from parsed text. Simpler way to create?


code: s = s + (' ' * padsize)

rawDescription: How to make sure the input is a multiple of 16, and if not add padding to it

description: Make sure the input is a multiple of 16, and if not add padding to it


code:
L = [10,20]
L1 = []
for i in L:
    L2 = [] # initialize a new list
    for j in range(i):
        if not (j%3 and j%5): # use falsy values and DeMorgan's Law
            L2.append(j) # append to this list
    if L2: # use this if you don't want to keep empty lists
        L1.append(L2)

rawDescription: Multiples of 3 and 5

description: Multiples of 3 and 5


code:
_distance_wrap.cdist_euclidean_wrap(_convert_to_double(XA),
                                    _convert_to_double(XB), dm)

rawDescription: Calculate the euclidean distance in scipy csr matrix


code:
import urllib2

data = "{'email':{'email':'example@email.com'}}"
req = urllib2.Request("http://some/API/endpoint", data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()

rawDescription: Passing structs through urllib2

description: Passing structs through urllib2


code:
cl = g.community_fastgreedy().as_clustering()
crossing_edges = [index for index, is_crossing in enumerate(cl.crossing()) if is_crossing]

rawDescription: A scalable function for get boundary vertices in a graph


code:
d = {'key1': 'value1', 'key2': 'value2'}
['{}_{}'.format(k,v) for k,v in d.iteritems()]

rawDescription: Python getting a string (key + value) from Python Dictionary


code:
col_prefix = "Base (MW) "
for col in ['Allocated', 'Bought', 'Sold', 'Remaining']:
    df[col] = baseMultiply(df, col_prefix + col)

rawDescription: Refactoring a bad 'code smell' in multiplication of columns in a dataframe


code:
np.size(x, 0)
np.size(x, 1)

rawDescription: Use size in Python

description: Use size in Python


rawDescription: analyzing a txt file in python by jumping the n_th element of a list

description: Analyzing a txt file in python by jumping the n_th element of a list


code:
import re
re.search(r"^/(?P<path>(?!special/).*)$", '/special/path') is None
re.search(r"^/(?P<path>(?!special/).*)$", '/not-so-special/path').groupdict()

rawDescription: Regex for everything except certain matches


code:
...
# I find the div by class_name, of course you can use xpath
select_birthday_month = driver.find_element_by_class_name('jfk-select')
select_birthday_month.send_keys('January')
...

rawDescription: Selenium, Selecting an element inside of a <span>


code:
import zmq, time
from datetime import datetime

context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://localhost:25647")

#filter message for particular subscriber ('1')
socket.setsockopt(zmq.SUBSCRIBE, '1')

while True:
    message = socket.recv()
    print(str(datetime.now().time()) + "> received: " + str(message))

rawDescription: Python: sharing message between processes


rawDescription: zipped array returns as <zip object at 0x02B6F198>

description: Zipped array returns as <zip object at 0x02B6F198>


code: string = ''.join('[%s%s]' % (x[1:], self.obj[x]) for x in self.obj)

rawDescription: Simplification of iterating

description: Simplification of iterating


code:
# nothing for a while
write_port("pwm_0.period", 0)
my_run(200)

# start a waveform
write_port("pwm_0.period", 100)

# see it operate for 2 cycle)
my_run(230)

# change duty cycle
write_port("pwm_0.duty", 10)
my_run(200)

# change period
write_port("pwm_0.period", 50)
my_run(200)

rawDescription: How to avoid typing the arguments to run() all the time

description: Avoid typing the arguments to run() all the time


code: sortedlist = [(k, a[k]) for k in sorted(a)]

rawDescription: Sorting a dictionary having keys as string of numbers in python


rawDescription: Better algorithm to riffle shuffle (or interleave) multiple lists of varying lengths


code:
[u'HeaderName1', u'Parent', u'Parent']
[u'HeaderName1', u'Parent', u'Child1']
[u'HeaderName1', u'Parent', u'Child2']
[u'HeaderName2', u'Parent2', u'Parent2']
[u'HeaderName2', u'Parent2', u'Child4']
[u'HeaderName2', u'Parent2', u'Child5']

rawDescription: How do you use Beautiful Soup to pull out list items that have certain class attributes?

description: Use Beautiful Soup to pull out list items that have certain class attributes


code:
__a = 3
class B:
    def __init__(self):
        self.a = globals()["__a"]
b = B()

rawDescription: How to access private variable of Python module from class

description: Access private variable of Python module from class


code: isinstance([], (tuple, list, set))

rawDescription: Determine the type of an object?

description: Determine the type of an object


code: np.arange(n) - np.repeat(csum - occupations, occupations) + np.repeat(idx_unique_objIDs, occupations)

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


rawDescription: writing "dictionary of dictionaries" to .csv file in a particular format

description: Writing "dictionary of dictionaries" to .csv file in a particular format


rawDescription: compare similar items nested in a list, and removing them

description: Compare similar items nested in a list, and removing them


code:
df = read_data(data1, known_states, DF_columns)
df = df.append(read_data(data2, known_states, DF_columns), ignore_index=True)
df = df.append(read_data(data3, known_states, DF_columns), ignore_index=True)
# and so on...

rawDescription: Inexpensive way to add time series intensity in python pandas dataframe


rawDescription: Adding the product of an element of a list to an existing list in Python


code:
import matplotlib.cm as cm
import numpy as np

colormap =cm.get_cmap("jet")
different_colors=10
color_mapping=colormap(np.linspace(0,1,different_colors),1,True)
bokeh_palette=["#%02x%02x%02x" % (r, g, b) for r, g, b in color_mapping[:,0:3]]

p=Bar(df,label='nr',values='data',stack='rank',legend='top_right',palette=bokeh_palette)
show(p)

rawDescription: Moving a stacked bar that that worked in Bokeh 0.9 to Bokeh 0.11


rawDescription: Using Python 3 with Python 2

description: Using Python 3 with Python 2


code:
import re
string = 'AASKH317298DIUANFProgramming is fun'
re.sub(r'^[A-Z0-9]*(?![a-z])', '', string)

rawDescription: Python Regex - checking for a capital letter with a lowercase after


code:
for d in products:
    for k in d:
        if d[k] and k in ok2split: d[k] = d[k].split(';')

rawDescription: Convert a colon separated string to a list - within a list of dictionaries... (Python)


code:
class Label(models.Model):
    label = models.CharField(max_length=200)
    labelname = models.CharField(max_length=200)

class LabelWord(models.Model):
    word = models.CharField(max_length=30)
    position = models.IntegerField()
    label = models.ForeignKey(Label)

rawDescription: How to annotate/aggregate each item in a list without for loops (Django)

description: Annotate/aggregate each item in a list without for loops (Django)


code:
for k in frames.keys():
    series_dict[k].name = 'New_Name'

rawDescription: Rename Pandas column inside Python dictionary


code:
words = []
word = input('Word: ')
while word != '':
    if word not in words:
        words.append(word)
    word = input('Word: ')
print("You know "+ str(len(words)), "unique word(s)!")

rawDescription: How to not count the duplicates from an user input?

description: Not count the duplicates from an user input


code:
ListOne = ['jumps', 'over', 'the']
ListTwo = ['The', 'quick', 'brown', 'fox'] + ListOne + ['lazy', 'dog!']

rawDescription: Python 2: insert existing list inside of new explicit list definition


code:
class MyClass(object):
    myattrib = None

    def __setattr__(self, prop, val):
        super().__setattr__('myattrib', val)
        print("setting myattrib")

rawDescription: How to call __setattr__() correctly in Python3 as part of a class?

description: Call __setattr__() correctly in Python3 as part of a class


code:
string1 = 'This is a test trees are green roses are red'
string2 = 'This iS a TEST trees 12.48.1952 anthony gonzalez'
merged = merge(string1.lower().split(), string2.lower().split())
' '.join(' '.join(x) for x in merged)

rawDescription: How to find union of two strings and maintain the order

description: Find union of two strings and maintain the order


code:
soup = BeautifulSoup.BeautifulSoup(your_data)
while True:
    h2 = soup.find('h2')
    if not h2:
        break
    h2.name = 'h1'

rawDescription: How to change tag name with BeautifulSoup?

description: Change tag name with BeautifulSoup


code: number

rawDescription: strip string from url in Python

description: Strip string from url in Python


code:
def plus():
    var += 1

dis.dis(plus)

rawDescription: When does Python recognize/not recognize variables from main?


code: ['replacement' if a[i+1]=='b' else v for i,v in enumerate(a[:-1])]+[a[-1]]

rawDescription: Increment the next element based on previous element


code:
from nltk import Tree
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget

cf = CanvasFrame()
t = Tree.fromstring('(S (NP this tree) (VP (V is) (AdjP pretty)))')
tc = TreeWidget(cf.canvas(),t)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file('tree.ps')
cf.destroy()

rawDescription: Saving nltk drawn parse tree to image file


code: [{'date': u'2011-08-01', 'plans': {u'PLAN_B': True, u'PLAN_C': True, u'PLAN_A': True, u'PLAN_F': True, u'PLAN_G': True, u'PLAN_D': True, u'PLAN_E': True}}, {'date': u'2011-08-22', 'plans': {u'PLAN_B': False, u'PLAN_C': True, u'PLAN_A': True, u'PLAN_F': False, u'PLAN_G': True, u'PLAN_D': True, u'PLAN_E': True}}]

rawDescription: generate html table with potentially expanding columns and need to reordering columns, using django

description: Generate html table with potentially expanding columns and need to reordering columns, using django


code:
import sublime_plugin

class PrintSelectionTextCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        for region in view.sel():
            print(view.substr(region))

rawDescription: Sublime Text 2 plugin: capture the selected text


code:
CATIA.RefreshDisplay = False
CATIA.DisplayFileAlerts = False

rawDescription: Run a Catia macro with a python script

description: Run a Catia macro with a python script


code:
import numpy
import matplotlib.pyplot as plt

X = [0, 1, 2]
Y = [4, 6, 4]

plt.plot(X,Y)
axes = plt.axis()
plt.plot([X[-2],X[-2]+1000*(X[-1]-X[-2])], [Y[-2],Y[-2]+1000*(Y[-1]-Y[-2])])
plt.xlim( [axes[0], axes[1]])
plt.ylim( [axes[2], axes[3]])
plt.show()

rawDescription: Matplotlib continuing line into infinity


code:
import itertools
z = [(x[0], len(list(x[1]))) for x in itertools.groupby(a)]
z

rawDescription: find maximum length of consecutive repeated numbers in a list (python)

description: Find maximum length of consecutive repeated numbers in a list (python)


rawDescription: How to access way coordinates from a large (.json-based) list structure

description: Access way coordinates from a large (.json-based) list structure


code:
with open('dataset3.txt') as f:
    Matrix = [map(float, line.split()) for line in f]

rawDescription: How to load dataset in libsvm python

description: Load dataset in libsvm python


code:
if request.is_ajax():
    uploaded = request.body
    newstring = "{\"testdata\": [" + uploaded + "]}"
    data = json.loads(newstring)
    num_lines = sum(len(v) for v in data.itervalues())
    testing(data, num_lines)

    zip_subdir = 'testapi'
    zip_filename = '%s.zip' % zip_subdir

    zf = z.ZipFile(zip_filename, mode='w')
    zf.write('Test.xlsx')
    zf.close()

if request.method == 'POST':
    zip_file = open('testapi.zip', 'rb')
    response = HttpResponse(zip_file, content_type='application/x-zip-compressed')
    response['Content-Disposition'] = 'attachment; filename=%s' % 'testapi.zip'
    return response

rawDescription: Python zipfile not being delivered to user


code:
def answers(self, other):
    if not isinstance(other,IP):
        return 0
    if conf.checkIPaddr and (self.dst != other.src):
        return 0
    if ( (self.proto == socket.IPPROTO_ICMP) and
         (isinstance(self.payload, ICMP)) and
         (self.payload.type in [3,4,5,11,12]) ):
        # ICMP error message
        return self.payload.payload.answers(other)

    else:
        if ( (conf.checkIPaddr and (self.src != other.dst)) or
             (self.proto != other.proto) ):
            return 0
        return self.payload.answers(other.payload)

rawDescription: What defines Scapy send / receive?

description: What defines Scapy send / receive


rawDescription: Making missing time slots and filling in 0 values in a Pandas series?


rawDescription: Sorting a list of list of tuples based on the sum of first field in the tuple in Python


rawDescription: Creating a Dictionary with a list of values by appending in python


rawDescription: Recursive function for tuple

description: Recursive function for tuple


code:
def fileSelection(self):
    selection = listbox.curselection()
    print(selection)

rawDescription: Returning the index of an item clicked in a tkinter Listbox


code:
[(False, False, False),
 (False, False, True),
 (False, True, False),
 (False, True, True),
 (True, False, False),
 (True, False, True),
 (True, True, False),
 (True, True, True)]

rawDescription: python build a dynamic growing truth table

description: Python build a dynamic growing truth table


code:
def use_from(step_todo, *args):
    use_all(step_todo, True, *args)

rawDescription: Python: Using defined arguments with *args


code:
# open up the dropdown
dropdown = driver.find_element_by_css_selector("ul.level1")
dropdown.click()

# select element
item = dropdown.find_element_by_xpath("//li[@id='m1_m5']/following-sibling::li")
item.click()

rawDescription: How to click on drop down menu in Python using Selenium and Chrome

description: Click on drop down menu in Python using Selenium and Chrome


code: a,b,c = map(list,zip(*l))

rawDescription: Pass each nested list as an arg to map

description: Pass each nested list as an arg to map


rawDescription: Creating a table out of data in python

description: Creating a table out of data in python


code: sorted(sorted(['Bear', 'bear', 'Apple', 'apple'], reverse=True), key=str.lower)

rawDescription: How to sort a list in python to make lowercase precede uppercase?

description: Sort a list in python to make lowercase precede uppercase


code:
result, last = [], 0.0
for d in data:
    result.extend((r,0) for r in range(int(last), int(d[0])))
    result.append(d)
    last = d[0]+1

rawDescription: Python - filling a list of tuples with zeros in places of missing indexes


code: worksheet.insert_chart(3, 4, chart)

rawDescription: Calculate relative positions using xlsxwriter


rawDescription: python regular expression replace two situations with one command

description: Python regular expression replace two situations with one command


rawDescription: How can I obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy?

description: Obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy


code:
# <INSTALLED_ADDONS>
...
# </INSTALLED_ADDONS>

rawDescription: Aldryn - how to add own Django apps and its dependencies


code:
from collections import defaultdict

newdict = defaultdict(lambda: [0])
for key in olddict:
    newdict[(key.year, key.month)][0] += olddict[key][0]

rawDescription: Modifying a dictionary with datetime as keys


code: instanceList = [MyClass(arg) for arg in args]

rawDescription: Rapid Class Declaration

description: Rapid Class Declaration


code:
with open(outFileName, 'w') as f:
     for city, values in d.items():
        values.sort(key=lambda fn: map(int, os.path.splitext(fn)[0].split('_')))
        f.write('{} {}\n'.format(city, ' '.join(values)))

rawDescription: Sort os.listdir files Python

description: Sort os.listdir files Python


code:
import optparse

class PlainHelpFormatter(optparse.IndentedHelpFormatter):
    def format_description(self, description):
        if description:
            return description + "\n"
        else:
            return ""

parser = optparse.OptionParser(
    prog='./spill.py',
    formatter=PlainHelpFormatter(),
    description=u'''
  /     \
  vvvvvvv  /|__/|
      I   /O,O   |
      I /_____   |      /|/|
     J|/^ ^ ^ \  |    /00  |    _//|
      |^ ^ ^ ^ |W|   |/^^\ |   /oo |
       \m___m__|_|    \m_m_|   \mm_|
''',
    epilog='''
        Las cucarachas lograron con exito su plan, echando a los pestilentes sangre caliente de sus cajas de cemento.
Ahora el hombre es una especie errante en el espacio, un vagabundo errante en las estrellas.''')
(opt,args) = parser.parse_args()

rawDescription: ASCII art in the optparse description

description: ASCII art in the optparse description