code:
from __future__ import division
from random import gauss
import time
import redis

class MyStreamMonitor(object):
    def __init__(self):
        self.sum   = 0
        self.count = 0
        self.r = redis.StrictRedis()
    @property
    def mu(self):
        if self.count >1:
            outv = self.sum/self.count
        else:
            outv = 0
        return outv
    def generate_values(self):
        while True:
            yield gauss(0,1)
    def monitor(self):
        for x in self.generate_values():
            self.sum   += x
            self.count += 1

            # This is the magic here
            self.r.publish('count', self.count)
            self.r.publish('mu', self.mu)

if __name__ == '__main__':
    stream = MyStreamMonitor()
    stream.monitor()

rawDescription: Use a class to monitor a data stream and print reports to two different windows at different time intervals in python


code:
class C(object):
    @classmethod
    def my_class_method(cls, foo, bar):
        pass

c.my_class_method(1, 2)

rawDescription: Can python have class or instance methods that do not have "self" as the first argument?


code:
import sys

if sys.version_info[0] >= 3:
    from urllib.parse import urlparse
else:
    from urlparse import urlparse

class DataSource(object):

    def _isurl(self, path):
        scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path)
        return bool(scheme and netloc)

    @staticmethod
    def _isurl_staticmeth(path):
        scheme, netloc, upath, uparams, uquery, ufrag = urlparse(path)
        return bool(scheme and netloc)

rawDescription: Why is `_isurl` an instance method rather than a static method of a numpy `DataSource`?


code:
import statsmodels.formula.api as smf
dat = pd.read_csv('wow.csv')
mod = smf.ols('levels ~ week + character + guild', data=dat).fit()

rawDescription: OLS Regression: Scikit vs. Statsmodels?

description: OLS Regression: Scikit vs. Statsmodels


code:
def foo(x=5):
    return x

assert foo() == 5
with mock.patch.object(foo, 'func_defaults', (10,)):
    assert foo() == 10

assert foo() == 5  # Oops; I'm observing foo.func_defaults to be None now

rawDescription: Change default arguments of function in python


code: df.columns = ['{}_{}'.format(t, v) for v,t in df.columns]

rawDescription: Pandas: break categorical column to multiple columns


code: links = [a['href'] for a in soup.find_all('a',href=re.compile('http.*\.(mp3|wav|ogg|wma)'))]

rawDescription: Finding all Audio Links in a page using python


code: reduce(getattr, x.split('.'), value)

rawDescription: How can I use getattr to access an attribute within an attribute?

description: Use getattr to access an attribute within an attribute


code:
init()
run()

rawDescription: Why wont collide_rect work in this scenario? The game keeps printing "Collided!" even when the two sprites aren't touching?


rawDescription: How do I make a list a key value in a dictionary?

description: Make a list a key value in a dictionary


code:
def multiplier(n, d):
    """Return a function that multiplies its argument by n/d."""
    def multiply(x):
        """Multiply x by n/d."""
        return x * n / d
    return multiply

rawDescription: What is a cell in the context of an interpreter or compiler?


code:
for k, v in res.items():
    print(str(k) + ": " + str(v))

rawDescription: Append list items by number of hyphens available


code:
_map = {}
def phred64ToStdqual2(qualin):
    if not _map:
        for i in range(31, 127):
            _map[chr(i)] = chr(i - 31)
    return ''.join(map(_map.__getitem__, qualin))

rawDescription: Convert ascii encoding to int and back again in python (quickly)


code:
class CalcUpdate(SuccessMessageMixin, UpdateView):
    model = Calc
    template_name = 'calc/cru_template.html'
    form_class = CalcForm

    def archive_calc(self, object_id):
        model_a = Calc.objects.get(id = object_id)
        model_b = Calc()

        for field in model_a._meta.fields:
            setattr(model_b, field.name, getattr(model_a, field.name))
        model_b.pk = None
        model_b.save()

        return self.get_success_url(idnumber = model_b.pk) # you never return this value

    def form_valid(self, form):
        #objects
        if self.object.checked == True:
            object_id = self.object.id
            return HttpResponseRedirect(self.archive_calc(object_id)) # you never return a `HttpResponse`
        #save  -- If this is where you are saving... you can store the value from archive and return it after saving

    def get_success_url(self, **kwargs):
        if  kwargs != None:
            return reverse_lazy('detail', kwargs = {'pk': kwargs['idnumber']})
        else:
            return reverse_lazy('detail', args = (self.object.id,))

rawDescription: Django success url using kwargs

description: Django success url using kwargs


rawDescription: Print a dictionary of lists vertically

description: Print a dictionary of lists vertically


rawDescription: Print a nested list line by line - Python


code: datetime.datetime.strptime('Wed 15 Jul 2015 15:39:33 GMT','%a %d %b %Y %H:%M:%S %Z')

rawDescription: How do I get the recent json object based on datetime value?

description: Get the recent json object based on datetime value


code:
def parse(self, response):
    # Loop all the product elements
    for product in response.xpath('//div[@class="listing-item"]'):
        item = ArcherItemGeorges()
        product_name = product.xpath('.//*[@class="product-shop"]/h5/a/text()').extract()[0].strip()
        item['product'] = product_name
        item['price'] = product.xpath('.//*[@class="price-box"]/span/span[@class="price"]/text()').extract()[0].strip()
        # Yield the raw primary item
        yield item
        # Yield the primary item with its secondary items
        for subproduct in product.xpath('.//*[@class="more-views"]/following-sibling::div'):
            item['product'] = product_name + ' ' + subproduct.xpath('a/text()').extract()[0].strip()
            item['price'] = subproduct.xpath('text()[2]').extract()[0].strip()
            yield item

rawDescription: SOLVED: How do I create a "Nested Loop" that returns an item to the original list in Python and Scrapy


code:
tick_start = np.argmin(abs(clevs1-clevs[0]))
cbar.ax.set_xticklabels(clevs1[tick_start:],rotation=90)

rawDescription: Rotation of colorbar tick labels in matplotlib


rawDescription: Not sure how to XPath to specific website element


rawDescription: Creating numpy array with empty columns using genfromtxt


code:
# settings.py
default_settings = Settings()
my_settings = Settings(foo=False)
current_settings = my_settings.copy()
current_settings.foo = False    # pointless example

rawDescription: how to override default values needed by function in module?

description: Override default values needed by function in module


code: result = sum(np.minimum(ar, 1) for ar in list_of_arrays)

rawDescription: Numpy: find occurrences for non-zero values, grouped by index


code: fetchButton = Button(frame, text="Fetch",command=self.handle)

rawDescription: Adding python functionality to Tkinter front end


code:
g = df.groupby('Browser')
g['Metric1'].max()
over2000 = g['Metric1'].max() > 2000
over2000

rawDescription: Filter DataFrame based on Max value in Column - Pandas


code:
my_list = ['blahblah','asdas']
[m for m in my_list if 'blahblah' in m]

rawDescription: Python: Having difficulty filtering out strings containing certain substrings


rawDescription: How to index numpy array on subset of array of bools that is smaller than numpy array's dimensions?

description: Index numpy array on subset of array of bools that is smaller than numpy array's dimensions


code:
import types
class MyClass(object):
    def function(self):
        pass

m = MyClass(object)
m.function = types.MethodType(decorator(MyClass.function), m)

rawDescription: How to retrieve arguments from a "fluid" decorated function

description: Retrieve arguments from a "fluid" decorated function


code: a = ("hello")

rawDescription: How to properly convert list of one element to a tuple with one element

description: Properly convert list of one element to a tuple with one element


code: people = [(key, value["position"], value["company"]) for key, value in data["people"].items()]

rawDescription: Efficiently find objects satisfying relationship


code:
Web_Keywd = 'car loan cheap'

results = {}
for word in Web_Keywd.split():
    for synset in wn.synsets(word):
        for lemma in synset.lemmas:
            results.setdefault(word, []).append(lemma.name)

rawDescription: Using NTLK properly with python

description: Using NTLK properly with python


code:
for k,g in egroup.groupby(df["event"]):
    print(g)

rawDescription: Find recurring events in time series with pandas


code:
for row in textfile:
    wrd += row.split()

rawDescription: Recreating a sentence using two text files (Python)


code:
outrow = [[1,2,3], [4,5,6], [7,8,9]]
import csv
import sys
w = csv.writer(sys.stdout)
w.writerows(zip(*outrow))

rawDescription: Write each list as a column in csv table


code:
def word_exists(wordlist, word_fragment):
    return any(w.startswith(word_fragment) for w in wordlist)

rawDescription: Fastest way in Python to find a 'startswith' substring in a long sorted list of strings


code:
from bisect import bisect_left, bisect_right
left = bisect_left(keys, parsedate('05-22-2013'))
right = bisect_right(keys, parsedate('05-24-2013'))

rawDescription: Get Elements between two dates from a list


code:
dict = {}
for el in list:
    if el in dict:
        dict[el] += 1
    else:
        dict[el] = 1

max(dict.iteritems(), key=operator.itemgetter(1))[0] # This is your result

rawDescription: Find the Common first_name from Django Auth user Model


code:
try:
    # Python 2
    from string import maketrans
except ImportError:
    # Python 3
    maketrans = str.maketrans

def replace(original, char, replacement):
    map = maketrans(char, replacement)
    return original.translate(map)

rawDescription: Replacing a character in a stringin Python


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

distrNameList = ['beta', 'expon', 'gamma']
sample = stats.norm(0, 1).rvs(1000)
abscissas = np.linspace(0,1, 10)
for distrName in distrNameList:
    distr = getattr(stats.distributions, distrName)
    param = distr.fit(sample)
    pdf = distr.pdf(abscissas, *param)
    print(pdf)

rawDescription: Getting a pdf from scipy.stats in a generic way


code:
class Buffer(object):
    def __init__(self):
        self.size = 0
    def write(self, bytes):
        self.size += len(bytes)

f = Buffer()
plt.savefig(f, ...)
size = f.size

rawDescription: Estimate final size of image without writing it to disk with Python


code:
df['output'] = (df.groupby('a_id')
               .apply(lambda x : x['b_received'].isin(x['c_consumed']).astype('i4'))
               .reset_index(level='a_id', drop=True))

rawDescription: Compare values in 2 columns and output the result in a third column in pandas


code:
dff['Mean'] = dff.Nb_sales / dff.Nb_view
dff

rawDescription: np.mean for rows with specific values across multiple columns

description: Np.mean for rows with specific values across multiple columns


code: player_dict = {'player%s' % i : Player() for i in xrange(players)}

rawDescription: Generating Multiple Duplicate Objects

description: Generating Multiple Duplicate Objects


code:
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    # one-to-many with Topic
    topic = db.relationship('Topic', backref=db.backref('post', lazy='dynamic'))

def __init__(self, title, body, topic):
        self.title = title
        self.body = body
        self.topic = topic

class Topic(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

    def __init__(self, name):
        self.name = name

rawDescription: WTForms: setting default value from an SQLAlchemy field with relationship


code:
@property
def o(self):
    return 'o'

rawDescription: Python new style class can not use __dict__ to update property attribute


code:
def factorial_recurrence(x, position):
    return x * position

rawDescription: Issues with Recursion using Python 3

description: Issues with Recursion using Python 3


code:
for line in re.findall(r' (.*)', s):
    print(line)

rawDescription: Regex for this dataset

description: Regex for this dataset


code:
import ast
ast.literal_eval(b'0b11111111'.decode('utf8'))
ast.literal_eval(b'0xff'.decode('utf8'))

rawDescription: Python Comparison of byte literals

description: Python Comparison of byte literals


code:
import numba as nb

@nb.jit(nopython=True)
def sum_opt(arr1, arr2):
    s = arr1[0]*arr2[0]
    for i in range(1, len(arr1)):
        s+=arr1[i]*arr2[i]
    return s

@nb.jit(nopython=True)
def numba2(nx, nz, c, rho, a, b):
    for ix in range(2, nx-3):
        for iz in range(2, nz-3):
            a[ix, iz]  = sum_opt(c, rho[ix-1:ix+3, iz])
            b[ix, iz]  = sum_opt(c, rho[ix-2:ix+2, iz])
    return a, b

rawDescription: Optimize Double loop in python

description: Optimize Double loop in python


code:
def save(self, *args, **kwargs):
    super(YourModelName, self).save(*args, **kwargs)
    kwargs.update({'using' : 'orcl'})
    super(YourModelName, self).save(*args, **kwargs)

rawDescription: Push table data from django postgres model to remote oracle database


code:
from collections import OrderedDict
dct = OrderedDict()
dct['a'] = 1
dct['b'] = 2
dct['c'] = 3
dct
del dct['b']
dct

rawDescription: Delete a key and value from an OrderedDict


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

user_specified_value = 100.0
spread = 0.33
n = 1000

## uniform
accuracy = 0.01
costs = [0] * n
for i in range(0,n):
    costs[i] = random.random() * user_specified_value * accuracy
plt.scatter(range(0,n), costs)
plt.ylim(0, 100)

## triangular
accuracy = [0] * n
costs = [0] * n
for i in range(0,n):
    accuracy[i] = float(i)/n
    costs[i] = random.triangular(0.0,max(0.01,accuracy[i]),1.0) * user_specified_value
plt.scatter(accuracy, costs)

rawDescription: Generate random values based on a variable in Python


rawDescription: Trouble in Grouping similar files using Multi processing and ssdeep Python


code:
import subprocess
from Tkinter import *
import ttk

def btnCallback():
    #this is the path to your other script
    cmdpath = '/path/to/test.py'

    #extract the textbox variable
    var = stringadacercare.get()

    progressbar.start()

    #pass the variable to the command line
    proc = subprocess.popen([cmdpath,var])

    #block while the subprocess executes
    proc.wait()

    progressbar.stop()

app = Tk()
app.title('Myapp')
app.geometry('260x100+50+50')

labelText =StringVar()
labelText.set('Insert the version you want to check')
label1 = Label(app, textvar=labelText, height=4)
label1.pack()

stringadacercare = StringVar(None)
lastringa = Entry(app, textvar=stringadacercare)
lastringa.place(x=30, y=40, width=200)

progressbar = ttk.Progressbar(orient=HORIZONTAL, length=260, mode='determinate')
progressbar.pack(side='bottom')

#use a button to execute the subprocess
buttonOK = Button(app,text='GO',command=btnCallback)
buttonOK.pack(side='bottom')

app.mainloop()

rawDescription: I would like to pass the value entered into the textbox to a python program


code:
def per_word(filename):
    result = []

    with open(filename) as fh:
        for line in fh:
            for word in line.split():
                result.append(word)

    return result

rawDescription: Struggling with python generator function


rawDescription: If jinja markup is in string format, how do I use it in django and jinja2?


code:
import shutil

def save_uploaded_file (form_field, upload_dir):
    form = cgi.FieldStorage()
    if not form.has_key(form_field): return
    fileitem = form[form_field]
    if not fileitem.file: return

    outpath = os.path.join(upload_dir, fileitem.filename)

    with open(outpath, 'wb') as fout:
        shutil.copyfileobj(fileitem.file, fout, 100000)

rawDescription: Upload a File with Python

description: Upload a File with Python


code:
def func():
    """
    I am a function who doesn't do anything,
    I just sit in your namespace and crowd it up.
    If you call me expecting anything
    I'll just return to you the singleton None
    """
    pass

help(func)

rawDescription: How do I find information about a function in python?

description: Find information about a function in python


code:
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

def flatten(lists):
    results = []
    for i,lst in enumerate(lists): #for loop that loops through the indeces of list (the subsists)
        print("i=",i)
        for j,numbers in enumerate(lst): #for loop that loops through the indices of sub-lists (the numbers)
            print("j=",j)
            results.append(numbers)
    return results

rawDescription: How does the nested loop iterates?

description: How does the nested loop iterates


code: [i for i in range(2,244) if i not in s]

rawDescription: How can I count up by one by using or adding various numbers in a list?

description: Count up by one by using or adding various numbers in a list


code:
def parse(self, response):
    for sel in response.xpath('//ul[@class="nav_cat_links"]/li'):
        item = AmazoncrawlerItem()
        item['title'] = sel.xpath('a/text()').extract().pop()
        item['link'] = sel.xpath('a/@href').extract().pop()
        item['desc'] = sel.xpath('text()').extract()
        yield item
        yield Request(item['link'], callback=self.parse_link)

rawDescription: How to get data from mysql and extract data from web using spider in scrapy

description: Get data from mysql and extract data from web using spider in scrapy


code: env.filters['readcss'] = readcss

rawDescription: Google App Engine: Inject page-dependent CSS


code:
wordlist ['a', 'c', 'd', 'e', 'g', 'l', 'o', 'q', 't', 'x']
leftlist ['a', 'c', 'd', 'e', 'g']
rightlist ['l', 'o', 'q', 't', 'x']

wordlist ['l', 'o', 'q', 't', 'x']
leftlist ['l', 'o']
rightlist ['q', 't', 'x']

wordlist ['l', 'o']
leftlist ['l']
rightlist ['o']

wordlist ['l']
False
4

rawDescription: Why is my implementation of binary search very inefficient?


rawDescription: TkInter: how to display the normal cursor?


code:
import socket, struct

def ip2long(ip):
    """
    Convert an IP string to long
    """
    packedIP = socket.inet_aton(ip)
    return struct.unpack("!L", packedIP)[0]

rawDescription: Convert an IP string to a number and vice versa


code:
import sys
variable = sys.stdin.read()

rawDescription: How do I pipe the output of file to a variable in Python?

description: Pipe the output of file to a variable in Python


code:
from itertools import groupby
L = [3,5,0,6,8,9,7,0,1,0]
[list(g) for k, g in groupby(L, key=bool) if k]

rawDescription: Make a new sublist of preceding characters every time there's a zero in a list, excluding the zero


code:
list1 = ['a','aa','aaa','aaaa','aaaaa','aaaaaa','aaaaaaa','aaaaaaaa',]
max(list1, key=len)
len(max(list1, key=len))

rawDescription: Return len of the longest word in a list


code:
def is_business_day(day):
    return day.isoweekday() < 5

rawDescription: How would you get the xth weekday of a given month in python?


code: ibound & (abs(h-nodata) <= eps)

rawDescription: Efficient way to do conditional checks on Numpy Arrays


code:
def f(): pass

"foo"

rawDescription: Python: Why does calling just "f" run >4x faster than "f()"?


code:
import random
random.sample(uppercase_len5, 5)

rawDescription: Generate 2 Unique but random Elements in a List


code: new_index = zerovalue + 1

rawDescription: np.where() not returning expected indices in numpy python

description: Np.where() not returning expected indices in numpy python


code:
from itertools import product
var = {'A': 'A', 'W': 'AT', 'K': 'GT'}
word = "AWK"
poss = [var[c] for c in word]
poss
list(product(*poss))

rawDescription: Creating all combinations of a string given character values from a dictionary in python


code:
for zip in sorted_keys:
    print(offense_map[zip], victims_by_offense[zip])

rawDescription: Python: Replace value with the value from a dictionary key value pair


code: b = a[::2]  # Start at first element, then every other.

rawDescription: split list into 2 lists corresponding to every other element

description: Split list into 2 lists corresponding to every other element


code: plot(distance * 4, elevation * 5)

rawDescription: Matplotlib axis limits and text positions independent of dataset units


code:
a = A()
a.func()
a.get_name()

rawDescription: pass an undefined method call to an attribute containing a different object

description: Pass an undefined method call to an attribute containing a different object


code:
'o' in 'hello'
'el' in 'hello'
'x' in 'hello'
'hex' in 'hello'

rawDescription: Reading ε using python

description: Reading ε using python


code:
for i in combObj: # Don't call `list` on it before you do this!
    print(i)

rawDescription: working with combinations object in python

description: Working with combinations object in python


code:
conv = dict(zip('kMGT', (3, 6, 9, 12)))
def parse_number(value):
  if value[-1] in conv:
    value = '{}e{}'.format(value[:-1], conv[value[-1]])
  return float(value)

rawDescription: Formatting "Kilo", "Mega", "Gig" data in numpy record array


code: ''.join(item.split('|')[1] for item in translate(seq[frame:]))

rawDescription: translate my sequence?

description: Translate my sequence


code: rle = ''.join(['{}{}'.format(k, sum(1 for _ in g)) for k, g in groupby(string)])

rawDescription: Run Length Encoding in Python with List Comprehension


code:
example_list = [
    [1, '+', 3, "MNP1", 2480],
    [2, '+', 2, "MNP1", 2480],
    [3, '+', 1, "MNP2", 3200],
    [4, '-', 4, "MNP3", 2480],
    [5, '-', 2, "MNP4", 4700]
]

output_dict = collections.OrderedDict()
for _, op, arg2, _, num in example_list:
    key = num, op
    output_dict.setdefault(key, [0, 0])
    output_dict[key][0] += 1
    output_dict[key][1] += arg2

rawDescription: Restructuring a list of lists in python

description: Restructuring a list of lists in python


code:
from pandas import DataFrame
df = DataFrame.from_csv("tsv.tsv", sep="\t")

rawDescription: python reading in multi-column tsv file with row numbers

description: Python reading in multi-column tsv file with row numbers


rawDescription: Using DataFrame#loc with arguments of trivially different types


rawDescription: Numpy 3D array to 2D row major array

description: Numpy 3D array to 2D row major array


code:
def doc(docstr):
    def deco(f):
        if isinstance(f, type):
            d = vars(f).copy()
            d["__doc__"] = docstr
            return type(f.__name__, f.__bases__, d)
        f.__doc__ = docstr
        return f
    return deco

rawDescription: Change position of doc string in Python code


code:
import os

x = 1000000

print( "Sorting List:" )
for i in range( 0, x ):
    print( str( i ) + "/" + str( x ) + " elements sorted", end='\r' )

rawDescription: Display Number of Iterations in Output Window


code:
serv=echoserver()
serv.start()
... # sleep of do anything you want
serv.stop()

rawDescription: python stop multithreaded echo server

description: Python stop multithreaded echo server


code: ln -s /path/to/script.py /path/to/script

rawDescription: How to run python script without using ./script.py?

description: Run python script without using ./script.py


code: ['are', 'you', 'awake', 'now', 'me', 'time', 'is', 'over', 'now', 'okay', 'so', "they're", 'rich', 'and', 'hopefully', 'available']

rawDescription: Python how to split a string into words that contain words with a single quote?


code:
# class for routing db operations for  some blog myapp
class MyAppRouter(object):
    """A router to control all database operations on models in
    the myapp application"""

    def db_for_read(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        if model._meta.app_label == 'myapp':
            return 'other'
        return None

    def db_for_write(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        if model._meta.app_label == 'myapp':
            return 'other'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        "Allow any relation if a model in myapp is involved"
        if obj1._meta.app_label == 'myapp' or obj2._meta.app_label == 'myapp':
            return True
        return None

    def allow_syncdb(self, db, model):
        "Make sure the myapp app only appears on the 'other' db"
        if db == 'other':
            return model._meta.app_label == 'myapp'
        elif model._meta.app_label == 'myapp':
            return False
        return None

rawDescription: How can I use one django app ( with one db ) in two projects ? ( Using my app as a service )

description: Use one django app ( with one db ) in two projects ? ( Using my app as a service )


code:
import os
import glob
os.chdir('..')
glob.glob('foo/google*')

rawDescription: Open file knowing only a part of its name


code:
n = mat.shape[0]
idx = np.arange(n)
mask = idx[:, None] + idx < n - 1
mat[mask] = 0

rawDescription: How do i access all elements of numpy array which indexes satisfy some condition?

description: Access all elements of numpy array which indexes satisfy some condition


code:
class GeoObject(models.Model):
    name = models.CharField('Name',max_length=30)
    father = models.ForeignKey('self', related_name = 'geo_objects')
    crumb = PickledObjectField()
    # more attributes...

    def _breadcrumb(self):
        ...
        return breadcrumb

    def save(self,*args, **kwargs):
        self.crumb = self._breadcrumb()
        super(GeoObject, self).save(*args,**kwargs)

rawDescription: How can I handle dynamic calculated attributes in a model in Django?

description: Handle dynamic calculated attributes in a model in Django


code:
import win32com.client
def Hello():
 import win32com.client
 w=win32com.client.Dispatch("imacros")
 w.iimInit("", 1)
 w.iimPlay("Demo\\FillForm")
if __name__=='__main__':
 Hello()

rawDescription: Integrating iMacros scripts into python

description: Integrating iMacros scripts into python


code: catids = set(s for catid in df.catid.values for s in catid.split())

rawDescription: How to make "value is in dateframe column" quicker

description: Make "value is in dateframe column" quicker


code: f = lambda x: x * 2

rawDescription: Lambda equivalent from Python in PHP

description: Lambda equivalent from Python in PHP


rawDescription: Difference between dir(…) and vars(…).keys() in Python?


rawDescription: Can someone explain this program to me?

description: Can someone explain this program to me


code:
time_in_seconds = 123456789
hours = time_in_seconds // (60*60)
minutes = (time_in_seconds % (60*60)) // 60
seconds = time in seconds % 60

rawDescription: using a timer as a highscore system

description: Using a timer as a highscore system


code:
from __future__ import print_function

import numpy as np
import cvxpy
from scipy.optimize import minimize

# Problem data.
n = 4
M = [
        [0.00123727, 0.00011974, 0.00067403, 0.00060845],
        [0.00011974, 0.00736665, 0.00165674, 0.00053581],
        [0.00067403, 0.00165674, 0.00281547, 0.00129646],
        [0.00060845, 0.00053581, 0.00129646, 0.00153195]]
np.random.seed(1)
R = np.random.randn(n)
E = np.random.randn()

print('R:', R)
print('E:', E)
print()

A = np.matrix([np.ones(n), R])
b = np.matrix([[1], [E]])

def solve_cvxpy():

    # Construct the problem.
    x = cvxpy.Variable(n)
    objective = cvxpy.Minimize(cvxpy.quad_form(x, M))
    constraints = [0 <= x, A*x == b]
    problem = cvxpy.Problem(objective, constraints)

    # Solve the problem.
    result = problem.solve()
    print('cvxpy solution:')
    print(x.value)
    print()

def solve_scipy():
    def simplex_constraint(x):
        return x.sum() - 1
    def dot_constraint(x):
        return x.dot(R) - E
    def objective(x):
        return x.dot(M).dot(x)
    x0 = np.ones(n) / n
    bounds = [(0, np.inf)]*n
    constraints = (
            dict(type='eq', fun=simplex_constraint),
            dict(type='eq', fun=dot_constraint))
    result = minimize(
            objective, x0, method='SLSQP', tol=1e-8,
            bounds=bounds, constraints=constraints)
    print('scipy solution:')
    print(result.x)
    print()

solve_cvxpy()
solve_scipy()

rawDescription: How do I use Scipy minimize with constraints and dynamic function

description: Use Scipy minimize with constraints and dynamic function


code:
from nltk.tag.perceptron import PerceptronTagger
def pos_tag(tokens, tagset=None):
    tagger = PerceptronTagger()
    return _pos_tag(tokens, tagset, tagger)

rawDescription: Why is pos_tag() so painfully slow and can this be avoided?


code: outline = [k for k in lines[i] if k is not ''] + [cx,uf,rf,pc]

rawDescription: Python: Outputting the correct value from a list()


rawDescription: Setting spines in matplotlibrc

description: Setting spines in matplotlibrc


code:
np.column_stack((R_match[0],C_match[0]))  # First point
np.column_stack((grps_R[0],grps_C[0]))    # Its three neighbors

rawDescription: Find a nodes 8 neighbors on a 2D grid

description: Find a nodes 8 neighbors on a 2D grid


code:
for userId in userIds_to_check:
    stats.anderson(df[df.userId == userId].numCol)

rawDescription: Python: extracting arrays from DataFrame column


code:
import numpy as np
def process(iterable):
    for line in iterable:
        parts = [line[:11], line[11:24]] + line[24:].split()
        yield '@'.join(parts)
with open('data', 'rb') as f:
    data = np.genfromtxt(process(f), dtype=None, delimiter='@')

print(repr(data))

rawDescription: Numpy, Reading from File with no delimiter but fixed pattern


code:
class PixmapContainer(QtGui.QLabel):
    def __init__(self, pixmap, parent=None):
        super(PixmapContainer, self).__init__(parent)
        self._pixmap = QtGui.QPixmap(pixmap)
        self.setMinimumSize(1, 1)  # needed to be able to scale down the image

    def resizeEvent(self, event):
        w = min(self.width(), self._pixmap.width())
        h = min(self.height(), self._pixmap.height())
        self.setPixmap(self._pixmap.scaled(w, h, QtCore.Qt.KeepAspectRatio))

rawDescription: How to set maximum widths and heights for pixmaps?

description: Set maximum widths and heights for pixmaps


code: ('this matches',)

rawDescription: how to match whitespace and alphanumeric characters in python

description: Match whitespace and alphanumeric characters in python


code: [expression_involving_y for y in elements]

rawDescription: How can I rewrite this map() example using list comprehension?

description: Rewrite this map() example using list comprehension


code:
args = [A, B]
results = pool.map(solve1, args)

rawDescription: How to do parallel programming in Python

description: Do parallel programming in Python


code:
test = np.array([0, 1, 2, 5, 0])
states = [0, 2]
np.in1d(test, states)

rawDescription: Check if values in a set are in a numpy array in python


rawDescription: What is the difference between accessing image coordinates from image module of python or as a numpy array and storing it?


code:
[['# The loopback network interface\n'],
 ['auto lo\n'],
 ['iface lo inet loopback\n', '\n'],
 ['auto eth0\n'],
 ['iface eth0 inet static\n',
  '    address 192.168.2.7\n',
  '    netmask 255.255.255.0\n',
  '    network 192.168.2.0\n',
  '    broadcast 192.168.2.255\n',
  '    gateway 192.0.2.254\n',
  '    dns-nameservers 12.34.56.78 12.34.56.79\n',
  '\n'],
 ['auto eth0:0\n'],
 ['allow-hotplug eth0:0\n'],
 ['iface eth0:0 inet static\n',
  '    address 192.168.1.43\n',
  '    netmask 255.255.255.0\n',
  '\n'],
 ['auto eth1\n'],
 ['iface eth1 inet dhcp\n', '\n'],
 ['auto eth2\n'],
 ['iface eth2 inet6 static\n',
  '    address 2001:db8::c0ca:1eaf\n',
  '    netmask 64\n',
  '    gateway 2001:db8::1ead:ed:beef\n',
  '\n'],
 ['auto br0\n'],
 ['iface br0 inet static\n',
  '    address 10.10.0.15\n',
  '    netmask 255.255.255.0\n',
  '    gateway 10.10.0.1\n',
  '    bridge_ports eth0 eth1\n',
  '    up /usr/sbin/brctl stp br0 on']]

rawDescription: How to split /etc/network/interfaces using a regex in Python

description: Split /etc/network/interfaces using a regex in Python


code:
resultA = method_A()
resultB = method_B()[0]

rawDescription: How to remove extra list from the result in python

description: Remove extra list from the result in python


code:
def reload_imported_names(module_name, globals, *names):
    """Reload module and rebind imported names.

    If no names are given, rebind all names exported by the module

    """
    importlib.reload(module_name)
    module = sys.modules[module_name]
    if not names:
        names = getattr(module, '__all__',
                        (n for n in dir(module) if n[0] != '_'))
    for name in names:
        globals[name] = getattr(module, name)

rawDescription: Using importlib for cases like from x import *


code: rprim[0], rprim[1], rprim[2], rprim[3], rprim[4], rprim[5], rprim[6]

rawDescription: Python auto define variables

description: Python auto define variables


code: objects = MyModel.objects.filter(start_time__lt=time(7, 30))

rawDescription: Django filter datetime field by time, irrespective of date


code: sheet[rowIndex]["Message sent? (Y/N)"]

rawDescription: best way to index by value of the header in a 2d list

description: Index by value of the header in a 2d list


rawDescription: Output file formatting and rearrangement


code:
import argparse

parser = argparse.ArgumentParser(description='Rotate an image')
parser.add_argument('inputfile', type=argparse.FileType('r+b'),
                    help='The file to rotate')
parser.add_argument('degrees', type=int,
                    help='The number of degrees to rotate')
parser.add_argument('-o', '--output', type=argparse.FileType('wb'),
                    help='The file to write the result to. Defaults to the inputfile')

args = parser.parse_args()
outputfile = args.output or args.inputfile
rotate_picture(args.inputfile, outputfile, args.degrees)

rawDescription: make a test python options mandatory

description: Make a test python options mandatory


code: re.sub(re.escape('Aw, man...'), 'Match found.', 'Aw, manatee.')

rawDescription: How can I replace substrings without replacing all at the same time? Python

description: Replace substrings without replacing all at the same time? Python


code:
import wx
from wx.lib.wordwrap import wordwrap

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        b = wx.Button(self, -1, "Show a wx.AboutBox", (50,50))
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)

    def OnButton(self, evt):
        # First we create and fill the info object
        info = wx.AboutDialogInfo()
        info.Name = "Hello World"
        info.Version = "1.2.3"
        info.Copyright = "(C) 2006 Programmers and Coders Everywhere"
        info.Description = wordwrap(
            "A \"hello world\" program is a software program that prints out "
            "\"Hello world!\" on a display device. It is used in many introductory "
            "tutorials for teaching a programming language."

            "\n\nSuch a program is typically one of the simplest programs possible "
            "in a computer language. A \"hello world\" program can be a useful "
            "sanity test to make sure that a language's compiler, development "
            "environment, and run-time environment are correctly installed.",
            350, wx.ClientDC(self))
        info.WebSite = ("http://en.wikipedia.org/wiki/Hello_world", "Hello World home page")
        info.Developers = [ "Joe Programmer",
                            "Jane Coder",
                            "Vippy the Mascot" ]

        info.License = wordwrap(licenseText, 500, wx.ClientDC(self))

        # Then we call wx.AboutBox giving it that info object
        wx.AboutBox(info)

########################################################################
class MyFrame(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, title="Demo Test")
        panel = MyPanel(self)

        self.Show()

licenseText = "blah " * 250 + "\n\n" +"yadda " * 100

#----------------------------------------------------------------------
if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

rawDescription: How to use wx.python demos code

description: Use wx.python demos code


code:
def log_docstring(fn):
    print('docstring for %r is %r' % (fn, fn.__doc__))
    return fn

class InheritableDocstrings(type):
    def __prepare__(name, bases):
        classdict = dict()

        # Construct temporary dummy class to figure out MRO
        mro = type('K', bases, {}).__mro__[1:]
        assert mro[-1] == object
        mro = mro[:-1]

        def inherit_docstring(fn):
            if fn.__doc__ is not None:
                raise RuntimeError('Function already has docstring')

            # Search for docstring in superclass
            for cls in mro:
                super_fn = getattr(cls, fn.__name__, None)
                if super_fn is None:
                    continue
                fn.__doc__ = super_fn.__doc__
                break
            else:
                raise RuntimeError("Can't inherit docstring for %s: method does not "
                                   "exist in superclass" % fn.__name__)

            return fn

        classdict['inherit_docstring'] = inherit_docstring
        return classdict

class Animal():
    def move_to(self, dest):
        '''Move to *dest*'''
        pass

class Bird(Animal, metaclass=InheritableDocstrings):
    @log_docstring
    @inherit_docstring
    def move_to(self, dest):
        self._fly_to(dest)

assert Animal.move_to.__doc__ == Bird.move_to.__doc__

rawDescription: Python 3 - Method docstring inheritance without breaking decorators or violating DRY


code: ['Ace'] + [str(i) for i in range(2,11)] + ['Jack', 'Queen', 'King']

rawDescription: How do I use a list comprehension to generate more values in a list

description: Use a list comprehension to generate more values in a list


code:
def posts(self):
    from posts.models import Post
    return Post.filter(category__pk=self.id)

rawDescription: Two-way querying in Django without circular reference


code:
type_, *vals = strIn.split(',')
vals = [float(v) for v in vals]  # Convert list of strings to list of floats.

rawDescription: Python string get leading characters up to first comma


code:
lessthan = [v for v in ab if v < knowndistance]
greaterthan = [v for v in ab if v >= knowndistance]

rawDescription: Comparison of float numbers to a known value python


rawDescription: Adding elements of RGB array in Python

description: Adding elements of RGB array in Python


rawDescription: Json query on button press python / django


code:
fig = plt.gcf()
ax = plt.gca()

rawDescription: How to use ax with Pandas and Matplotlib

description: Use ax with Pandas and Matplotlib


code:
class RealestateAdmin(...):
   list_display = [processing,]

   def processing(obj):
       return utils.processing(obj)
   processing.short_description = 'realestate app result'
   processing.allow_tags = True

class PartyAdmin(...):
   list_display = [processing,]

   def processing(obj):
       return utils.processing(obj)
   processing.short_description = 'party app result'
   processing.allow_tags = False

rawDescription: list_display with a function, how to pass arguments?

description: List_display with a function, how to pass arguments


code:
# Function Being Decorated
@app.route("/some/restricted/stuff")
@login_required
def main(html_template):
    return render_template(html_template, stuff = getstuff())

rawDescription: What is a self-written decorator (like @login_required) actually doing?


code:
from zope.component import getMultiAdapter, getUtility
from plone.portlets.interfaces import IPortletManager
from plone.portlets.interfaces import ILocalPortletAssignmentManager
from plone.portlets.constants import USER_CATEGORY
from plone.portlets.constants import GROUP_CATEGORY
from plone.portlets.constants import CONTENT_TYPE_CATEGORY
from plone.portlets.constants import CONTEXT_CATEGORY

def blockPortletsUpponMyContentCreation(mycontent, event):
    for manager_name in ('plone.leftcolumn','plone.rightcolumn'):
        manager = getUtility(IPortletManager, name=manager_name)
        assignable = getMultiAdapter((mycontent, manager,), ILocalPortletAssignmentManager)
        for category in (GROUP_CATEGORY, CONTENT_TYPE_CATEGORY,CONTEXT_CATEGORY,USER_CATEGORY):
            assignable.setBlacklistStatus(category, 1)

rawDescription: Plone Content Type-Specific Portlet Assignment


code:
from collections import OrderedDict
from pymysql.cursors import DictCursorMixin, Cursor

class OrderedDictCursor(DictCursorMixin, Cursor):
    dict_type = OrderedDict

rawDescription: PyMySQL and OrderedDict

description: PyMySQL and OrderedDict


rawDescription: Python slicing of list of list

description: Python slicing of list of list


code:
def encode_b(obj):
    if isinstance(obj, B):
        return obj.__dict__
    return obj

dumps(a.__dict__, default=encode_b)

rawDescription: Python serialize objects list to JSON

description: Python serialize objects list to JSON


code: x0 = int(rho*np.cos(theta)*np.sin(phi))

rawDescription: How to rotate a 3D spot with numpy?

description: Rotate a 3D spot with numpy


rawDescription: PyCharm. Regular expression to replace all script src attributes


code:
a = base()
a.context("value")
base.description()

rawDescription: How to return a value computed by overriding method from a subclass to it's base class method in python

description: Return a value computed by overriding method from a subclass to it's base class method in python


rawDescription: Getting the values of many defaultdicts that contains a certain key


code:
# this maps elements in a to elements in b (elements of a are the keys)
# each element of a maps to several elements of b (as a list)
a2b = {
       'a' : [1,2,3]
      }

# this maps elements in b to elements in a (elements of b are the keys)
# each element of bmaps to several elements of a (as a list)
b2a = {
        1 : ['a'],
        2 : ['a'],
        3 : ['a'],
      }

rawDescription: Data structure for many-many

description: Data structure for many-many


code:
window2(root)
# HELP I DON'T KNOW WHAT root IS!!

rawDescription: window label is not printing : Python

description: Window label is not printing : Python


code:
def initialer(name):
    space_pos = name.find(' ')
    if space_pos == -1:
        return name[0]
    else:
        return name[0] + name[space_pos + 1]

rawDescription: How can i use "str.find" (python) to locate the next character after a space or " "?

description: Use "str.find" (python) to locate the next character after a space or " "


code:
import operator

ops = {
    'conjunction': operator.and_,
    'disjunction': operator.or_,
    'implication': lambda a, b: (1 - a) | b,
    'exclusive': operator.xor,
    'equivalence': operator.eq,
}
def boolean(a, b, operation):
    return ops[operation](a, b)

rawDescription: Python operations

description: Python operations


code: modules = map(__import__, moduleNames)

rawDescription: Import modules from a list or dict in Python?


code:
param = [2, 6, 3]
pattern = 'www.url?param=%s&param2=%s&param3=%s'
url = pattern % tuple(param)
url

rawDescription: Django store regular expression in DB which then gets evaluated on page


code:
def generate(self, length=100):
    if '_trigram_model' not in self.__dict__:
        estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2)
        self._trigram_model = NgramModel(3, self, estimator)
    text = self._trigram_model.generate(length)
    return tokenwrap(text) # or just text if you don't want to wrap

rawDescription: NLTK "generate" function: How to get back returned text?


code:
queen = cv2.imread('queen.jpg', cv2.IMREAD_GRAYSCALE)
queen = cv2.resize(queen, (525, 700))

rawDescription: How to best create a new image out of existing images in openCV

description: Best create a new image out of existing images in openCV


code:
try:
    y = int(x)
except ValueError:
    y = None

rawDescription: python pattern matching numbers

description: Python pattern matching numbers


rawDescription: PCA projecting and reconstruction in Scikit


code:
text = "he/s is/v a/p good/j man/n"
dict([i.split('/') for i in text.split()])

rawDescription: Create a dictionary for the token, tags of a text


code: df

rawDescription: Calculating percentile for specific groups


code:
y1 = [i for i, x in enumerate(s) if -1 <= x <= -0.8]
y2 = [i for i, x in enumerate(s) if -0.8 <= x <= 0.8]

rawDescription: Enumerate function

description: Enumerate function


code:
import collections

class deque(collections.deque):
    def __init__(self, iterable=(), maxlen=None):
        super(deque, self).__init__(iterable, maxlen)
        self._maxlen = maxlen
    @property
    def maxlen(self):
        return self._maxlen

rawDescription: Check maxlen of deque in python 2.6

description: Check maxlen of deque in python 2.6


rawDescription: read multiple files by python

description: Read multiple files by python


code:
res = requests.get(BASE_URL + "/confluence/rest/api/content", params={"parent": "<parentId>"} , auth=("username", "pass"))

res = requests.get(BASE_URL + "/confluence/rest/api/content", params={"title": "parents title"} , auth=("username", "pass"))

rawDescription: How can I retrieve all the child pages in Confluence by a parent page title?

description: Retrieve all the child pages in Confluence by a parent page title


code: w["button"].configure(command = lambda w=w: delete(w["url"], widgets))

rawDescription: Dynamicaly deleting widgets in Tkinter in Python


code:
b.sort(key=lambda x: filterdict[x['id']])
b

rawDescription: Sorting a list of dicts in python, using another list as a "filter"?


code:
import pkg
print(pkg.b.a)
print(pkg.x)

rawDescription: Importing package in Python

description: Importing package in Python


code:
d = {}
with open("sometext.txt", "r") as f:
    for line in f:
        if line.startswith('List of purchases'):
            purchases = d['List of purchases'] = []
            for line in f:
                info = line.strip('() \n').split(', ')
                purchases.append(info)
            break
        key, val = line.split(': ')
        d[key] = val.rstrip('\n')

rawDescription: Python - Reading text file into dict

description: Python - Reading text file into dict


rawDescription: Python equivalent code to MATLABs vec2mat


code: soup

rawDescription: How do I sort an unordered list using BeautifulSoup 4 by a child element

description: Sort an unordered list using BeautifulSoup 4 by a child element


code:
c.InteractiveShellApp.exec_files = [ "/path/to/myscript.py" ]
# if you put the script in the profile dir, just the filename will suffice

rawDescription: how to define functions in ipython configuration file?

description: Define functions in ipython configuration file


code: x = np.repeat(0.5*np.arange(N, dtype=np.float32), 2).reshape(-1, 2)

rawDescription: Repeating numpy values and specifying dtype


code:
import django.conf.global_settings as DEFAULT_SETTINGS

TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
    'custom_context_processors.add_verification',
      )

rawDescription: How to insert data to a template after render ? (django)

description: Insert data to a template after render ? (django)


rawDescription: lxml parsing google search results

description: Lxml parsing google search results


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

# Form implementation generated from reading ui file 'btngroup.ui'
#
# Created: Wed Nov 21 17:50:42 2012
#      by: PyQt4 UI code generator 4.9.5
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_ButtonGroup(object):
    def setupUi(self, ButtonGroup):
        ButtonGroup.setObjectName(_fromUtf8("ButtonGroup"))
        ButtonGroup.resize(240, 167)
        self.horizontalLayout = QtGui.QHBoxLayout(ButtonGroup)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.buttonBox = QtGui.QWidget(ButtonGroup)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        self.verticalLayout = QtGui.QVBoxLayout(self.buttonBox)
        self.verticalLayout.setMargin(0)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.buttonA = QtGui.QPushButton(self.buttonBox)
        self.buttonA.setObjectName(_fromUtf8("buttonA"))
        self.verticalLayout.addWidget(self.buttonA)
        self.buttonB = QtGui.QPushButton(self.buttonBox)
        self.buttonB.setObjectName(_fromUtf8("buttonB"))
        self.verticalLayout.addWidget(self.buttonB)
        self.buttonC = QtGui.QPushButton(self.buttonBox)
        self.buttonC.setObjectName(_fromUtf8("buttonC"))
        self.verticalLayout.addWidget(self.buttonC)
        self.buttonD = QtGui.QPushButton(self.buttonBox)
        self.buttonD.setObjectName(_fromUtf8("buttonD"))
        self.verticalLayout.addWidget(self.buttonD)
        self.horizontalLayout.addWidget(self.buttonBox)

        self.retranslateUi(ButtonGroup)
        QtCore.QMetaObject.connectSlotsByName(ButtonGroup)

    def retranslateUi(self, ButtonGroup):
        ButtonGroup.setWindowTitle(QtGui.QApplication.translate("ButtonGroup", "Button Group", None, QtGui.QApplication.UnicodeUTF8))
        self.buttonA.setText(QtGui.QApplication.translate("ButtonGroup", "Button A", None, QtGui.QApplication.UnicodeUTF8))
        self.buttonB.setText(QtGui.QApplication.translate("ButtonGroup", "Button B", None, QtGui.QApplication.UnicodeUTF8))
        self.buttonC.setText(QtGui.QApplication.translate("ButtonGroup", "Button C", None, QtGui.QApplication.UnicodeUTF8))
        self.buttonD.setText(QtGui.QApplication.translate("ButtonGroup", "Button D", None, QtGui.QApplication.UnicodeUTF8))

rawDescription: Single button event handler for buttons

description: Single button event handler for buttons


rawDescription: numpy ndarray indexing - retrieving indexes from tuple

description: Numpy ndarray indexing - retrieving indexes from tuple


code:
def alt(A, MIN_OBS):
    temp_dict = count(A, MIN_OBS)
    df = pd.DataFrame(0, index=A.index, columns=temp_dict)
    for col in df:
        df[col] = A.str.contains(r'^{v}|,{v},|,{v}$'.format(v=col)).astype(int)
    df.columns = ['A_{}'.format(col) for col in df]
    return df

rawDescription: Transform pandas Series with variable length comma separated values to Dataframe


rawDescription: Python build a list by two different methods


code:
import re
re.split(r'\s+AND\s+', 'Romeo AnD Juliet', flags=re.I) # re.I tells Python to ignore case

rawDescription: Recognize the words "AND" and "OR" into a string


code:
cols = zip(*rows)
cols

rawDescription: Whats the best way of putting tabular data into python?


code: nodollarstrings = [s for s in strings if not s.startswith('$')]

rawDescription: Very new to python, looking for some clarification


code:
for animal in animals:
    try:
        animal.fly(destination)
    except AttributeError:
        animal.walk(destination)

rawDescription: get the name of the class and wrap it in an if statement

description: Get the name of the class and wrap it in an if statement


code:
import csv
RESULTS = [
    ['apple','cherry','orange','pineapple','strawberry']
]
resultFile = open("output.csv",'wb')
wr = csv.writer(resultFile, dialect='excel')
wr.writerows(RESULTS)

rawDescription: Writing List of Strings to Excel CSV File in Python


code:
reload_imported_names('my_module', globals())  # import *
reload_imported_names('my_module', globals(), 'foo', 'bar')  # import foo, bar

rawDescription: Using importlib for cases like from x import *


code:
class Spam:
    egg = 42

assert Spam.egg.__doc__ == int.__doc__

rawDescription: Docstrings for static properties in boost::python


code:
import pandas as pd
import numpy as np

#%% create dataframe
ts1 = [0, 1, np.nan, np.nan, np.nan, np.nan]
ts2 = [0, 2, np.nan, 3, np.nan, np.nan]
d =  {'X': ts1, 'Y': ts2, 'Z': ts2}
df = pd.DataFrame(data=d)
print(df.head())

#%% apply forward fill
col = ['X', 'Y']
df[col] = df[col].ffill()
print(df.head())

rawDescription: forward fill specific columns in pandas dataframe

description: Forward fill specific columns in pandas dataframe


code:
soup = BeautifulSoup(html)

for anchor in soup.select('a.Unique_Class_Name'):
    if anchor.has_attr('href'):
        print (anchor['href'])

rawDescription: Get the href text of a link that has a certain class attribute using BeautifulSoup in Python


rawDescription: Get attribute of a property in python

description: Get attribute of a property in python


code: [line.split(',')[0] for line in entireResult.split('\n')]

rawDescription: Can I write this as a two-level list comprehension?

description: Write this as a two-level list comprehension


code:
class KeyValue(object):
    def __init__(self, k, v):
        self.k = k
        self.v = v
    def __iter__(self):
       for x in [self.k, self.v]:
           yield x

rawDescription: How to determine if object is a valid key-value pair in PySpark

description: Determine if object is a valid key-value pair in PySpark


code:
lY = ImageMultiply[MorphologicalBinarize[GaussianFilter[srcAdjusted, 3, {2, 0}], {0.02, 0.05}], mask];
lX = ImageMultiply[MorphologicalBinarize[GaussianFilter[srcAdjusted, 3, {0, 2}], {0.02, 0.05}], mask];

rawDescription: How to remove convexity defects in a Sudoku square?

description: Remove convexity defects in a Sudoku square


code: x = x.reshape(-1, 100).mean(axis=1)

rawDescription: plotting a graph with matplotlib plot function takes sometimes minutes

description: Plotting a graph with matplotlib plot function takes sometimes minutes


rawDescription: Drawing Histogram in OpenCV-Python

description: Drawing Histogram in OpenCV-Python


rawDescription: How to not display script name when looping on command line argument?

description: Not display script name when looping on command line argument


rawDescription: Combinations from dictionary with list values using Python


rawDescription: IPython Notebook doesn't show full namespace


code:
from itertools import chain
l = [{1: "a"}, {2: "b"}]
list(chain.from_iterable(l))

rawDescription: How can I get a list of all keys of dicts inside a list?

description: Get a list of all keys of dicts inside a list


code:
def threaded(event):
    import time
    while True:
        event.set()
        time.sleep(1)

rawDescription: asyncio: Wait for event from other thread

description: Asyncio: Wait for event from other thread


code:
def obsfucate_letters(letters):
    try:
        letters[0] = obsfucate_function()
    except ValueError:
        # ignore the exception, letters[0] will be unchanged
        pass

    try:
        letters[1] = obsfucate_function()
    except ValueError:
        pass

    try:
        letters[2] = obsfucate_function()
    except ValueError:
        pass

    try:
        letters[3] = obsfucate_function()
    except ValueError:
        pass

    return letters

def obsfucate_function():
    import random as r
    randomnumber = r.random() * 100
    if randomnumber <= 16:
        letters1 = "!"
        return letters1
    elif randomnumber > 16 and randomnumber <= 30:
        letters1 = "%"
        return letters1
    elif randomnumber > 30 and randomnumber <= 45:
        letters1 = "&"
        return letters1
    elif randomnumber > 45 and randomnumber <= 60:
        letters1 = "*"
        return letters1
    elif randomnumber > 60 and randomnumber <= 75:
        letters1 = "#"
        return letters1
    elif randomnumber > 75 and randomnumber <= 90:
        letters1 = "@"
        return letters1
    else:
        raise ValueError('random number out of range')

rawDescription: Return original value, python

description: Return original value, python


rawDescription: Save for loop result in variable

description: Save for loop result in variable


code:
import numpy as np

mu, sigma = 2.0, 0.5

# A and B will have different seeds and so different numbers
A = np.random.normal(mu, sigma, size=(1000, 1000))
B = np.random.normal(mu, sigma, size=(1000, 1000))

# But their statistical characteristics should be similar enough
print(mu, np.mean(A), np.mean(B))
print(sigma, np.std(A), np.std(B))

rawDescription: numpy random usage validity

description: Numpy random usage validity


code:
import urlparse, urllib
parts = urlparse.urlsplit(u'http://ne.wikipedia.org/wiki/मुख्य_पृष्ठ')
parts = parts._replace(path=urllib.quote(parts.path.encode('utf8')))
parts.geturl().encode('ascii')

rawDescription: Scraping a webpage with URL in Nepali (Non-English)


code:
for k, v in SERVICES.items(): # or iteritems in Python 2
    if 'check' in v:
        print(k) # 'domain'
        break

rawDescription: Python search by value

description: Python search by value


code:
import numpy as np
import pandas as pd
from ggplot import meat

rawDescription: finding a record with a max value in python

description: Finding a record with a max value in python


rawDescription: Sorting list of lists by a third list of specified non-sorted order


code:
def do_fn(a, b, c, op_fn):
    return op_fn(a, b, c)

print(do_fn(a, b, c, (lambda a, b, c: (a | b) ^ c)))  # => {1, 2, 5, 6}

rawDescription: Possible to pass set operators (operation) as a string argument to a function?


code:
def test1(self):
    ...
    self.to_be_removed.append(filename)

rawDescription: Unittest tearDown() method depends on finished test


rawDescription: Pandas: join with outer product

description: Pandas: join with outer product


code:
from functools import wraps
from flask import request, abort

def limit_content_length(max_length):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            cl = request.content_length
            if cl is not None and cl > max_length:
                abort(413)
            return f(*args, **kwargs)
        return wrapper
    return decorator

rawDescription: Is it possible to limit Flask POST data size on a per-route basis?


rawDescription: Don't understand how Timeit works. Need an explanation


code:
@property
def area(self):
    try:
        return self._area
    except AttributeError:
        area = pi*self.r**2
        self._area = area
        return area

rawDescription: When and how often are properties calculated in python?


rawDescription: String.replace() Python remove first coincidence


code:
import inspect

def rstr(func):
    return inspect.formatargspec(*inspect.getargspec(func))

rawDescription: Is there a Python equivalent of R's str(), returning only the structure of an object?


rawDescription: Should I put the shebang line in every python file?


rawDescription: PDF Viewer for Python Tkinter

description: PDF Viewer for Python Tkinter


code:
import os
## first file in current dir (with full path)
file = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
file
os.path.dirname(file) ## directory of file
os.path.dirname(os.path.dirname(file)) ## directory of directory of file
...

rawDescription: Extract a part of the filepath (a directory) in Python


code:
files = (
    r'..\..\data\User\level1\level2\sun.png',
    r'..\..\data\User\level1\level2\description.txt'
)
files[0].split("\\")

rawDescription: Convert single backslash to double backslash


code:
df = pd.DataFrame({'user_agent':['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36']})

# create 10.000 rows DF:
df = pd.concat([df] * 10**4)

def parse_ua_series(ua):
    p = user_agents.parse(ua)
    return pd.Series([p.browser.family, p.os.family])

def parse_ua_list(ua):
    p = user_agents.parse(ua)
    return [p.browser.family, p.os.family]

rawDescription: Python. BigData. Need to extract Web-Browser and OS users' preferences from cells. Best-performance method?


code:
long_object_name.do_something_with_long_name(
    long_expression_returning_is_first_arg,
    long_expression_returning_is_second_arg
)

rawDescription: I know I'm supposed to keep Python code to 79 cols, but how do I indent continuations of lines?


code:
# script2.py
import pandas as pd
import numpy as np
import time
import fcntl

for i in range(500,1000):
    with open("lock.lck") as f_lock:
        fcntl.flock(f_lock, fcntl.LOCK_EX)
        time.sleep(np.random.uniform(0, 0.05))

        df = pd.read_pickle("data.pkl")
        df.loc[i, :] = np.concatenate([np.array([2]), np.random.sample(2)])
        df.to_pickle("data.pkl")

rawDescription: fcntl file lock example not working

description: Fcntl file lock example not working


code:
def test1():
    print("test1")

def test2():
    print("test2")

def caller(name, fn):
    print("calling function with name: {}".format(name))
    fn()

class Driver(object):
    def __init__(self):

        self.signals = []

    def connect_to_signal(self, name, what_to_call):
        self.signals.append((name, what_to_call))

    def run(self):
        for name, signal in self.signals:
            signal(1)

def main():
    signals = {'test1':test1, 'test2':test2}

    d = Driver()

    for signal, callback in signals.items():
        cb = lambda x: caller(signal, callback)
        #cb = lambda x,s=signal,c=callback: caller(s, c)  # TRY THIS INSTEAD!
        d.connect_to_signal(signal, cb)

    d.run()

if __name__ == '__main__':
    main()

rawDescription: Pass a lambda expression as callable to dbus.Interface.connect_to_signal


code:
def start():
    print("Welcome to the adventure")
    stage1()

def stage1():
    print("You made it this far!")
    stage2()

# if you called start() here,
# you would have an error when stage1() tries to call stage2(),
# because the interpreter doesn't know what a stage2 is yet.

def stage2():
    print("Oops - you died.")

start()

rawDescription: Changing python to read code differently?


code: resp.status == httplib.PARTIAL_CONTENT

rawDescription: Python: How to download file using range of bytes?


rawDescription: Indentation of pformat() output

description: Indentation of pformat() output


code:
from scipy import ndimage
import cv2
import numpy as np
import pandas as pd

img = cv2.imread("image.png")

blue = np.array([200, 70, 60])
red = np.array([30, 20, 220])

isblue = cv2.inRange(img, blue, blue+20)
isred = cv2.inRange(img, red, red+20) > 0

labels, count = ndimage.label(~isblue)

loc = np.where(labels >= 2) #label 1 is the border

# to get the location, we need to sort the block along yaxis and xaxis
df = pd.DataFrame({"y":loc[0], "x":loc[1], "label":labels[loc], "isred":isred[loc]})

grid = df.groupby("label").mean().sort_values("y")

def f(df):
    return df.sort_values("x").reset_index(drop=True)
res = grid.groupby((grid.y.diff().fillna(0) > 10).cumsum()).apply(f)

print((res.isred.unstack(1) > 0).astype(np.uint8))

rawDescription: Determining if a color is within a contour OpenCV


code: self.foo = 5

rawDescription: How to call a data member of the base class if it is being overwritten as a property in the derived class?

description: Call a data member of the base class if it is being overwritten as a property in the derived class


code:
def plot(n, *args):
    plotter_map = {
        1: plot1,
        2: plot2,
        3: plot3,
        # ...,
        N: plotN
    }

    fxn = plotter_map.get(N, None)
    if fxn is None:
        raise ValueError("there is no `plot{}`".format(N))

    try:
        fxn(*args)
    except:
        print("failed to run `plot{}`".format(N))

rawDescription: Use try/except to handle multiple plots

description: Use try/except to handle multiple plots


code:
new = {}
for (k, v) in dict1.items():
    new.setdefault(k, []).append(v)
for (k, v) in dict2.items():
    new.setdefault(k, []).append(v)

rawDescription: Dictionaries in Python

description: Dictionaries in Python


code: dict(zip(rowHeaders, leafIDs))

rawDescription: Sorting tuples based on another list

description: Sorting tuples based on another list


code:
import urlparse
from django.conf import settings
from storages.backends.s3boto import S3BotoStorage

def domain(url):
    return urlparse.urlparse(url).hostname

class MediaFilesStorage(S3BotoStorage):
    def __init__(self, *args, **kwargs):
        kwargs['bucket'] = settings.MEDIA_FILES_BUCKET
        kwargs['custom_domain'] = domain(settings.MEDIA_URL)
        super(MediaFilesStorage, self).__init__(*args, **kwargs)

class StaticFilesStorage(S3BotoStorage):
    def __init__(self, *args, **kwargs):
        kwargs['bucket'] = settings.STATIC_FILES_BUCKET
        kwargs['custom_domain'] = domain(settings.STATIC_URL)
        super(StaticFilesStorage, self).__init__(*args, **kwargs)

rawDescription: Django-compressor: how to write to S3, read from CloudFront?


code:
def main():
    flag = 0
    default_screen()
    reactor.callLater(0.1, tick)

def tick():
   for event in pygame.event.get():
        if event.type == pygame.QUIT:
            reactor.stop() # just stop somehow
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            reactor.stop() # just stop somehow
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            pos = pygame.mouse.get_pos()
            # some stuff
   reactor.callLater(0.1, tick)

rawDescription: Twisted clients within pygame mainloop?

description: Twisted clients within pygame mainloop


rawDescription: Not able to scrape text inside p tag/element using python scrapy


code: img1Array[mask] += img2Array[mask]

rawDescription: Add two 3D numpy arrays with a 2D mask

description: Add two 3D numpy arrays with a 2D mask


code:
import pandas as pd
df = pd.DataFrame({'STEPS_ID':range(1107,1113)*2})
df['GROUP'] = (df['STEPS_ID'] < df['STEPS_ID'].shift(1)).astype('int').cumsum()
# df.set_index('GROUP', inplace=True, append=True)
print(df)

rawDescription: Pandas truncate DataFrame after a column condition is met


rawDescription: How to get part of string and pass it to other function in python?

description: Get part of string and pass it to other function in python


code:
import os
import os.path

def get_files(folder_path):
    return [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]

rawDescription: How to read datas from several files with python

description: Read datas from several files with python


code:
filtered = contracts.groupby(['State']).filter(lambda x: x['Year'].nunique() >= len(years))
result = filtered.groupby(['State', 'Year'])['$'].mean()

rawDescription: Pandas Groupby with multiple columns selecting rows with full range of values


code:
for row in csvfile:
    if row[0]:
        rowa.append(row[0])
    if row[1]:
        rowb.append(row[1])

rawDescription: Trying to convert a list of tuples to a list of lists


code:
data = """ifDescr lo
ifDescr eth0
ifAdminStatus 1
ifAdminStatus 1
ifOperStatus 1
ifOperStatus 0"""

from collections import defaultdict

d = defaultdict(list)
for line in data.splitlines():
    a, b = line.split()
    d[a].append(b)
print((d.items()))
[('ifOperStatus', ['1', '0']), ('ifAdminStatus', ['1', '1']), ('ifDescr', ['lo', 'eth0'])]

rawDescription: Grouping data by value in first column

description: Grouping data by value in first column


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

def make_csr(n, N):
    rows = np.random.choice(N, n)
    cols = np.random.choice(N, n)
    data = np.ones(n)
    return csr_matrix((data, (rows, cols)), shape=(N,N), dtype=np.float32)

rawDescription: Csr_matrix.dot vs. Numpy.dot

description: Csr_matrix.dot vs. Numpy.dot


code:
def make_callback(m_type):
    def callback(msg):
        m = m_type(msg)
        pub2.publish(m.to_other_type())
    return callback

callback1 = make_callback(MsgX, msg_type_a)
callback2 = make_callback(MsgY, msg_type_b)

rawDescription: How to avoid similar function definitions in Python?

description: Avoid similar function definitions in Python


code:
with open('test_file.txt','r') as f :
 lines =f.readlines()

rawDescription: How to Empty Lines?

description: Empty Lines


code: text = re.sub(r'(M\w{1,2})\.', r'\1', text) # no for loop needed for this, like there was before

rawDescription: open file and read sentence

description: Open file and read sentence


rawDescription: How do convert unicode escape sequences to unicode characters in a python string


code:
message = "whatever..."*1000
tmp = message
msgList = []
while tmp:
    msgList.append(tmp[:444])
    tmp = tmp[444:]

rawDescription: Splitting string in while loop and appending to list


code: list1.sort(key= lambda x: int(x.split('.')[0].split('-')[1]))

rawDescription: Python sorted list [a1, a2 ... b1, b2]

description: Python sorted list [a1, a2 ... b1, b2]


rawDescription: Celery Logging: consistent way to log inside and outside of a task


code:
def roman_to_int_repl(match):
    return str(roman_to_int(match.group(0)))

rawDescription: Convert a string containing a roman numeral to integer equivalent


rawDescription: How to plot beautifully the segmentation of time series (pandas dataframe)

description: Plot beautifully the segmentation of time series (pandas dataframe)


code:
class Foo(object):
    def __init__(self):
        self.right = False
    def func(self):
        self.right = True

a = Foo() #calls __init__ implicitly
print(a.right)  #should be False -- We set this in __init__
a.func()  #change state of `a`
print(a.right)  #Now it's True!

rawDescription: Arrow key input code not working in tkinter


code:
df=pd.read_csv(url, index_col=0, na_values=['(NA)']).fillna(0)
df.dtypes

rawDescription: pandas: to_numeric for multiple columns

description: Pandas: to_numeric for multiple columns


code:
possibleMatches = soup.select('select[name=languageid] option')
for match in possibleMatches:
    print(match.text, "-", match.get('value'))

rawDescription: Python 3: Can't properly encode and print a downloaded string with /xXX literals


rawDescription: How to get a list of all config args?

description: Get a list of all config args


code:
from .settings import *

DEBUG = False # <-- just add some settings or override the previous ones like this.

rawDescription: BASE_DIR output within a subfolder, DJANGO


code:
import pandas as pd
from datetime import datetime, timedelta

df = pd.read_csv("hourmelt.csv", sep=r"\s+")
df

rawDescription: How to rearrange a python pandas dataframe?

description: Rearrange a python pandas dataframe


code:
import mailbox
from email.utils import parsedate
from dateutil.parser import parse
import itertools
import plotly.plotly as py
from plotly.graph_objs import *
import plotly.tools as tls
import csv
from itertools import izip

path = 'mail.mbox'
mbox = mailbox.mbox(path)

# map date to number of emails seen on that date
date_counts = {}

for message in mbox:
    date = str( parse( message['date'] ) ).split(' ')[0]
    try:
        date_counts[date] += 1
    except KeyError:
        date_counts[date] = 1

with open('data.csv', 'wb') as f:
    writer = csv.writer(f)
    for date in date_counts:
        writer.writerow([date, date_counts[date]])

rawDescription: python, reducing memory consumption and making this code more efficient?

description: Python, reducing memory consumption and making this code more efficient


code:
new_gb = pandas.concat( [ gb.get_group(group) for i,group in enumerate( gb.groups) if i < 5 ] ).groupby('model')
new_gb.hist()

rawDescription: Select multiple groups from pandas groupby object


code:
def create_app():
  app = Flask(__name__)

  @app.route('/')
  def index():
    return render_template('index.html')

  return app

rawDescription: Flask: are blueprints necessary for app factories?


code:
p = np.arange(1, 19)
section_bis = s[p[:, None], p]
section_bis.shape

rawDescription: Slice numpy matrix using vectors as indices


code:
from sklearn.ensemble import GradientBoostingRegressor

gbr = GradientBoostingRegressor(n_estimators=100)
# fit our model
gbr.fit(X_informative, y)
# generate predictions
gbr_preds = gbr.predict(X_informative)

# calculate erros and plot it
gbr_error = y - gbr_preds

fig, ax = plt.subplots()
ax.hist(y, label='y', alpha=0.5)
ax.hist(gbr_error, label='errors in predictions', alpha=0.4)
ax.legend(loc='best')

rawDescription: Using Python to find correlation pairs

description: Using Python to find correlation pairs


code:
# admin.py
from django.contrib import admin

class PlayerInline(admin.TabularInline):
    model = Player

class DivisionAdmin(admin.ModelAdmin):
    inlines = [
        PlayerInline,
    ]

rawDescription: Simple way to show group members in Django Admin?


code:
while gtk.events_pending():
  gtk.main_iteration()

rawDescription: gtk TextView widget doesn't update during function

description: Gtk TextView widget doesn't update during function


code:
pack = "oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64"
reg = re.compile(r"^(?P<package>.*?)-(?P<version>\d.*?)\.(?:noarch|x86_64)$")
m = reg.match(pack)
m.groupdict()

rawDescription: merge multiple regex into one which could "catch them all"

description: Merge multiple regex into one which could "catch them all"


code:
if myPlayer in self.players:
    raise ValueError("Player:  is duplicate")

rawDescription: Adding an object of one class to an object of another class and checking for duplicates in Python


code:
prs = Person.objects.create(name="Tom")
GroupMembers.objects.create(person=prs, group=grp, order=1)
prs = Person.objects.create(name="Dick")
GroupMembers.objects.create(person=prs, group=grp, order=2)
prs = Person.objects.create(name="Harry")
GroupMembers.objects.create(person=prs, group=grp, order=3)

rawDescription: Getting the first item item in a many-to-many relation in Django


code:
import re
s = """> From: "FastTech" <support@fasttech.com>
>
> == Ship to ==
> Example Name
>
> Shipping via Registered Airmail w/Tracking
>
> == Shipping ETA ==
>
> == Items ordered ==
>
> == Other services ==
>
>
> == Order total ==
> $2.63
>
>
>
>
> Thank you again for choosing FastTech.
>
> Kind regards,
>
> The FastTech Team
>
>
> FastTech - gadget and electronics
> http://www.fasttech.com
> support@fasttech.com
>
>
> This email was automatically generated for """
m = re.findall(r'> == Ship to == *\n. (\w+\s\w+)', s)
m

rawDescription: Python regex not working in code

description: Python regex not working in code


code:
yourcounter = itertools.count().next

next_counted_value = yourcounter()

rawDescription: Suggestions to implement an automatic counter in Python


code:
foo()
foo(c='x')  # don't know or care about a and b's value

rawDescription: Python: is this a passing parameter convention?


code:
import tkinter as tk

root = tk.Tk()
e = tk.Entry(root)
e.insert(0, "some text")

def some_callback(event): # note that you must include the event as an arg, even if you don't use it.
    e.delete(0, "end")
    return None

e.bind("<Button-1>", some_callback)

e.pack()

rawDescription: Entry box text clear when pressed Tkinter


code:
import time

def time_func(func):
    try:
        name = func.__name__
    except:
        name = func.f_name
    def tf_wrapper(*args, **kwargs):
        t = time.time()
        ret = func(*args, **kwargs)
        print("{}: {}".format(name, time.time() - t))  # Or use QMessageBox
        return ret
    return tf_wrapper

class myPluginName:
    @time_func
    def firstFunction(self):
        pass

    @time_func
    def secondFunction(self):
        pass

    def run(self):
        self.firstFunction()
myPluginName().firstFunction()

rawDescription: Timeit module for qgis plugin

description: Timeit module for qgis plugin


code: res = add.chunks(zip(range(10), range(10)), 2).apply_async(queue='my_special_queue')

rawDescription: What is the right way to invoke celery.task.chunks?


code:
a = 4
b = 5
a , b  = b, a
a
b
c  = 5
d = 6
t = c
c = d
d = t
c
d

rawDescription: Wrong output in Python - as per my logic


code: articles_liked = Likes.objects.filter(user_id=this_user_id).values_list('article_id', flat = True)

rawDescription: Check a List With If Statement in a Loop Using Python/Django


code:
class MyClass:
    x = 1
    def _make_results(x=x):
        return list(i+x for i in range(10))
    results = _make_results()
    del _make_results    # otherwise it would be added as a method.
    # or:
    results = (lambda x=x: list(i+x for i in range(10)))()

rawDescription: How to reference a static attribute from within a class in Python?

description: Reference a static attribute from within a class in Python


code: df.drop(('col1', 'a'), axis=1)

rawDescription: Dropping a single (sub-) column from a MultiIndex


code:
sprite = sprites[0][0]  # first sprite
timer = sprites[0][1]  # first timer

rawDescription: Pygame sprites timer

description: Pygame sprites timer


code:
re.compile(r"""
    (?:\w+\s){2}        # two words we don't care about
    (                   # begin capturing
      (?:\w+\s?)+       #   1+ word chars followed by an optional space, 1+ times
    )                   # stop capturing""", re.X)

rawDescription: Regex for matching the third,fourth,fifth... word


code:
import sys
sys.path.insert(0, 'lib.zip')

rawDescription: Bootstrapping tests and using Python test discovery


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

fig=plt.figure()
ax1=fig.add_subplot(211)
ax2=fig.add_subplot(212)
ax1.set_ylim(40,50)
ax2.set_ylim(40,70)

def adjust_axes_limits(ax1,ax2):

    yrange1 = np.ptp(ax1.get_ylim())
    yrange2 = np.ptp(ax2.get_ylim())

    def change_limits(ax,yr):
        new_ymin = ax.get_ylim()[0] - yr/2.
        new_ymax = ax.get_ylim()[1] + yr/2.
        ax.set_ylim(new_ymin,new_ymax)

    if yrange1 > yrange2:
        change_limits(ax2,yrange1-yrange2)
    elif yrange2 > yrange1:
        change_limits(ax1,yrange2-yrange1)
    else:
        pass

adjust_axes_limits(ax1,ax2)
plt.show()

rawDescription: same scale of Y axis on differents figures

description: Same scale of Y axis on differents figures


code:
individuals = (np.arange(0,200).reshape(-1,1)*np.ones(10).reshape(1,-1)).flatten()
individuals = pd.Series(individuals)

allCoords = pd.DataFrame(coords, columns = ['x','y'])

plt.scatter(allCoords['x'], allCoords['y'], c = individuals,
      s = 40, cmap = 'hot')

rawDescription: Localized random points using numpy and pandas


code:
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.patches as mpatches
from matplotlib.path import Path
import numpy as np

# Create some lons/lats
lats = np.linspace(20,40,50)
lons = np.linspace(110,130,50)
lons,lats = np.meshgrid(lons,lats)

# Some data with 'cloud'.
thedata = np.zeros_like(lats)
thedata[5:8, 7:13] = 1

pc = ccrs.PlateCarree()
ax = plt.axes(projection=ccrs.Mercator())
ax.coastlines()

# Some decoration to see where we are
gl = ax.gridlines(crs=pc,
                  draw_labels=True,
                  linewidth=2, color='gray', alpha=0.5,
                  linestyle='--')
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER

mycmap = mcolors.ListedColormap(['white', 'black'])
bounds=[0, 0.5, 1]
norm = mcolors.BoundaryNorm(bounds, mycmap.N)

im = ax.pcolormesh(lons, lats, thedata, cmap=mycmap,
                   norm=norm, transform=pc)

proj_extent = np.array(list(pc.x_limits) + list(pc.y_limits))
data_extent = np.array((lons[0,0], lons[-1,-1], lats[0,0], lats[-1,-1]))

# Make the extent larger to see a margin outside of the domain
ax.set_extent(data_extent + [-2, 2, -2, 2])

# Create a path which has the exterior of the map, with an interior of the data we care about.
path_with_hole = Path([[proj_extent[0], proj_extent[3]],
                       [proj_extent[1], proj_extent[3]],
                       [proj_extent[1], proj_extent[2]],
                       [proj_extent[0], proj_extent[2]],
                       [proj_extent[0], proj_extent[3]],
                       [data_extent[0], data_extent[2]],
                       [data_extent[1], data_extent[2]],
                       [data_extent[1], data_extent[3]],
                       [data_extent[0], data_extent[3]],
                       [data_extent[0], data_extent[2]]],
                      codes=[Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO,
                             Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO])

geom = mpatches.PathPatch(path_with_hole, facecolor='lightgrey',
                          edgecolor='white',
                          hatch='xxxx', alpha=0.6, transform=pc)
ax.add_patch(geom)

plt.show()

rawDescription: Cartopy background color (outside of data domain)


rawDescription: Anomalies when trying to fit student's t distribution using scipy


rawDescription: manipulating list items python

description: Manipulating list items python


code:
# data = {}
# key = 'UID'
# value = ('Name','Male','Accountant','20000')
# data[key] = value

def consistency(dictionary):

    temp_list_of_values_we_care_about = [(x[0],x[1],x[2]) for x in dictionary.itervalues()]
    temp_dict = {}

    for val in temp_list_of_values_we_care_about:
        if val in temp_dict:
            temp_dict[val] += 1
        else:
            temp_dict[val] = 1

    if max(temp_dict.values()) >=5:
        return False
    else:
        return True

rawDescription: Python Group by count

description: Python Group by count


code:
db = pymongo.MongoClient().collection.summary
db.update_one({'_id': 1},
    {
        '$inc': {
            'summary.tags.Good' : 1,
            'summary.tags.Enjoy': 1
        }
    })

rawDescription: update mongodb on fly

description: Update mongodb on fly


code:
import numpy
from collections import OrderedDict

choices = OrderedDict()
choices["September"] = 0.90
choices["October"] = 0.25
choices["November"] = 0.45
choices["December"] = 0.50

n_rolls = 5
probs = numpy.random.uniform(size=(n_rolls, len(choices)))
samples = probs < choices.values()

rawDescription: randomly select multichoice options

description: Randomly select multichoice options


code:
if v == 10.10:
    print("Mac OS X v. 10.10 Yosemite")
else:
    print("Mac OS X v. ", v)

rawDescription: Mac OS X Find Version returns two statements


rawDescription: Parsing ifconfig output with python

description: Parsing ifconfig output with python


code:
class Toolbar:
    def __init__(self, width, height): #And other customisation options
        self.image = pygame.Surface(width, height)
        self.image.fill(colour)
        self.rect = self.image.get_rect()
        self.rect.topleft = (0,0)
        self.leftbutton = ButtonClass(args)
        self.rightbutton = ButtonClass(args)

    def update(self):
        self.leftbutton.hover() #to animate an effect if the mouse hovers over
        self.rightbutton.hover()

    def draw(self, screen):
        screen.blit(self.image, self.rect)
        screen.blit(self.leftbutton.draw(), self.leftbutton.getRect())
        screen.blit(self.rightbutton.draw(), self.rightbutton.getRect())

    def click(pos):
        if self.leftbutton.getRect().collidepoint(pos):
            self.leftbutton.click()

        if self.rightbutton.getRect().collidepoint(pos):
            self.rightbutton.click()

rawDescription: Creating a ToolBar in pygame window

description: Creating a ToolBar in pygame window


code:
test_list = [['foo_job', 'bar_user', 'baz_permission'], ['foo_job', 'bar_user', 'spam_permission']]
fDict = {}
for jobName, uname, perms in test_list:
    fDict.setdefault(jobName, {}).setdefault(uname, []).append(perms)

fDict

rawDescription: setdefault - add more than one value to the key

description: Setdefault - add more than one value to the key


code:
n = sympyexpression_whichevaluatestoacomplexnumber
expressionangle = sympy.arg( n )

rawDescription: Python Sympy angle of a complex number?

description: Python Sympy angle of a complex number


code: [eelem for eelem in e if any(eelem in relem for relem in r)]

rawDescription: Cross Matching in python

description: Cross Matching in python


code:
from celery.result import AsyncResult
...
@app.route('/status/<task_id>/')
def status(task_id):
    task = AsyncResult(task_id) # retrieving the task we started
    if task.state == 'PROGRESS':
        response = {
            'state': task.state,
            'current': task.info.get('current', 0)
        }
    return jsonify(response)

rawDescription: How to retrieve meta from celery backend storage

description: Retrieve meta from celery backend storage


code:
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute ("""
              CREATE TABLE users (
                  uid INTEGER PRIMARY KEY AUTOINCREMENT,
                  username TEXT UNIQUE,
                  email TEXT UNIQUE );
             """)

test_users = (
    {'username':"Alice",    'email':"Alice@mail.com"},
    {'username':"Billy",    'email':"Billy@mail.com"},
    {'username':"Charles",  'email':"Charles@mail.com"},
    {'username':"Dick",     'email':"Dick@mail.com"},
    {'username':"Emily",    'email':"Emily@mail.com"},
    {'username':"Faramir",  'email':"Faramir@mail.com"},
)

for user in test_users:
    conn.execute("INSERT INTO users (username, email) VALUES (?,?)",
                 (user['username'],user['email'])
                )

result = conn.execute("SELECT COUNT(*) FROM users WHERE username='Alice'")
number_of_Alices = result.next()[0] # number_of_Alices will be 1

rawDescription: SQLite / Python database retrieval and comparison


code:
import math
x = (2<<53) + 1
int(math.sqrt(x*x)) == x

rawDescription: Exactness of integer square root in Python


code:
import csv

with open('output.csv', 'w') as csvfile:
    fieldnames = ['Program', 'Version', 'Count']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for k, v in data.iteritems():
        for id, count in v.iteritems():
           f.write({'Program':k, 'Version':id, 'Count':count})

rawDescription: Printing nested dicts to CSV in Python

description: Printing nested dicts to CSV in Python


code: myDict[name] = value

rawDescription: Add results from a for loop in a dict, Python


code:
cmd_template = 'SMILExtract -C {config_path} -I {wav_base}.wav -O {csv_path}'
os.system(cmd_template.format(
  config_path='config/demo/demo1_energy.conf',
  wav_base='user',
  csv_path='csv/user.csv',
))

rawDescription: variable inside a string used as an os command in python

description: Variable inside a string used as an os command in python


code: result = df.groupby(['A']).agg({'C': lambda x: x.sum()/x.count(), 'D':'sum'})

rawDescription: Aggregate groups in Python Pandas and spit out percentage from a certain count


code: numbersList = re.findall('{"number":(\d{x,y})', myFile.read(), re.DOTALL)

rawDescription: python, regex: What RegEx do I need?

description: Python, regex: What RegEx do I need


rawDescription: Converting String Date to Timestamp and back python


code:
results = [(10, 'Mary'), (9, 'John'), (10, 'George'), (9, 'Frank'), (9, 'Adam')]
results.sort(key=lambda x: x[1])
results.sort(key=lambda x: x[0], reverse=True)
results

rawDescription: How can I sort tuples by reverse, yet breaking ties non-reverse? (Python)

description: Sort tuples by reverse, yet breaking ties non-reverse? (Python)


code:
from mongoengine import connect
from mongoengine.connection import _get_db

connect('test')

db = _get_db()
db.connection.drop_database('test')

rawDescription: Dropping all collections in Mongoengine

description: Dropping all collections in Mongoengine


rawDescription: A templated constructor cursor and a templated member cursor have kind FUNCTION_TEMPLATE in libclang


rawDescription: Why won't my for loop work? (Python)

description: Why won't my for loop work? (Python)


code:
def printTable (tbl, borderHorizontal = '-', borderVertical = '|', borderCross = '+'):
    cols = [list(x) for x in zip(*tbl)]
    lengths = [max(map(len, map(str, col))) for col in cols]
    f = borderVertical + borderVertical.join(' {:>%d} ' % l for l in lengths) + borderVertical
    s = borderCross + borderCross.join(borderHorizontal * (l+2) for l in lengths) + borderCross
    rtr=[s]

    for row in tbl:
        rtr.append(f.format(*row))
        rtr.append(s)

    return '\n'.join(rtr)

print(printTable(table))

rawDescription: How do I shift rows of consecutive numbers. Python 3.3.2

description: Shift rows of consecutive numbers. Python 3.3.2


code:
with open('test.txt','r') as myfile:
    mylist = [line.strip().split('|') for line in myfile]

rawDescription: Python operation with delimited texts in text file


code:
def wrapped_lines(line, width=80):
    whitespace = set(" \n\t\r")
    length = len(line)
    start = 0

    while start < (length - width):
        end = start + width + 1
        chunk = line[start:end]
        try:
            end = start + chunk.index('\n')
        except ValueError: # no newline in chunk
            # we iterate characters from the end:
            for i, ch in enumerate(reversed(chunk)):
                if ch in whitespace:
                    end -= i # we have our end on first whitespace
                    break
        yield line[start:end]
        start = end + 1
    yield line[start:]

rawDescription: How to limit the number of characters per line without affecting a word?

description: Limit the number of characters per line without affecting a word


code: 'Willem Jan van Steen         9859  77\n'.rsplit(None, 2)

rawDescription: python parsing input, making a sum of the input

description: Python parsing input, making a sum of the input


code:
def valid(name):
    if name[0].isdigit():
       return False
    for c in name:
       if not (c.isalnum() or c == '_'):
          return False
    return True

def main():

    while True:

        name = input("Enter your Python variable name or 'done': ")

        if name == "done":
           break

        if valid(name):
            print("This is a valid variable name.")
        else:
            print("This is not a valid variable name.")

main()

rawDescription: Python- checking for letters, numbers, and underscore character.


code:
url(r'^choose/$', views.choose_city, name='choose_city'),
url(r'^deals/(?P<city_id>\d+)/$', views.deals_by_city, name='deals_by_city'),

rawDescription: Django forms and passing data between views/pages


code:
import csv

data = [[u'Neoplasms', u'Medical Subject Headings', u'direct', u'cancer', u'Neoplasms', u'Medical Subject Headings', u'Malignant Neoplasm', u'National Cancer Institute Thesaurus', u'direct', u'cancer', u'Malignant Neoplasm', u'National Cancer Institute Thesaurus']]

with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerows(data)

rawDescription: Save data to csv file using Python

description: Save data to csv file using Python


code:
for i in kinetic_parameters:
        if d.get(i[1]) is None:
            d[i[1]]={}
        d[i[1]][i[2]]=i[3]

rawDescription: How can I correct my code to produce a nested dictionary?

description: Correct my code to produce a nested dictionary


code:
rental_avg_costperweek = 0
for this_id in closest_rental_ids:
    rental = LLSRental.select(LLSRental.id == this_id)
    rental_avg_costperweek += calcCostPerWeek(rental.price, rental.rental_freq)
rental_avg_costperweek /= len(closest_rental_ids)

rawDescription: How much nesting of python list comprehensions is appropriate?


code: df1.change.shift(1) - df1.change

rawDescription: get previous row's value and calculate new column pandas python

description: Get previous row's value and calculate new column pandas python


code:
import re
reqset = {re.search('SRC=(\S+)',l).group(1) for l in content}
print('\n'.join(reqset))

rawDescription: How to get the nth parameter of a list with delimiter space in python

description: Get the nth parameter of a list with delimiter space in python


code:
class Demo(object):
    def __init__(self):
        self._shared = None

    @property
    def a(self):
        return self._shared

    @a.setter
    def a(self, value):
        self._shared = value

    @property
    def b(self):
        return self._shared

    @b.setter
    def b(self, value):
        self._shared = value

rawDescription: Transitive value assignation in Python classes


code:
# value is a float .01 to .99
def set_alpha(image, value):
    array = pygame.surfarray.pixels_alpha(image)
    for x in xrange(array.shape[0]):
        for y in xrange(array.shape[1]):
            array[x][y] = int(array[x][y] * value)

rawDescription: Set constant translucency for background


code:
from bokeh.plotting import *

output_file("foo.html")

inds = [str(x) for x in [2, 5, 6, 8, 9]]
colors = ["red", "orange", "blue", "green", "#4488aa"]

rect(inds, inds, 1.0, 1.0, color=colors, x_range=inds, y_range=inds)

show()

rawDescription: Plot topics with bokeh or matplotlib

description: Plot topics with bokeh or matplotlib


code: non_vowels = bytes(set(range(0x100)) - set(b'aeiou'))

rawDescription: Deleting consonants from a string in Python


code: combo.setItemData(index, 'other data', QtCore.Qt.UserRole + 1)

rawDescription: Inserting hidden data into a combobox pyqt


rawDescription: (Single line) command to join list of lists, where the inner list are joined by spaces and the outer lists are joined by '\n'


code:
def __str__(self):
    return "date added:   %s\nPrice:        %s\nReport:       %s\nretail price: %s\nuser:         %s" % tuple([str(i) for i in vars(self).values()])

rawDescription: How to use pprint to print an object using the built-in __str__(self) method?

description: Use pprint to print an object using the built-in __str__(self) method


code:
from decimal import Decimal
b = Decimal('nan')
print(b)
print(repr(b))
Decimal(float('nan'))

import math
math.isnan(b)

rawDescription: Assigning a variable NaN in python without numpy


code:
[(-1, 'This is m'), (1, 'M'), (0, 'y'), (-1, ' original'), (0, ' paragraph'), (1, ' is much better now'), (0, '.')]
[(-1, 'This is my original paragraph'), (1, 'My paragraph is much better now'), (0, '.')]

rawDescription: Paragraph Matching Python

description: Paragraph Matching Python


code:
class file_iterator ():
    def __init__ (self, filename, begin, end):
        self.file = open (filename)
        self.line_number = 0
        self.begin = begin
        self.end = end

    def __iter__ (self): return self

    def next (self):
        for line in self.file:
            self.line_number += 1
            if self.begin <= self.line_number <= self.end:
                return line
        raise StopIteration

rawDescription: numpy: How to load a bounded (R1 C1 to R2 C2) matrix from file

description: Numpy: How to load a bounded (R1 C1 to R2 C2) matrix from file


code:
def all_subclasses(cls):
    return cls.__subclasses__() + [g for s in cls.__subclasses__()
                                   for g in all_subclasses(s)]

print(all_subclasses(vars()['Foo']))
# [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

rawDescription: How can I find all subclasses of a given class in Python?

description: Find all subclasses of a given class in Python


rawDescription: How to limit decimal places when using complex numbers

description: Limit decimal places when using complex numbers


code:
from fileinput import input
from sys import stdout

line = "2    5             9            10.4"

r, st, ed, val = line.split()
r, st, ed = int(r), int(st), int(ed)
for ind, line in enumerate(input("test.txt",inplace=True), 1):
    if ind == r:
        stdout.write(line.replace(line[st-1:ed], val))
    else:
        stdout.write(line)

rawDescription: change a value in a specific location in a text file in python

description: Change a value in a specific location in a text file in python


code: a = {k.replace('1','3'): v for k,v in self.test_lockCheck().iteritems()}

rawDescription: Python; Search and Replace; Lists; Strings


rawDescription: numpy where compare arrays as a whole

description: Numpy where compare arrays as a whole


code: my_list.count(1) < 25 or my_list.count(1) > 25

rawDescription: Why my_list.remove(x) doesn't work

description: Why my_list.remove(x) doesn't work


code:
import json

from django.shortcuts import render
from django.http import HttpResponse

from forms import CollegeForm
from models import CollegeInfo

def original_endpoint(request):
    # ...
    if request.method == 'POST':
        college_form = CollegeForm(request.POST)
    else:
        college_form = CollegeForm()
    return render(request, 'market/product_list.html', {'college_form': college_form})

def college_data_endpoint(request, college_name):
    """
    Endpoint for sending back college-specific data

    Response sent back in json format to make for easier processing with javascript
    """

    # Get college-specific data from the db
    college = CollegeInfo.objects.get(id=college_name)

    # format it
    response_data = {
        'field1': college.field1,
        'field2': college.field2
    }

    return HttpResponse(json.dumps(response_data), content_type='application/json')

rawDescription: Get POST value from select tag in Django 1.7


rawDescription: Get rid of Mongo $ signs in JSON

description: Get rid of Mongo $ signs in JSON


code:
with open('somefile') as fin:
    lines = (line.split(None, 2) for line in fin if line.strip())
    for k, g in groupby(lines, lambda L: L[:2]):
        lines = [el[2] for el in g]

rawDescription: Python- group lines by first two words

description: Python- group lines by first two words


code: filter(lambda dt: hasattr(dt, 'hour') and dt.hour % 6, dates)

rawDescription: Chaining operator functions in Python's filter


rawDescription: Numpy argwhere inequality conditions

description: Numpy argwhere inequality conditions


code:
from collections import Counter, OrderedDict

class OrderedCounter(Counter, OrderedDict):
    pass

rawDescription: Find the occurrences of unique element in list in python


code:
outlists = []

for func in functions:
    thislist = []
    for j in y:
        thislist.append(func(j*2))
    outlists.append(thislist)

rawDescription: Loop through function in python generating separate list for each set of data


code:
df = pd.read_hdf('test.h5','df',where='date=>global_start_date & date<=global_end_date')
df[df.isin(list_of_ids)]

rawDescription: Query HDF5 in Pandas

description: Query HDF5 in Pandas