code:
key = OpenKey(HKEY_LOCAL_MACHINE, net, 0,
              KEY_READ | KEY_WOW64_64KEY)

rawDescription: How do I use Python to retrieve Registry values?

description: Use Python to retrieve Registry values


code:
class C(object):
    @property
    def prop(self):
        return 'abc'

C.prop
C.prop.fget

rawDescription: python attribute lookup without any descriptor magic?

description: Python attribute lookup without any descriptor magic


code:
newdic = {}
for k,v in items.items():
    for i in v:
        if i not in newdic:
              newdic[i] = set()
        newdic[i].add(k)

newdic

rawDescription: Reversing logic of a product-country mapping


code: qs = posts | comments

rawDescription: How Do I Select From Two Different Tables in Django?


rawDescription: SQLAlchemy freezing application

description: SQLAlchemy freezing application


code:
ax1.get_xlim()
ax2.get_xlim()

rawDescription: matplotlib - Second X axis has an offset (wrt 1st X axis) I can't pin down

description: Matplotlib - Second X axis has an offset (wrt 1st X axis) I can't pin down


rawDescription: Any way to speed up Python and Pygame?

description: Any way to speed up Python and Pygame


code:
import random
words = [x.rstrip() for x in random.sample(open('in.txt').readlines(), 9)]

grid = [words[i:i + 3] for i in range(0, len(words), 3)]

[['BLUE', 'ANGRY', 'RED'], ['HAPPY', 'FOO', 'ORANGE'], ['JOYFUL', 'YELLOW', 'SAD']]

rawDescription: Creating a 3x3 grid from a text file Python 3


code: recs.sort(key=lambda rec: rec['data'])

rawDescription: Filter latest items in a list

description: Filter latest items in a list


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

latlon_ar = np.array(latlon)

threshold = 90
idx_wrap = np.nonzero(np.abs(np.diff(latlon_ar[:,1])) > threshold)[0]+1

lon_1 = lon[:idx_wrap]
lat_1 = lat[:idx_wrap]

lon_2 = lon[idx_wrap:]
lat_2 = lat[idx_wrap:]

f = plt.figure(figsize(10,7.5))
m = Basemap(projection="mill", lon_0=0)

m.drawcoastlines()
m.drawparallels(np.arange(-90,91,30),labels=[1,0,0,0])
m.drawmeridians(np.arange(-180,181,60), labels=[0,0,0,1])

x1, y1 = m(lon_1, lat_1)
x2, y2 = m(lon_2, lat_2)

m.plot(x1, y1, color="red", latlon=False)
m.plot(x2, y2, color="blue", latlon=False)

rawDescription: Plotting a wrapped path in Basemap

description: Plotting a wrapped path in Basemap


code: new_data = data[['a','b','c']].astype(np.float).reshape((data.size, 3))

rawDescription: Converting (part of) a numpy recarray into a 2d array?


code:
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request
from mike.items import MikeItem

class SonrisSpider(scrapy.Spider):
    name = "sspider"
    allowed_domains = ["sonlite.dnr.state.la.us"]
    start_urls = [
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=207899",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=971683",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=214206",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=159420",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=243671",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=248942",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=156613",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=972498",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=215443",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=248463",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=195136",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=179181",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=199930",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=203419",
                "http://sonlite.dnr.state.la.us/sundown/cart_prod/cart_con_wellinfo2?p_WSN=220454",
            ]

    def start_requests(self):
        for url in self.start_urls:
            yield Request(url=url, callback=self.parse_data, dont_filter=True)

    def parse_data(self, response):
        item = MikeItem()
        serial = response.xpath(
            '/html/body/table[1]/tr[2]/td[1]/text()').extract()
        serial = serial[0] if serial else 'n/a'
        item['serial'] = serial
        yield item

rawDescription: Scrapy only scrapes the first start url in a list of 15 start urls


code:
num_samples = 10000
for count in range(100):
    dup = 0
    for test_number in range(num_samples):
        the_list = make_birthday_list(count)
        if duplicates(the_list):
            dup += 1
    print(count, dup/num_samples)   # / returns a float in Python3

rawDescription: Python 3.3: Birthday Probablity

description: Python 3.3: Birthday Probablity


rawDescription: Django 1.6: Redirect to last page after login not working


code: total_time = max(all_individual_times) + n*some_overhead

rawDescription: How to improve the performance of the combination of gevent and tornado?

description: Improve the performance of the combination of gevent and tornado


code:
import requests
data = {"myparam": "1234"}
headers = {'User-Agent': 'Mozilla 5.0','referer':'https://myreferer'}

rawDescription: Python equivalent to curls --form: Create multipart form-data post request with data in "form" parameter


code:
import datetime

then = datetime.datetime(year=2015, month=1, day=1)
now = datetime.datetime.now()

difference = now - then

rawDescription: Subtracting Months/Years

description: Subtracting Months/Years


code:
isinstance(type, object)
isinstance(object, type)
isinstance(type, type)

rawDescription: how does Cpython implement its type Objects, i.e. type's type is always type?

description: How does Cpython implement its type Objects, i.e. type's type is always type


code:
only_in_range = sets.restrict(data_clan, record_in_range)
print(only_in_range)

rawDescription: Comparing date object in a Couplet between two dates


code:
import pandas as pd

df = pd.DataFrame({'Name1':['a','a','a','b','b','b'],
                   'Name2':[1,2,4,2,4,8],
                   'present':[1,1,3,1,5,1]})
df.set_index(['Name1','Name2'], inplace=True)

df2 = pd.DataFrame({'Data1':[80,61,45,30],
                    'Data2':[6,8,7,3]},
                   index=pd.Series([1,2,4,8], name='Name2'))
result = df.reset_index(level=0).join(df2).set_index('Name1', append=True)
print(result)
#              present  Data1  Data2
# Name2 Name1
# 1     a            1     80      6
# 2     a            1     61      8
#       b            1     61      8
# 4     a            3     45      7
#       b            5     45      7
# 8     b            1     30      3

rawDescription: Pandas: Merge or join dataframes based on column data?


code:
import matplotlib.pyplot as plt
#Plot convex hull
for simplex in hull.simplices:
    plt.plot(points[simplex, 0], points[simplex, 1], 'k-')

#Plot centroid
plt.plot(cx, cy,'x',ms=20)
plt.show()

rawDescription: Scipy: Centroid of convex hull

description: Scipy: Centroid of convex hull


code:
df.loc[(df['status'].isin(['A','P'])),'end_date'] = Timestamp('20130101')
df

rawDescription: Modifying a column depending on multiple conditions from another column, Pandas


code:
for idx, word in enumerate(unique_everseen(reader), 1):
    print(idx)

rawDescription: Faster than dict way to assign index to strings python


code:
f = open(filename, 'r') #we're just reading it now, so we use mode 'r'
strFile = f.read()
f.close()

rawDescription: Simple way to perform various replacements of string in a txt and erase whitespaces with python


code:
def make_comparator(less_than):
    def compare(x, y):
        if less_than(x, y):
            return -1
        elif less_than(y, x):
            return 1
        else:
            return 0
    return compare

sortedDict = sorted(subjects, cmp=make_comparator(cmpValue), reverse=True)

rawDescription: Using a comparator function to sort

description: Using a comparator function to sort


code:
list1
list2

rawDescription: Randomize two lists by maintaining the sequence of mapping of values in the lists


code:
import nltk
html = """

I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.
With xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !

"""
nltk.clean_html(html)

rawDescription: How can I get all the plain text from a website with Scrapy?

description: Get all the plain text from a website with Scrapy


rawDescription: Python: Grouped constants with possibility to iterate over group


code:
for d in r.json()['results']:
    print('{first_name} {last_name}: {twitter_id}'.format(**d))

rawDescription: how to access key values in a json files dictionaries with python

description: Access key values in a json files dictionaries with python


code:
import collections

key_value_pairs = [('Civic86', 12.5),
                   ('Camry98', 13.2),
                   ('Sentra98', 13.8)]
smallestCars = collections.OrderedDict(key_value_pairs)

for car in smallestCars:
    print(car)

rawDescription: Print original input order of dictionary in python


code:
def push_to_s3(photo, filename):
    # ... snip ...
    k.set_contents_from_file(photo, rewind=True)
    # ... etc. ...

rawDescription: Is there a cleaner way to rotate smartphone images uploaded via flask before pushing to S3?


code:
import json

with open(filename, "r+") as data:
    scores_dict = json.loads(data.read())
    scores_dict[student_full_name] = correct # if already exist it will be updated otherwise it will be added
    data.seek(0)
    data.write(json.dumps(scores_dict))
    data.truncate()

rawDescription: How Do I Change the Data Stored in a Text File in Python?


rawDescription: Convert a 3D array to 2D array based on dictionary


code:
def collatz(start):
    current = start

    yield current

    while current != 1:
        if current % 2 == 0:
            current /= 2
        else:
            current = current * 3 + 1

        yield current

rawDescription: Is it safe to append to a list during iteration if I want to iterate over the added value?


code:
class FooError(BaseException):
    pass

def foo(x):
    sleep(0.1)
    # 50% chance to have a fault
    if random.rand() > 0.5:  # fault condition
        raise FooError('foo had an error!')
    return x, x

def successful_foo(x):
    '''Version of the foo(x) function that never fails.'''

    while True:
        try:
            return foo(x)
        except FooError as e:
            pass  # Log appropriately here; etc.

rawDescription: Dynamically add arguments to a Pool of workers


code:
import itertools

results = list(itertools.takewhile(lambda x: x[0] > 0.9 * x[1],
                                   itertools.izip(reversed(sub),
                                                  runningMean(reversed(sub)))))

rawDescription: To stop finding running average once the condition fails?


code:
def twopointcorr2(x, y, s, dr):
    width = np.max(x)-np.min(x)
    height = np.max(y)-np.min(y)
    n = len(x)
    maxR = np.sqrt((width/2)**2 + (height/2)**2)
    r = np.arange(0, maxR, dr)
    osub = lambda x:np.subtract.outer(x, x)

    ind = np.clip(np.round(np.hypot(osub(x), osub(y)) / dr), 0, len(r)-1).astype(int)
    rw = np.bincount(ind.ravel())
    rw[0] -= len(x)
    corrfun = np.bincount(ind.ravel(), (osub(s)**2).ravel())
    return r, corrfun, rw

rawDescription: Vectorizing for loop with repeated indices in python


code:
if U == 0:
   multiplier = 1
elif U > 0:
   multiplier = U/100.0 + 1
else:
   multiplier = (100 - (U * -1.0))/100.0

rawDescription: How to compute a percentage increase/decrease multiplier in python without if statements

description: Compute a percentage increase/decrease multiplier in python without if statements


code:
# Get shape info and the middle column index
M,N = A.shape
mid_col_idx = int(N/2)

# Get required shifts for each row
shifts = mid_col_idx - np.argmax(A,axis=1)

# Get offsetted column indices
offsetted_col_idx = np.mod(np.arange(N) - shifts[:,None],N)

# Finally generate correctly ordered linear indices for all elements
# and set them in A in one-go
Aout = A.ravel()[offsetted_col_idx + N*np.arange(M)[:,None]]

rawDescription: Shift matrix rows to have maxima in the middle


code:
color = ['k', 'r','g', 'b']
alist = customfigure() # (customfigure doesn't need to take any
                       # arguments now)
for i in xrange(4):
    s = np.sin(2*(i+1) * np.pi * t)
    plt.sca(alist[i])
    plt.plot(t, s, '-', color = color[i])

rawDescription: Figure appearance is not preserved when its axes are added to new figure


code:
from collections import Counter
Counter(char for char in 'big data examiner' if char != ' ')

rawDescription: default dict counts for spaces in python

description: Default dict counts for spaces in python


code: #! python3

rawDescription: In CMD "python" starts Python 3.3, "py" starts Python 2.7, how do I change this?


code:
clubs = {}

for table in soup.find_all('table', class_='tabelle_grafik'):
    club_name = table.find('th', class_='al').text
    count = len(table.find_all('a'))
    clubs[club_name] = count

rawDescription: BeautifulSoup, how to stop executing at certain tag


code:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

rawDescription: Sort a Python dictionary by value

description: Sort a Python dictionary by value


code: {{ project.leaders }}

rawDescription: django concat string with comma in template

description: Django concat string with comma in template


code:
import re
sfxs = ['suffix1', 'sfx2', 'suffix333']
s = 'string-to-process-sfx2'
re.sub(r'(' + '|'.join(sfxs) + r')$', '',s)
re.sub(r'\b(' + '|'.join(sfxs) + r')$', '',s)
re.sub(r'-(' + '|'.join(sfxs) + r')$', '',s)

rawDescription: Python: what's a more compact/efficient way to strip string of a suffix from list?


rawDescription: Named Stuctured Data storage in Python

description: Named Stuctured Data storage in Python


rawDescription: Python: Mean of several dictionaries with the same keys


code:
from enum import Enum

class CommonNames(Enum):
    C1 = 'c1'
    C2 = 'c2'
    C3 = 'c3'

values = [e.value for e in CommonNames]

rawDescription: Getting all constants within a class in python


code:
df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'),  'col3':list('ababb')})
df['col2'] = df['col2'].astype('category')
df['col3'] = df['col3'].astype('category')
df.dtypes

rawDescription: Convert categorical data in pandas dataframe


rawDescription: What is the best way to parse a colon separated string with pyparsing


code:
counter={}.fromkeys(s, 0)
counter
for c in s:
   counter[c]+=1

counter

rawDescription: Nested for-loops and dictionaries in finding value occurrence in string


code:
def findFullURL(d, e, s):
    a = s[d]
    if a != "/":
        #Subtract from d to move back another letter
        d = d - 1
        return findFullURL(d, e, s)   # <<<<<<< here
    else:
        fullURL = "http://download.ted.com/talks/" + s[(d+1):e] + "-480p.mp4"
        #print(fullURL)
        return fullURL

rawDescription: Python 3.2.2 Function Returns None on Non-Empty Variable


code:
if GO_TO_MAX_SPEED_CONDITION:
    while NOT_AT_MAX_SPEED:
        ACCELERATE

rawDescription: Need help detecting a change in a variable outside of a while loop


code:
def main() :
    # keep reference to threads
    threads = [threading.Thread(target=run) for _ in range(20)]
    # start all threads
    for t in threads:
        t.start()

    #20 jobs are put in the queue
    for x in range(1,21) :
        q.put(x)
    #waits until queue is empty and then continues
    q.join()
    # join all threads
    for t in threads:
        t.join()

rawDescription: The correct implementation of queue.Queue when multithreading in Python


code:
import csv

with open('output_file.csv', 'w') as f:
    csv_w = csv.writer(f)
    for rec in time_deltas(infile):
        csv_w.writerow(rec)

rawDescription: How do I get my output in column format?

description: Get my output in column format


rawDescription: Pivot table from a pandas dataframe without an apply function


rawDescription: Copying Text in Python and Preserving/Finding Special Characters


code:
firstName
lastName
number
children

rawDescription: reverse template with python

description: Reverse template with python


code:
result.columns = ['a','c','e','b','d']
result.reindex(columns=sorted(result.columns))

rawDescription: Groupby Pandas DataFrame and calculate mean and stdev of one column and add the std as a new column with reset_index


rawDescription: minidom.parse reading short XML?

description: Minidom.parse reading short XML


code:
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
   print("Connected with result code "+str(rc))
   client.subscribe("Labbo/control")

def on_message(client, userdata, msg):
   print(msg.topic+" "+str(msg.payload))
   char = str(msg.payload)
   if char == 'x':
       client.disconnect()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60)
client.loop_forever()

rawDescription: Controlling Program with MQTT and Python


code:
def __init__(self, elements):
    self.list = elements

rawDescription: How to use __repr__ to create new object from it?

description: Use __repr__ to create new object from it


code: print(*('\t'.join(map(str, item)) for item in mylist), sep='\n')

rawDescription: Pretty print Python Lists

description: Pretty print Python Lists


code:
from itertools import groupby
words.sort()
dct = {k: sum(1 for _ in g) for k, g in groupby(words)}

rawDescription: Python: count occurrences in a list using dict comprehension/generator


code:
import numpy as np
import cv2
import Tkinter as tk
import Image, ImageTk

#Set up GUI
window = tk.Tk()  #Makes main window
window.wm_title("Digital Microscope")
window.config(background="#FFFFFF")

#Graphics window
imageFrame = tk.Frame(window, width=600, height=500)
imageFrame.grid(row=0, column=0, padx=10, pady=2)

#Capture video frames

cap = cv2.VideoCapture(0)

def show_frame():
    _, frame = cap.read()
    frame = cv2.flip(frame, 1)
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    imgtk = ImageTk.PhotoImage(image=img)
    display1.imgtk = imgtk #Shows frame for display 1
    display1.configure(image=imgtk)
    display2.imgtk = imgtk #Shows frame for display 2
    display2.configure(image=imgtk)
    window.after(10, show_frame)

display1 = tk.Label(imageFrame)
display1.grid(row=1, column=0, padx=10, pady=2)  #Display 1
display2 = tk.Label(imageFrame)
display2.grid(row=0, column=0) #Display 2

#Slider window (slider controls stage position)
sliderFrame = tk.Frame(window, width=600, height=100)
sliderFrame.grid(row = 600, column=0, padx=10, pady=2)

show_frame() #Display
window.mainloop()  #Starts GUI

rawDescription: Using OpenCV with Tkinter

description: Using OpenCV with Tkinter


code:
from collections.abc import Mapping

class Foo(Mapping):
    def __iter__(self):
        yield "a"
        yield "b"

    def __len__(self):
        return 2

    def __getitem__(self, item):
        return ord(item)

f = Foo()

print(*f)
print(dict(**f))

rawDescription: Custom double star operator for a class?

description: Custom double star operator for a class


rawDescription: How can I use the ".title() command to read a text file and capitalize every word in the file?

description: Use the ".title() command to read a text file and capitalize every word in the file


rawDescription: Regex - matching numbers between hyphens


rawDescription: How to use lattice in Rpy2 and save result to pdf?

description: Use lattice in Rpy2 and save result to pdf


code: arts = d['artist'].lower()

rawDescription: Put dict into new list based on a key value in Python


code:
@cache_result
def do_once():
    print('doing it once')
    return 'expensive result'

rawDescription: Python method which computes the result only on the first call, without extra parameters


code:
m = 4; n = 2; p = 3; q = 5
a = np.arange(m*n*p*q).reshape(p*q, m*n)
a.T.reshape(m, n, p, q).transpose(0, 2, 1, 3).reshape(m*p, n*q)

rawDescription: Building block matrix from array in the correct order


code:
d
d.replace(day=1 if d.day < 15 else 15)
t = pd.Timestamp(d)
t.replace(day=1 if t.day < 15 else 15)

rawDescription: In python convert day of year to month and fortnight


code:
def trans(year, month, location):
    return dict(year=year, month=month, location=location)

rawDescription: python's ".format" function

description: Python's ".format" function


code:
while True:
        moduleName = raw_input("Please enter module name: ")
        if moduleName == "-1":
            break
        grade = raw_input ("Please enter students grade for " + moduleName+": ")

rawDescription: Saving Raw_input to a list when used in a While Loop


code:
class ui():
    def start(self): print("Started!")

Game = type("Game", (ui,), {})
game = Game()
game.start()

rawDescription: Python 3 dynamically assign base class

description: Python 3 dynamically assign base class


rawDescription: How to retrieve all indexes from pandas DataFrame

description: Retrieve all indexes from pandas DataFrame


code:
class TestSomeFeatureWithDataXYZ(testbase.TestSomeFeature):
    @property
    def test_data_A(self):
        return json.load("data/XYZ.json")

rawDescription: A long definition of an object inside a Python unit test


code:
scrolled_window = Gtk.ScrolledWindow()
scrolled_window.add_with_viewport(self.objectsView)
scrolled_window.set_property("shadow_type","in")

rawDescription: Python GTK3 Treeview buttons

description: Python GTK3 Treeview buttons


code:
t = Test()
args = [1,2,3]
kwargs= {'a':1,'b':2}
t.f1(*args,**kwargs)
t.f1(**kwargs)

rawDescription: how to make *args optional in python when **kwargs is given?

description: Make *args optional in python when **kwargs is given


code:
for k in range(9):
    for rest in product(letters, repeat=k):
        yield (first_letter,) + rest

rawDescription: fractionate a combination generator to distribute it with celery

description: Fractionate a combination generator to distribute it with celery


rawDescription: How to print Radio Control information

description: Print Radio Control information


code:
l_max=[1,2,3]
a=l_max # a points to l_max
b=a     # b points to a
c=b     # so on
s=c     # so forth
s.insert(0, 0) # insert into the only list, which all variable point to

rawDescription: python: list.insert: Insert an item at a given position

description: Python: list.insert: Insert an item at a given position


rawDescription: How do I get Python and Selenium to click an angularjs link by matching the link to user input text?

description: Get Python and Selenium to click an angularjs link by matching the link to user input text


code:
class HiddenInteger(IntegerField):
    widget = HiddenInput()

rawDescription: How can I use a HiddenField to coerce integer data in WTForms?

description: Use a HiddenField to coerce integer data in WTForms


code:
myList = ['L', 'H', 'V', 'M']
''.join(reversed(myList))
''.join(myList[::-1])

rawDescription: How do I reverse items from a list and store it as a string in python

description: Reverse items from a list and store it as a string in python


code: df.sub(df.mean(axis=1), axis=0)

rawDescription: Pandas: Subtract row mean from each element in row


code:
import mock

def testClearWasCalled(self):
   aw = aps.Request("nv1")
   with patch.object(aw, 'Clear') as mock:
       aw2 = aps.Request("nv2", aw)

   mock.assert_called_with(42) # or mock.assert_called_once_with(42)

rawDescription: Assert that a method was called in a Python unit test


code:
conditions = {
      key1: value1,
      key2: value2,
    }

rawDescription: Is there any way to compress test cases?

description: Is there any way to compress test cases


code: df.apply(func, axis=1)

rawDescription: python dask DataFrame, support for (trivially parallelizable) row apply?

description: Python dask DataFrame, support for (trivially parallelizable) row apply


code:
class Artist(HasPhotos, db.Model):
    pass

rawDescription: Polymorphic belongs-to relationships in SQLAlchemy?


code: new = [line for line in new_lines if line not in existing_lines]

rawDescription: How to compare all lines in some file with another line?

description: Compare all lines in some file with another line


code: cleaned = [i for i in (word.strip() for word in words) if i]

rawDescription: Python - are there other ways to apply a function and filter in a list comprehension?


rawDescription: Python: Delete specific timestamp index row (independently of date)


code:
vbump(np.array([-0.99]))
vbump(np.array([-0.99])).dtype
vbump(np.array([-1.0]))
vbump(np.array([-1.0])).dtype

rawDescription: Python - expanding numpy array changes all values of vectorized function


rawDescription: how to check if a value exists in any array in python dictionary values?

description: Check if a value exists in any array in python dictionary values


rawDescription: How to import and create my class from my module?

description: Import and create my class from my module


code:
from pylab import *

from matplotlib import pyplot,colors
import matplotlib as mpl

fig = pyplot.figure(figsize=(8,1.5))
ax1 = fig.add_axes([0.05, 0.25, 0.82, 0.5])

cmap = colors.ListedColormap(['r', 'g', 'b', 'k','y'])

xBounds =  array([0, 1, 2, 4, 7, 8, 13])
yBounds =  array([0, 1])
Vals    =  array([[  1, 2, 1, 3, 4, 5]])

cBounds = [i+0.5 for i in arange(amax(Vals)+1)]

norm = mpl.colors.BoundaryNorm(cBounds, cmap.N)

c = ax1.pcolormesh(xBounds,yBounds,Vals,cmap=cmap,norm=norm)

ax1.set_xticks(xBounds[1:-1])
ax1.set_yticks([])
ax1.set_xlim(xBounds[0],xBounds[-1])
ax1.set_ylim(yBounds[0],yBounds[-1])

ax2 = fig.add_axes([0.9, 0.25, 0.05, 0.5])
colorbar(c,cax=ax2,ticks=arange(amax(Vals))+1)

rawDescription: Custom Colorbar-like plot with matplotlib


code:
import urllib2
import json
from twython import Twython

CONSUMER_KEY = 'XXXXXXXXXXXXXXXX'
CONSUMER_SECRET = 'XXXXXXXXXXXXXXXX'
ACCESS_KEY = 'XXXXXXXXXXXXXXXX'
ACCESS_SECRET = 'XXXXXXXXXXXXXXXX'

# get remote string
url = 'http://www.reddit.com/new.json?sort=new'
response=urllib2.urlopen(url)

# interpret as json
data = json.load(response)
#print(data)
response.close()

api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)

d = data['data']['children'][3]['data']
title = d['title']
permalink = d['permalink']
subreddit = d['subreddit']

api.update_status(status=title+permalink+subreddit) #or you can post this as different
#status, depends on how you'd like to format the tweet.

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


code: indices = {c: i for i, c in enumerate(thestring.split())}

rawDescription: Python: sort list of strings in order that they appear in another string


code:
from urllib.parse import urljoin
result_links = [urljoin(url, tag['href']) for tag in results]
pprint(result_links)

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

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


code:
#!/usr/bin/env python
import random
import time
import multiprocessing

def func(arg):
    time.sleep(random.random())
    return arg*10

def main():
    counter = 10
    args = "abc"
    pool = multiprocessing.Pool()
    for result in pool.imap_unordered(func, args):
        counter -= 1
        print("counter=%d, result=%r" % (counter, result))

if __name__ == "__main__":
    main()

rawDescription: Increment/decrement global variable using python multiprocessing module


code: matplotlib.use( 'Agg' )

rawDescription: Change permissions to allow PHP script in browser to execute matplotlib operations in a python script


code:
import gdal
import gdalconst

class BilFile(object):

    def __init__(self, bil_file):
        self.bil_file = bil_file
        self.hdr_file = bil_file.split('.')[0]+'.hdr'

    def get_array(self, mask=None):
        self.nodatavalue, self.data = None, None
        gdal.GetDriverByName('EHdr').Register()
        img = gdal.Open(self.bil_file, gdalconst.GA_ReadOnly)
        band = img.GetRasterBand(1)
        self.nodatavalue = band.GetNoDataValue()
        self.ncol = img.RasterXSize
        self.nrow = img.RasterYSize
        geotransform = img.GetGeoTransform()
        self.originX = geotransform[0]
        self.originY = geotransform[3]
        self.pixelWidth = geotransform[1]
        self.pixelHeight = geotransform[5]
        self.data = band.ReadAsArray()
        self.data = np.ma.masked_where(self.data==self.nodatavalue, self.data)
        if mask is not None:
            self.data = np.ma.masked_where(mask==True, self.data)
        return self.nodatavalue, self.data

rawDescription: Reading zipped ESRI BIL files with Python


code: name = fallBack(input("What is your name?"))

rawDescription: Python function to give default value for blank entry not working


code:
UL, UR = '╔', '╗'
SL, SR = '╠', '║'
DL, DR = '╚', '╝'
AL, AR = '═', '>'

def padded(
    line, info=None, width=42, intro='>', outro='<', filler='.', chopped='..'
):
    # cleanup input
    line = ''.join([' ', line.strip()]) if line else ''
    info = info.strip() if info else ''

    # determine available width
    width -= sum([len(intro), len(outro), len(line), len(info)])
    if width < 0:
        # chop off overflowing text
        line = line[:len(line)+width]
        if chopped:
            # place chopped characters (if set)
            chopped = chopped.strip()
            line = ' '.join([line[:len(line)-(len(chopped)+1)], chopped])

    return ''.join(e for e in [
        intro,
        info,
        line,
        ''.join(filler for _ in range(width)),
        outro
    ] if e)

def box(rnum, nbeds, *extras):
    arrow = (AL+AR)
    res = [
        # head line
        padded(
            'Stanza n. {:03d} <'.format(rnum), (AL+AL+arrow),
            intro=UL, outro=UR, filler=AL
        ),
        # first line
        padded(
            'Num letti: {:3d}'.format(nbeds), arrow,
            intro=SL, outro=SR, filler=' '
        ),
    ]
    # following lines
    res.extend(padded(e, arrow, intro=SL, outro=SR, filler=' ') for e in extras)
    # bottom line
    res.append(padded(None, None, intro=DL, outro=DR, filler=AL))

    return '\n'.join(res)

print(
    box(485, 3, 'Fumatori', 'Televisione')
)
print(
    box(123, 4, 'Fumatori', 'Televisione', 'Aria Condizionata')
)
print(
    box(1, 1, 'this is so much text it will be chopped off')
)

rawDescription: How to print framed strings

description: Print framed strings


rawDescription: Removing nth row in Pandas

description: Removing nth row in Pandas


code:
import numpy as np

def montage(imgarray, nrows=None, border=5, border_val=np.nan):
    """
    Returns an array of regularly spaced images in a regular grid, separated
    by a border

    imgarray:
        3D array of 2D images (n_images, rows, cols)
    nrows:
        the number of rows of images in the output array. if
        unspecified, nrows = ceil(sqrt(n_images))
    border:
        the border size separating images (px)
    border_val:
        the value of the border regions of the output array (np.nan
        renders as transparent with imshow)
    """

    dims = (imgarray.shape[0], imgarray.shape[1]+2*border,
        imgarray.shape[2] + 2*border)

    X = np.ones(dims, dtype=imgarray.dtype) * border_val
    X[:,border:-border,border:-border] = imgarray

    # array dims should be [imageno,r,c]
    count, m, n = X.shape

    if nrows != None:
        mm = nrows
        nn = int(np.ceil(count/nrows))
    else:
        mm = int(np.ceil(np.sqrt(count)))
        nn = mm

    M = np.ones((nn * n, mm * m)) * np.nan

    image_id = 0
    for j in xrange(mm):
        for k in xrange(nn):
            if image_id >= count:
                break
            sliceM, sliceN = j * m, k * n
            img = X[image_id,:, :].T
            M[sliceN:(sliceN + n), sliceM:(sliceM + m)] = img
            image_id += 1

    return np.flipud(np.rot90(M))

rawDescription: Algorithm to create a square matrix given any number of smaller square matrices


code:
from numpy import *

def points_in_circle(circle, arr):
    "A generator to return all points whose indices are within given circle."
    i0,j0,r = circle
    def intceil(x):
        return int(ceil(x))
    for i in xrange(intceil(i0-r),intceil(i0+r)):
        ri = sqrt(r**2-(i-i0)**2)
        for j in xrange(intceil(j0-ri),intceil(j0+ri)):
            yield arr[i][j]

rawDescription: Extract points within a shape from a raster


code:
l = []
entries = {}
queue = {}

for id, fid, title in t:
    entries[id] = entry = {'id': id, 'fid': fid, 'title': title}
    if id in queue:
        entry['sons'] = queue[id]
        del queue[id]
    if fid == -1:
        l.append(entry)
    elif fid in entries:
        parent = entries[fid]
        parent.setdefault('son', []).append(entry)
    else:
        queue.setdefault(fid, []).append(entry)

if queue:
    raise ValueError('No entries found for fid(s) {}'.format(queue.keys()))

rawDescription: how to change a tuple into dictionary tree in python

description: Change a tuple into dictionary tree in python


code:
while self.disabledControls:
    child = self.disabledControls.pop()
    if type(child) in [Button, ComboBox, CheckBox]:
        child.IsEnabled = True
    elif type(child) == TextBox:
        child.IsReadOnly = False

rawDescription: Set style for certain controls within window from contained usercontrol


code:
{'top_parent': {'child_one': None, 'child_two': {'grand_child': None}}}
{'top_parent': {'child_one': {}, 'child_two': {'grand_child': {}}}}
{'top_parent': {'child_one': None, 'child_two': {'grand_child': None}}}
{'top_parent': {'child_one': {}, 'child_two': {'grand_child': {}}}}

rawDescription: Build nested tree-like dict from an array of dicts with children


code:
set(s)
'a' in set(s)

rawDescription: How to determine whether a Pandas Column contains a particular value

description: Determine whether a Pandas Column contains a particular value


code:
in_file = 'reach.txt'
out_file = 'outreach.txt'

def clean(string):
    if not string:
        return string

    cleaned = []
    items = string.split()
    for item in items:
        if item.startswith('(') and item.endswith(')'):
            cleaned.append(item.strip('()'))
            break
    cleaned.append(items[-1])
    return ' '.join(cleaned)

with open(in_file) as i, open(out_file, 'w') as o:
    o.write('\n'.join([clean(line) for line in i]))

rawDescription: Python process text file with these criteria


rawDescription: what's faster: merging lists or dicts in python?

description: What's faster: merging lists or dicts in python


code:
request.query_string
from urllib import unquote
from flask import json
unquote(request.query_string.partition('&')[0])
json.loads(unquote(request.query_string.partition('&')[0]))

rawDescription: flask - how to get parameters from a JSON GET request

description: Flask - how to get parameters from a JSON GET request


rawDescription: Does Python copy references to objects when slicing a list?


code:
a
b
boolvec

rawDescription: Selecting columns in numpy based on a Boolean vector


code: data[:,0]  # assuming time is the first column

rawDescription: How to convert an array of dates (format 'mm/dd/yy HH:MM:SS') to numerics?

description: Convert an array of dates (format 'mm/dd/yy HH:MM:SS') to numerics


code: whos

rawDescription: numpy squeeze along an axis wont work

description: Numpy squeeze along an axis wont work


code:
from scipy.optimize import fsolve

x0 = 1.0  # Initial guess

sol = fsolve(myfunc2, x0, args=(3,))

rawDescription: Python find root for non-zero level

description: Python find root for non-zero level


rawDescription: Conditions with Numpy

description: Conditions with Numpy


code:
class Table(object):
    def __init__(self, xsize=1, ysize=1, zsize=1):
        self.data = numpy.zeros((xsize, ysize, zsize))

    def __getitem__(self, key):
        return self.data[key]

    def __setitem__(self, key, value):
        self.data[key] = value

    def resize(self, xsize=1, ysize=1, zsize=1):
        # This only works for increasing the size of the data,
        # but is easy do adapt to other cases
        newdata = numpy.zeros((xsize, ysize, zsize))
        shape = self.data.shape
        newdata[:shape[0], :shape[1], :shape[2]] = self.data
        self.data = newdata

rawDescription: increasing speed of python list operations and comparisons in a custom table class

description: Increasing speed of python list operations and comparisons in a custom table class


code: next(filter(matcher, lis)).split(';')

rawDescription: Fastest possible way to iterate through specific list in python


code:
for output_line in run_command('java -jar jarfile.jar'):
    print(output_line)

rawDescription: Running Jar files from Python

description: Running Jar files from Python


rawDescription: How can I find "week" in django's calendar app?

description: Find "week" in django's calendar app


code:
import matplotlib.pylab
import numpy as np

for q in range(1,10):
    # create a random, 100 length array
    s_A_approx = np.random.randint(0, 100, 100)
    # note I had to make q a string to avoid an AttributeError when
    # initializing the legend
    matplotlib.pylab.plot(s_A_approx, marker='.', linestyle='None', label=str(q))

matplotlib.pylab.legend(loc='upper left')
matplotlib.pylab.show()

rawDescription: Dynamically add legends to matplotlib plots in python


code:
print(str(lang))
print(str(port))

rawDescription: def function returning wrong value (python 2.7)

description: Def function returning wrong value (python 2.7)


code:
if evaluateBet(userInput) == True:
    points = ( points + (wager * 2) )
    wager = 0
    wins += 1
else:
    losses += 1

rawDescription: How do I make a score counter for my game in python?

description: Make a score counter for my game in python


rawDescription: Grammar rule extraction from parsed result


code:
value_I_want
value_I_want

rawDescription: Parsing XML in Python with ElementTree - findall


code:
if getattr(my_view, "name", None) == "User Profile View":
    ...

rawDescription: How to search a string with the url patterns in django?

description: Search a string with the url patterns in django


rawDescription: Displaying a floor division

description: Displaying a floor division


code: result = [list(item) for item in result]

rawDescription: generating a full combination of values from multiple lists in python?

description: Generating a full combination of values from multiple lists in python


code:
list1_clean, list2_clean = map(list, zip(*out))
list1_clean
list2_clean

rawDescription: List comprehension and logical indexing

description: List comprehension and logical indexing


code: print(dfrs)

rawDescription: Grouping pandas data frame by time intervals


code:
s = "# blah1\n# blah2\n# blah3\nCol1 Col2 Col3\na1 b1 c1\na2 b2 c2\n"
pd.read_table(StringIO(s), skiprows=3, sep=' ')

rawDescription: Delete rows containing particular pattern [Python/Pandas]


code:
if foods["Steak"] == "veg":
    print("Vegetarian food")
else:
    print("Not a vegetarian food")

rawDescription: How do I pick a string from a list and put it in a new list with the criteria

description: Pick a string from a list and put it in a new list with the criteria


code:
RcParams({u'axes.edgecolor': u'#bcbcbc',
          u'axes.facecolor': u'#eeeeee',
          u'axes.grid': True,
          u'axes.labelsize': u'large',
          u'axes.prop_cycle': cycler(u'color', [u'#348ABD', u'#A60628', u'#7A68A6', u'#467821', u'#D55E00', u'#CC79A7', u'#56B4E9', u'#009E73', u'#F0E442', u'#0072B2']),
          u'axes.titlesize': u'x-large',
          u'legend.fancybox': True,
          u'lines.linewidth': 2.0,
          u'mathtext.fontset': u'cm',
          u'patch.antialiased': True,
          u'patch.edgecolor': u'#eeeeee',
          u'patch.facecolor': u'blue',
          u'patch.linewidth': 0.5,
          u'text.hinting_factor': 8})

rawDescription: Get matplotlib color from style palette

description: Get matplotlib color from style palette


code: ls -1

rawDescription: Batch rename directories in reverse order


rawDescription: percentile rank in pandas in groups

description: Percentile rank in pandas in groups


code:
class MyTable(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1 = models.IntegerField(primary_key=True)
    key2 = models.IntegerField()

rawDescription: Composite primary key in django

description: Composite primary key in django


rawDescription: What is the easiest way to convert list with str into list with int?


code:
div = soup.find("div", id="test")
p = div.find_next_sibling("p")

rawDescription: BeautifulSoup consecutive blocks

description: BeautifulSoup consecutive blocks


code:
def verify_session(fn):
  def inner(*args,**kwargs):
    if not 'logged_in' in session:
        flash("You are not logged in.<br/>Please, log in to use our application.", "warning")
        return redirect(url_for('login_path'))
    return fn(*args,**kwargs)
  return inner

rawDescription: How do you break Python Flask controller flow when calling return inside a function?

description: Break Python Flask controller flow when calling return inside a function


code:
import re

def MyFunc(s, sub):
    return len(re.compile(re.escape(sub)).findall(s))

rawDescription: Improving Python function to count occurrences of a substring


code:
import random
x = [random.random() for i in range(50)]
y = [random.random() for i in range(50)]

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

fig2 = plt.figure()
ax2 = fig2.add_subplot(111)

ax1.scatter( x, y )
ax1.set_xlabel('X title')
ax1.set_ylabel('Y title')
fig1.savefig('myfig1.pdf')

ax2.hist( y )

rawDescription: Basic Pandas matplotlib plotting

description: Basic Pandas matplotlib plotting


code:
nose.run(argv=['nosetests','-v','-s','--with-xunit','--tc-file','./configFile'],
             plugins=[TestConfig(),Capture(),Xunit()])

rawDescription: python nose tests: specifying which node the test should be run in Selenium Grid

description: Python nose tests: specifying which node the test should be run in Selenium Grid


code: self.results = Entry(display, textvariable=numbers, width=31, fg="black", bg="snow", font="Verdana")

rawDescription: Binding number and operator buttons to calculator buttons


code:
class Car:
    def __init__(self, make, year):
        self.make = make
        self.year = year
    def __repr__(self):
        return 'Car({!r}, {!r})'.format(self.make, self.year)

Car('Toyota Camry', 2007)

rawDescription: Class object display 'class object at ...'


code:
import cgi
form = cgi.FieldStorage()
searchterm =  form.getvalue('searchbox')

rawDescription: Posting html form values to python script


code:
#__init__.py
app = Flask(__name__)
app.config.from_object('settings')
app.config.from_envvar('MYCOOLAPP_CONFIG',silent=True)

rawDescription: Flask: How to manage different environment databases?


code:
import sys

spliced = False
if '-s' in sys.argv:
    spliced = True
    sys.argv.remove('-s')
infile, outfile = sys.argv[1:]

rawDescription: Optional Parameter Python?

description: Optional Parameter Python


code:
mean = lambda x: sum(x)/float(len(x)) #or `from statistics import mean` in python3.4
output = [foo(r) if isinstance(r, int) else mean(map(foo, r)) for r in data]

rawDescription: Check for multidimensional list in Python


code:
p = re.compile(r'^something/(?P<id1>\d+)/(?P<id2>\d+)/(?:(?P<id3>\d+)/)?(?:(?P<id4>\d+)/)?$')
p.match('something/1/2/3/4/').groups()
p.match('something/1/2/3/4').groups()
p.match('something/1/2/3/').groups()
p.match('something/1/2/3').groups()
p.match('something/1/2/').groups()

rawDescription: Passing 4 digits to view

description: Passing 4 digits to view


code:
def get_login(self, realm, username, may_save):

    # ...other code omitted...

    gtk.gdk.threads_enter()
    dialog = rabbitvcs.ui.dialog.Authentication(
        realm,
        may_save
    )
    result = dialog.run()
    gtk.gdk.threads_leave()

    return result

rawDescription: Requesting information from the user inside a GTK main loop


code:
# implicit root logger with loglevel WARNING

# both child-logger: loglevel NOTSET
logger = logging.getLogger('file')
hipchat_logger = logging.getLogger('hipchat')

# ...create and add file handler...

# change 'file'-loglevel to DEBUG
logger.setLevel(logging.DEBUG)

# ...create hipchat handler...

# change loglevel of the handler(!) to DEBUG.
# 'hipchat'-loglevel is still NOTSET
hipchat_handler.setLevel(logging.DEBUG)

# ...add hipchat handler ...

# logger -> loglevel DEBUG -> INFO gets logged.
logger.info("Hi, this is a test. I should not see this in Hipchat")

# hipchat_logger -> loglevel NOTSET -> delegate to root-logger
# root-logger -> loglevel WARNING -> INFO not logged (being below threshold)
hipchat_logger.info("Hi, display me in Hipchat")

rawDescription: Not able to log to two different places using Python logging module


code: result = var1 if var1 is not None and var1 is not False else var2

rawDescription: When zero is not None or not False but digit 0


code: dict([(x, 3) for x in [_id, _if, _while, _lbrace, _println]] + [(_variable, 2)])

rawDescription: Pythonic way to write create dictionary from dict comprehension, + something else


code: collection1.find({'albums': {'$in': [3, 7, 8]}})

rawDescription: pymongo: how to use $or operator to an column that is an array?

description: Pymongo: how to use $or operator to an column that is an array


code:
from collections import namedtuple
XYZ = namedtuple('XYZ', ['x', 'y', 'z'])
def location():
    return XYZ(5, 0, 0)
location().x

rawDescription: Return different value from function depending on suffix


code: 'function(a, b, c, d)'

rawDescription: Formatting a data structure into a comma-separated list of arguments


code:
from itertools import islice, permutations
from timeit import timeit
def list_index():
    return list(permutations(range(10)))[999999]

def for_loop():
    p = permutations(range(10))
    for i in xrange(999999): p.next()
    return p.next()

def enumerate_loop():
    p = permutations(range(10))
    for i, element in enumerate(p):
        if i == 999999:
            return element

def islice_next():
    return next(islice(permutations(range(10)), 999999, 1000000))

timeit('f()', 'from __main__ import list_index as f', number=10)
timeit('f()', 'from __main__ import for_loop as f', number=10)
timeit('f()', 'from __main__ import enumerate_loop as f', number=10)
timeit('f()', 'from __main__ import islice_next as f', number=10)

rawDescription: Elegant way to skip elements in an iterable


code: np.argmax(np.max(x, axis=0))

rawDescription: find row or column containing maximum value in numpy array

description: Find row or column containing maximum value in numpy array


code:
subset = pos_coordinates[3:9]
average = float(sum(subset))/len(subset)

rawDescription: How do i get the average of three pos_coordinates values?

description: Get the average of three pos_coordinates values


code:
from Carbon import File
def osx_realpath (path):
    return File.FSResolveAliasFile(path, True)[0].as_pathname()

rawDescription: Python: Check if a directory is an alias


code: filter(lambda x: searchLetter in x, hulkLine)

rawDescription: Write a function named containsLetter that identifies all of the strings in a list that contain a specified letter and returns a list of those strings


code:
def classify_func(X, Y):
    return np.round(abs(X+Y)).astype('int')

def prob_func(X,Y):
    return 1 - 2*abs(abs(X+Y)-classify_func(X,Y))

rawDescription: How to create colormap of confidence estimates for k-Nearest Neighbor Classification

description: Create colormap of confidence estimates for k-Nearest Neighbor Classification


code:
import gmpy2

def prime_numbers(limit=1000000):
    '''Prime number generator. Yields the series
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ...
    using Sieve of Eratosthenes.
    '''
    yield 2
    sub_limit = int(limit**0.5)
    # Actual number is 2*bit_position + 1.
    oddnums = gmpy2.xmpz(1)
    current = 0
    while True:
        current += 1
        current = oddnums.bit_scan0(current)
        prime = 2 * current + 1
        if prime > limit:
            break
        yield prime
        # Exclude further multiples of the current prime number
        if prime <= sub_limit:
            for j in range(2*current*(current+1), limit>>1, prime):
                oddnums.bit_set(j)

rawDescription: Speed up bitstring/bit operations in Python?


code:
def save_file(filename, new_list):
    with open(filename, 'w') as f:
        for line in new_list:
            f.write(line)

rawDescription: Python, adding a file into another file

description: Python, adding a file into another file


code: newdict = {k:olddict[k] for k in goodkeys}

rawDescription: Remove a dictionary key if it is a substring in any other key


rawDescription: Python doesn't parse Serial data to an array


rawDescription: How to call a function which returns multiple values

description: Call a function which returns multiple values


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

rawDescription: Numerical integration Loop Python

description: Numerical integration Loop Python


code:
# structure returned by get_metadata function.
MetaDataTuple = collections.namedtuple("MetaDataTuple",
        "coltype, colname, default, m2m, nullable, uselist, collection")

def get_metadata_iterator(class_):
    for prop in class_mapper(class_).iterate_properties:
        name = prop.key
        if name.startswith("_") or name == "id" or name.endswith("_id"):
            continue
        md = _get_column_metadata(prop)
        if md is None:
            continue
        yield md

def get_column_metadata(class_, colname):
    prop = class_mapper(class_).get_property(colname)
    md = _get_column_metadata(prop)
    if md is None:
        raise ValueError("Not a column name: %r." % (colname,))
    return md

def _get_column_metadata(prop):
    name = prop.key
    m2m = False
    default = None
    nullable = None
    uselist = False
    collection = None
    proptype = type(prop)
    if proptype is ColumnProperty:
        coltype = type(prop.columns[0].type).__name__
        try:
            default = prop.columns[0].default
        except AttributeError:
            default = None
        else:
            if default is not None:
                default = default.arg(None)
        nullable = prop.columns[0].nullable
    elif proptype is RelationshipProperty:
        coltype = RelationshipProperty.__name__
        m2m = prop.secondary is not None
        nullable = prop.local_side[0].nullable
        uselist = prop.uselist
        if prop.collection_class is not None:
            collection = type(prop.collection_class()).__name__
        else:
            collection = "list"
    else:
        return None
    return MetaDataTuple(coltype, str(name), default, m2m, nullable, uselist, collection)

def get_metadata(class_):
    """Returns a list of MetaDataTuple structures.
    """
    return list(get_metadata_iterator(class_))

def get_metadata_map(class_):
    rv = {}
    for metadata in get_metadata_iterator(class_):
        rv[metadata.colname] = metadata
    return rv

rawDescription: Get the relationship metadata from sqlalchemy


code: 'green' in tag['class']

rawDescription: Beautiful soup queries

description: Beautiful soup queries


code:
True == 1
False == 0

rawDescription: python pandas/numpy True/False to 1/0 mapping

description: Python pandas/numpy True/False to 1/0 mapping


code: map(lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%dT%H:%M:%S.%fZ'), data)

rawDescription: time.strptime got TypeError: function takes at most 8 arguments (9 given)

description: Time.strptime got TypeError: function takes at most 8 arguments (9 given)


code:
def inc(value, *args):
    for i in args:
        yield i+value

rawDescription: Multiple increment operators on the same line Python


code:
seen = set()

def allEvenDigits(numb): # This is the issue one
    return all( int(n)%2 == 0 for n in str(numb))

for i in range(1, 1000): # its 1000 to save a few minutes
    revNumb = reversed(i);
    total = revNumb+i;

    if i not in seen and revNumb not in seen:
        if (allEvenDigits(total)):
            print(i, "+" , revNumb, "=",total);
            seen.add(i)
            seen.add(revNumb)

rawDescription: Python: Project Euler 145

description: Python: Project Euler 145


code:
pos_count = pos_count.reindex(total_count.index, fill_value=0)
for col in pos_count:
    pos_count[col] = (pos_count[col] == total_count).astype(int)
pos_count = pos_count.reindex(sd.index, fill_value=0)
# Position  Contractor  President
# 0                  1          1
# 1                  1          0
# 2                  0          0
# 3                  0          0
# 4                  0          1
# 5                  1          1

rawDescription: Pandas Create Columns From Rows in Other Data Frame with Criteria


code: ['Maurice is smart', 'Maurice is dumb']

rawDescription: Save list items to a new list if the item contains specific substring


code:
def return_path(item_id):
    path = []
    # pad with zeros, grab only the last 6 digits
    str_id = format(item_id, '06d')[-6:]
    # any extra zero pairs at the start are in the path first
    while str_id.startswith('00'):
        path.append('00')
        str_id = str_id[2:]
    # for an odd number of padding zeros, swap out the 0 to the last digit
    if str_id[0] == '0':
        str_id = str_id[1:-1] + '0' + str_id[-1:]
    # grab digits in pairs starting at the end
    path += [str_id[i:i + 2] for i in range(len(str_id) - 2, -1, -2)]
    path.append(str(item_id))
    return os.path.join(*path)

rawDescription: splitting and merging the string in python

description: Splitting and merging the string in python


rawDescription: What is the complexity of the hash function sha1


code:
acceptable = set()
#...
acceptable = set(i for i in acceptable
                 if is_rank_x_top_100(i) and is_rank_y_top_10(i))

rawDescription: set(filter) repetition

description: Set(filter) repetition


code:
# get club links on each of the pagination pages
def parse_club(self, response):
    # loop through each of the rows
    for sel in response.xpath('//table/tbody/tr'):
        item = rankingItem()
        item['name'] = sel.xpath('td/a/div[@class="limittext"]/text()').extract()

        # get more club information
        club_href = sel.xpath('td[2]/a[1]/@href').extract_first()
        club_url = response.urljoin(club_href)
        request = scrapy.Request(club_url,callback=self.parse_club_page_2)

        request.meta['item'] = item
        yield request  # FIX HERE

rawDescription: Multi-page scrapy yielding my items too quickly to finish - functions not chaining and waiting for completion


rawDescription: comparing ndarray with values in 1D array to get a mask

description: Comparing ndarray with values in 1D array to get a mask


code:
import requests

from bs4 import BeautifulSoup

h = {"X-MicrosoftAjax": "Delta = true",
     "X-Requested-With": "XMLHttpRequest",
     "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"
     }
"ctl00$ctl13 | ctl00$MainContent$physicianSearchView$btnSearch"
d = {
    "ctl00$ctl13": "ctl00$MainContent$physicianSearchView$btnSearch",
    "__EVENTTARGET": "ctl00$MainContent$physicianSearchView$btnSearch",
    'ctl00$MainContent$physicianSearchView$hfPrefetchUrl': "http://service.cpsa.ca/OnlineService/OnlineService.svc/Services/GetAlbertaCities?name=",
    'ctl00$MainContent$physicianSearchView$hfRemoveUrl': "http://service.cpsa.ca/OnlineService/OnlineService.svc/Services/GetAlbertaCities?name=%QUERY",
    '__ASYNCPOST': 'true'}

nxt_d = {
    "ctl00$ctl13": "ctl00$MainContent$physicianSearchView$ResultsPanel|ctl00$MainContent$physicianSearchView$gvResults$ctl14$ddlPager",
    "ctl00$MainContent$physicianSearchView$gvResults$ctl01$ddlPager": "2",
    "ctl00$MainContent$physicianSearchView$gvResults$ctl14$ddlPager": "1",
    "__ASYNCPOST": "true",
    "__EVENTTARGET": "ctl00$MainContent$physicianSearchView$gvResults$ctl14$ddlPager"}

url = "http://search.cpsa.ca/PhysicianSearch"
with requests.session() as s:
    r = s.get(url, headers=h)
    soup = BeautifulSoup(r.content, "lxml")
    ev = soup.select("#__EVENTVALIDATION")[0]["value"]
    vs = soup.select("#__VIEWSTATE")[0]["value"]
    d["__EVENTVALIDATION"] = ev
    d["__VIEWSTATE"] = vs
    r = s.post(url, data=d, headers=h)
    soup = BeautifulSoup(s.get("http://search.cpsa.ca/PhysicianSearch").content, "lxml")
    ev = soup.select("#__EVENTVALIDATION")[0]["value"]
    vs = soup.select("#__VIEWSTATE")[0]["value"]
    nxt_d["__EVENTVALIDATION"] = ev
    nxt_d["__VIEWSTATE"] = vs
    r = s.post(url, data=nxt_d, headers=h)

rawDescription: Making subsequent POST request in session doesn't work - web scraping


rawDescription: Create pandas dataframe from nested dict with outer keys as df index and inner keys column headers


rawDescription: Python - one result from a list

description: Python - one result from a list


code:
def find_closest_ancestor(widget, ancestor_class):
    if not isinstance(widget, gtk.Widget):
        raise TypeError("%r is not a gtk.Widget" % widget)
    ancestor = widget.get_parent()
    while ancestor is not None:
        if isinstance(ancestor, ancestor_class):
            break;
        ancestor = ancestor.get_parent() if hasattr(ancestor, 'get_parent') and callable(ancestor.get_parent) else None
    return ancestor

rawDescription: PyGTK Entry widget in TreeViewColumn header


code:
RefCycle()
import gc
gc.collect()

rawDescription: How many times the finalizer method is called and zombies (PEP 442)


rawDescription: python for loop using lambda syntax

description: Python for loop using lambda syntax


code:
from re import findall
mystr = """
{"object" "rectangle" "param1" {"Type1" "Type2"} "param2" {{0.0 0.64} {0.08 0.72}} "smth" 0 "point1" 0 "point2" }
"""
findall("-?\d+\.\d+", mystr)
var1, var2, var3, var4 = findall("-?\d+\.\d+", mystr)
var1
var4

rawDescription: Collecting the numbers from a string in python


code: myobj[5] = 1

rawDescription: How to override [] operator

description: Override [] operator


code:
import wx
import p

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Checking Menubar from external Panel")

        sizer = wx.BoxSizer(wx.VERTICAL)

        mainPanel = p.MyPanel(parent=self)
        sizer.Add(mainPanel, 1, wx.EXPAND)
        self.SetSizer(sizer)

        self.Show()

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

rawDescription: wxpython setting frame menubar from panel

description: Wxpython setting frame menubar from panel


rawDescription: Using Python to Decode Steganography Images (example images at Wikipedia)


rawDescription: How to find number of instances of an item in a python list

description: Find number of instances of an item in a python list


rawDescription: For loop position in csv reader_Python

description: For loop position in csv reader_Python


rawDescription: Unicode strings in tornado web app

description: Unicode strings in tornado web app


code:
result =[[1,'stu1','grade A'],[2,'stu2','grade B']]
title = ('id', 'name', 'grade')
map(lambda x: dict(zip(title, x)), result)

rawDescription: How can i append database table column name as key to a list to convert it as dict

description: Append database table column name as key to a list to convert it as dict


rawDescription: Fast math operations on an array in python


code: ['Bonds', 'Susann ("Sun") Margreth Branco', 'Montreal', 'Quebec', 'August', 'They', 'Las Vegas', 'Nevada', 'Barry Bonds']

rawDescription: How to include special part in regex to find English names using python re.findall?

description: Include special part in regex to find English names using python re.findall


code:
for arg in len(sys.argv):
    filename = arg.split('/')[-1].strip('.fits')
    t = sex(arg, filename +'_star_catalog.fits')
    # Whatever else

rawDescription: running python code, to use sextractor with more than one image file

description: Running python code, to use sextractor with more than one image file


code:
def countOdd(l):
    return fold(lambda x,y: x+(y&1),l,0)

def fold(f,l,a):
    if l == list(): return a
    return fold(f,l[1:],f(a,l[0]))

rawDescription: counting odd numbers in a list python

description: Counting odd numbers in a list python


code:
def alle_parents(knoten, parents = None):
    parents = parents or []

rawDescription: Pathfinding code produces unexpected results


code:
from sqlalchemy import create_engine
engine = create_engine("postgresql://u:p@host/database")

rawDescription: List database tables with SQLAlchemy

description: List database tables with SQLAlchemy


code:
def read_file(filename):
  return open(filename).read()

rawDescription: Edit text in file in python

description: Edit text in file in python


code:
def power_law(x, a, b, c1, c2):
    l = len(x_data_one)
    return a * np.hstack([x[:l] + c1, x[l:] + c2]) ** b

x_data_one_two = np.hstack([x_data_one,x_data_two])
y_data_one_two = np.hstack([y_data_one,y_data_two])

(a_one, b_one, c_one, c_two), _ = curve_fit(power_law, x_data_one_two, y_data_one_two)

rawDescription: How to fit datasets so that they share some (but not all) parameter values

description: Fit datasets so that they share some (but not all) parameter values


code:
class SimpleList(collections.MutableSequence):
    def __init__(self, collection):
        super(SimpleList, self).__init__(collection)
        for e in collection:
            e.registerPropertyChangeObserver(self)

    def simpleObjectPropertyChanged(self, simpleObject):
        pass # react to simpleObject.property being changed

rawDescription: Is it possible to monitor a list (or mutable sequence) for when a member of the list is modified?


rawDescription: Concatenating keys in nested dictionary

description: Concatenating keys in nested dictionary


code:
from datetime import datetime, timedelta, date
def subtract_from_date(date, time_unit, num):
    return date - timedelta(**{time_unit: num})

subtract_from_date(date.today(), 'days', 5)

rawDescription: Pass time unit as a variable to the keyword argument in time delta function.


code:
vals = df.groupby(lambda x: (x.year, x.month)).sum()
vals

rawDescription: Pandas groupby year object plotting it year over year


code:
from multiprocessing import Pool, Manager
from Queue import Empty
import time

ff_tests = [1,2,3,4,5]
chrome_tests = [10, 11, 12, 13, 14, 15]
general_tests = [20, 21,22, 23,24,25]

def process_func(spec_queue, general_queue, browser):
    while True:
        try:
            test = spec_queue.get_nowait()
            print("Processing {} in {} process".format(test, browser))
            time.sleep(2)
        except Empty:
            break

    while True:
        try:
            test = general_queue.get_nowait()
            print("Processing {} in {} process".format(test, browser))
            time.sleep(2)
        except Empty:
            break

if __name__ == "__main__":
    m = Manager()
    ff_queue = m.Queue()
    chrome_queue = m.Queue()
    general_queue = m.Queue()

    for queue, tests in [(ff_queue, ff_tests), (chrome_queue, chrome_tests),
                         (general_queue, general_tests)]:
        for test in tests:
            queue.put(test)

    pool = Pool(8)
    for _ in range(4):
        pool.apply_async(process_func, args=(ff_queue, general_queue, "firefox"))
        pool.apply_async(process_func, args=(chrome_queue, general_queue, "chrome"))
    pool.close()
    pool.join()

rawDescription: How it to implement custom multiprocessing continuous (async) control in python?


code: {{ favorits|list_replace('|', '\|')|join(' | ')}}

rawDescription: jinja2 escape joined character in joinee

description: Jinja2 escape joined character in joinee


code:
import wx
from enum import Enum

from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub

import logging

#####
#   The control events that the Controller can process
#   Usually this would be in a module imported by each of M, V and C
#   These are the possible values for the "event" parameter of an APP_EVENT message

class AppEvents(Enum):
    APP_EXIT = 0
    APP_ADD_WORKPLACE = 1
    APP_ADD_CUSTOMER = 2
    CUSTOMER_DEPOSIT = 3
    CUSTOMER_WITHDRAWAL = 4
    CUSTOMER_EARN = 5
    PERSON_WORK = 6
    EARN_REVENUE = 7

#################
#
#   View
#

class MainWindow(wx.Frame):

    def __init__(self,  title):
        wx.Frame.__init__(self, None, -1, title)

        self._log = logging.getLogger("MVC Logger")
        self._log.info("MVC View - separate workspace: starting...")

        self._bankStatusDisplay = None
        self._customerUIs = {}
        self._workplaceUIs = {}

        # this is where we will put display elements - it's up to the controller to add them
        self._sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.SetSizer(self._sizer)

        # but we do need one button immediately...
        add_workplace_button = wx.Button(self, label="Add Workplace")
        self._sizer.Add(add_workplace_button)
        self._sizer.Layout()

        self.Bind(wx.EVT_BUTTON, self._OnAddWorkplaceClick, add_workplace_button)

        # These are the events that cause us to update our display
        pub.subscribe(self._OnCustomerBalanceChange, "CUSTOMER_BALANCE_EVENT")
        pub.subscribe(self._OnBankBalanceChange, "BANK_BALANCE_EVENT")

        self.Show()

    def _OnAddWorkplaceClick(self, event):
        pub.sendMessage("APP_EVENT", event = AppEvents.APP_ADD_WORKPLACE)

    def AddWorkplace(self, workplace):
        self._workplaceUIs[workplace.name] = the_ui = WorkplaceInterface(self, workplace)
        self._sizer.Add(the_ui)
        self._sizer.Layout()

    def AddBank(self, bank):
        if not(self._bankStatusDisplay):
            self._bankStatusDisplay = BankStatusDisplay(self, bank)
            self._sizer.Add(self._bankStatusDisplay)
            self._sizer.Layout()
        else:
            raise Exception("We can only handle one bank at the moment")

    def AddCustomer(self, customer):
        self._customerUIs[customer.name] = the_ui = CustomerInterface(self, customer)
        self._sizer.Add(the_ui)
        self._sizer.Layout()

    def _OnCustomerBalanceChange(self, value):
        customer = value
        self._customerUIs[customer.name].UpdateBalance()

    def _OnBankBalanceChange(self):
        self._bankStatusDisplay.Update()

class BankStatusDisplay(wx.Panel):
    def __init__(self, parent, bank):
        wx.Panel.__init__(self, parent, style = wx.RAISED_BORDER)

        self._bank = bank

        sizer = wx.BoxSizer(wx.VERTICAL)
        label = wx.StaticText(self, label="Bank Funds")

        balance_display = wx.TextCtrl(self)
        balance_display.SetEditable(False)
        balance_display.SetValue('$' + str(bank.Funds()))

        sizer.Add(label, 0, wx.EXPAND | wx.ALL)
        sizer.Add(balance_display, 0, wx.EXPAND | wx.ALL)

        self.SetSizer(sizer)

        self._balanceDisplay = balance_display

    def Update(self):
        self._balanceDisplay.SetValue('$' + str(self._bank.Funds()))

class CustomerInterface(wx.Panel):
    def __init__(self, parent, customer):
        wx.Panel.__init__(self, parent, style = wx.RAISED_BORDER)

        self._customer = customer
        self._standardTransaction = 5 # how much customers try to deposit and withdraw

        sizer = wx.BoxSizer(wx.VERTICAL)
        label = wx.StaticText(self, label=customer.name)

        self._balanceDisplay = wx.TextCtrl(self)
        self._balanceDisplay.SetEditable(False)
        self._balanceDisplay.SetValue('$' + str(customer.CashInHand()))

        deposit_button = wx.Button(self, label="Deposit $" + str(self._standardTransaction))
        withdraw_button = wx.Button(self, label="Withdraw $" + str(self._standardTransaction))
        earn_button = wx.Button(self, label="Earn Money")

        sizer.Add(label, 0, wx.EXPAND | wx.ALL)
        sizer.Add(self._balanceDisplay, 0, wx.EXPAND | wx.ALL)

        sizer.Add(deposit_button, 0, wx.EXPAND | wx.ALL)
        sizer.Add(withdraw_button, 0, wx.EXPAND | wx.ALL)
        sizer.Add(earn_button, 0, wx.EXPAND | wx.ALL)

        self.Bind(wx.EVT_BUTTON, self._OnDepositClick, deposit_button)
        self.Bind(wx.EVT_BUTTON, self._OnWithdrawClick, withdraw_button)
        self.Bind(wx.EVT_BUTTON, self._OnEarnClick, earn_button)

        self.SetSizer(sizer)
        self.Show()

    def _OnDepositClick(self, event):
        pub.sendMessage("APP_EVENT", event = AppEvents.CUSTOMER_DEPOSIT, value = (self._customer, self._standardTransaction))

    def _OnWithdrawClick(self, event):
        pub.sendMessage("APP_EVENT", event = AppEvents.CUSTOMER_WITHDRAWAL, value = (self._customer, self._standardTransaction))

    def _OnEarnClick(self, event):
        pub.sendMessage("APP_EVENT", event = AppEvents.CUSTOMER_EARN, value = self._customer)

    def UpdateBalance(self):
        self._balanceDisplay.SetValue('$' + str(self._customer.CashInHand()))

class WorkplaceInterface(wx.Panel):
    def __init__(self, parent, workplace):
        wx.Panel.__init__(self, parent, style = wx.RAISED_BORDER)

        self._workplace = workplace

        sizer = wx.BoxSizer(wx.VERTICAL)
        label = wx.StaticText(self, label="Workplace Funds")

        self._balanceDisplay = wx.TextCtrl(self)
        self._balanceDisplay.SetEditable(False)
        self._balanceDisplay.SetValue('$' + str(workplace.Funds()))

        revenue_button = wx.Button(self, label="Earn Revenue")

        sizer.Add(label, 0, wx.EXPAND | wx.ALL)
        sizer.Add(self._balanceDisplay, 0, wx.EXPAND | wx.ALL)

        sizer.Add(revenue_button, 0, wx.EXPAND | wx.ALL)

        self.SetSizer(sizer)
        self.Show()

        self.Bind(wx.EVT_BUTTON, self._OnRevenueClick, revenue_button)

        pub.subscribe(self._OnBalanceChange, "WORKPLACE_BALANCE_EVENT")

    def _OnRevenueClick(self, event):
        pub.sendMessage("APP_EVENT", event = AppEvents.EARN_REVENUE, value = (self._workplace))

    def _OnBalanceChange(self):
        self._balanceDisplay.SetValue('$' + str(self._workplace.Funds()))

rawDescription: How to keep the controller alive

description: Keep the controller alive


code:
v1 = RaspberryThread(function = shoppingcart)
v2 = RaspberryThread(function = dodgeballs)

v1.start()
v2.start()

rawDescription: Killing or stopping an active thread

description: Killing or stopping an active thread


code:
df = DataFrame('10.0%',index=range(100),columns=range(10))
df.replace('%','',regex=True).astype('float')/100

rawDescription: pandas convert strings to float for multiple columns in dataframe

description: Pandas convert strings to float for multiple columns in dataframe


code:
form = PostForm()
form.fill_tags([tag.name for tag in post.tags.all()])

rawDescription: How to send query results to a WTForm Field?

description: Send query results to a WTForm Field


code:
class Foo(NamedModel):
    KEY_NAME = '%(name)s'
    name = db.StringProperty()

rawDescription: Custom keys for Google App Engine models (Python)


code:
instance = Demo()
instance.class_method()
instance.static_method()
instance.instance_method()

rawDescription: Is it possible to import class method without instantiating class?


code:
import graphlab as gl
import datetime as dt
sf = gl.SFrame({'a':[1,2,3]})
sf['a'] = sf['a'].astype(dt.datetime)

rawDescription: How to convert date from unix timestamps to human readable format in graphlab (python 2.7)

description: Convert date from unix timestamps to human readable format in graphlab (python 2.7)


code:
pixmap = QPixmap.grabWidget(self.canvas)
pixmap.save('test.png')

rawDescription: Python - matplotlib - PyQT: Copy image to clipboard


code:
def setup():
    import random
    global a_list
    a_list = [random.randrange(100) for _ in xrange(SZ)]

def lambda_test():
    global a_list
    sorted(range(len(a_list)), key=lambda i:a_list[i])

def foo(indexable):
    return functools.partial(operator.__getitem__, indexable)

def foo_test():
    global a_list
    sorted(range(len(a_list)), key=foo(a_list))

def foo2(indexable):
    return indexable.__getitem__

def foo2_test():
    global a_list
    sorted(range(len(a_list)), key=foo2(a_list))

rawDescription: Inverse of `operator.itemgetter`

description: Inverse of `operator.itemgetter`


code:
@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
    if not values:
        return
    g.lang_code = values.pop('lang_code', None)
    for key, value in values.items():
        if key.startswith('_'):
            values.pop(key)

class TranslateCorrelationRule(Rule):

    def _update_translate_values(self, values):
        lang_code = values.get('lang_code', getattr(g, 'lang_code', None))
        if lang_code is None:
            return values
        values = values.copy()
        for argument in self.arguments:
            if argument in values:
                continue
            converter = self._converters[argument]
            if not isinstance(converter, TranslateConverter):
                continue
            values[argument] = converter.language_pairs[lang_code]
        return values

    def suitable_for(self, values, method=None):
        return Rule.suitable_for(self, self._update_translate_values(values),
                                 method)

    def build(self, values, append_unknown=True):
        return Rule.build(self, self._update_translate_values(values),
                          append_unknown)

rawDescription: Format canonical URL structure correctly with URL Processors


code:
if "DATABASE_URL" in os.environ:
        urlparse.uses_netloc.append("postgres")
        url = urlparse.urlparse(os.environ.get("DATABASE_URL"))
        DATABASE = {
             "database" : url.path[1:],
             "user" : url.username,
             "password": url.password,
             "host": url.hostname,
             "port": url.port
               }
        return PostgresqlDatabase(**DATABASE)

rawDescription: How to install app on heroku with postgres

description: Install app on heroku with postgres


code: scrollb = tki.Scrollbar(..., command=txt.yview)

rawDescription: How to attach a Scrollbar to a Text widget?

description: Attach a Scrollbar to a Text widget


code:
def fn(self):
    return self

class A(object):
    fn = fn

class B(object):
    fn = fn

rawDescription: Python Method object creation

description: Python Method object creation


rawDescription: difficulty with search url in django

description: Difficulty with search url in django


rawDescription: Checking if ranges cross paths

description: Checking if ranges cross paths


code:
from yourmodule import MyAPI

api = MyAPI

filtered_timetable = api.filter_on(something)

rawDescription: Optionally use decorators on class methods


code:
database_instance = Database()
database_instance.connect()

Database.connect()

rawDescription: Confusion over how to share and modify class level data between instances.


rawDescription: Counting the Frequency a Value appears in a given "set" within a DF


code:
from itertools import compress
arr = range(1,10)
mask = [1]*len(arr)
mask[5]=0
list(compress(arr,mask))

rawDescription: Index all *except* one item in python

description: Index all *except* one item in python


code:
class Bullet2:
    def __init__(self, image):
        self.image = image

rawDescription: Python class attributes usage and initialization


rawDescription: Turning Printed Answers into a List

description: Turning Printed Answers into a List


code:
someClass = SomeClass()
someClass.start()
somethingThread = threading.Thread(target=someClass.doSomething)
somethingThread.start()
doOtherImportantStuffWithSomethingIsHappening()
somethingThread.join()

rawDescription: How to call a function on a running Python thread

description: Call a function on a running Python thread


code:
def ols_res(df, xcols,  ycol):
    return pd.DataFrame({xcol : sm.OLS(df[ycol], df[xcol]).fit().predict() for xcol in xcols})

rawDescription: Python pandas: how to run multiple univariate regression by group


code:
with open('C:\\middlelist3.txt') as datafile:
    list = (line.split(',', 1)[0] for line in datafile)
    with open('C:\\nocommas.txt', 'w') as smallfile:
        smallfile.writelines(list)

rawDescription: Need to delete part of text lines in python


code:
[
{'company': {'employee': {'age': 20, 'name': 'john', 'others': {'grade': 'star'}}}},
{'company': {'employee': {'age': 20, 'name': 'noname', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': 20, 'name': 'noname', 'others': {'grade': 'star'}}}},
{'company': {'employee': {'age': 200, 'name': 'john', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': 200, 'name': 'john', 'others': {'grade': 'star'}}}},
{'company': {'employee': {'age': 200, 'name': 'noname', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': 200, 'name': 'noname', 'others': {'grade': 'star'}}}}
]

rawDescription: Generate all combinations from a nested python dictionary and segregate them


rawDescription: pandas get index for a row value

description: Pandas get index for a row value


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

# Remove the middle 40% of the RdBu_r colormap
interval = np.hstack([np.linspace(0, 0.3), np.linspace(0.7, 1)])
colors = plt.cm.RdBu_r(interval)
cmap = LinearSegmentedColormap.from_list('name', colors)

# Plot a comparison of the two colormaps
fig, axes = plt.subplots(ncols=2)
data = np.random.random((10, 10))

im = axes[0].imshow(data, cmap=plt.cm.RdBu_r, vmin=0, vmax=1)
fig.colorbar(im, ax=axes[0], orientation='horizontal', ticks=[0, 0.5, 1])
axes[0].set(title='Original Colormap')

im = axes[1].imshow(data, cmap=cmap, vmin=0, vmax=1)
fig.colorbar(im, ax=axes[1], orientation='horizontal', ticks=[0, 0.5, 1])
axes[1].set(title='New Colormap')

plt.show()

rawDescription: Remove a section of a colormap

description: Remove a section of a colormap


code: B[X.ravel()] = A.ravel()

rawDescription: Efficient way of getting a subarray of an array that the indices are mapped


code:
from heapq import merge # merge has key parameter in Python 3.5

def inner_join(a, b):
    key = itemgetter(0)
    a.sort(key=key)
    b.sort(key=key)
    for _, group in groupby(merge(a, b, key=key), key):
        row_a, row_b = next(group), next(group, None)
        if row_b is not None: # join
            yield row_a + row_b[1:] # cut 1st column from 2nd row

rawDescription: How do I merge two lists of tuples based on a key?

description: Merge two lists of tuples based on a key


code:
import urllib2
from bs4 import BeautifulSoup
html = urllib2.urlopen( "http://www.google.com" ).read()
soup = BeautifulSoup( html )

rawDescription: Using Beautifulsoup and Urllib2 in Python, how can I find the data surrounded by specific tags?


code:
import png

import numpy as np

# The following import is just for creating an interesting array
# of data.  It is not necessary for writing a PNG file with PyPNG.
from scipy.ndimage import gaussian_filter

# Make an image in a numpy array for this demonstration.
nrows = 240
ncols = 320
np.random.seed(12345)
x = np.random.randn(nrows, ncols, 3)

# y is our floating point demonstration data.
y = gaussian_filter(x, (16, 16, 0))

# Convert y to 16 bit unsigned integers.
z = (65535*((y - y.max())/y.ptp())).astype(np.uint16)

# Use pypng to write z as a color PNG.
with open('foo_color.png', 'wb') as f:
    writer = png.Writer(width=z.shape[1], height=z.shape[0], bitdepth=16)
    # Convert z to the Python list of lists expected by
    # the png writer.
    z2list = z.reshape(-1, z.shape[1]*z.shape[2]).tolist()
    writer.write(f, z2list)

# Here's a grayscale example.
zgray = z[:, :, 0]

# Use pypng to write zgray as a grayscale PNG.
with open('foo_gray.png', 'wb') as f:
    writer = png.Writer(width=z.shape[1], height=z.shape[0], bitdepth=16, greyscale=True)
    zgray2list = zgray.tolist()
    writer.write(f, zgray2list)

rawDescription: Can I save a numpy array as a 16-bit image using "normal" (Enthought) python?

description: Save a numpy array as a 16-bit image using "normal" (Enthought) python


rawDescription: Choosing and iterating specific sub-arrays in multidimensional arrays in Python


code:
from numpy import linspace
from scipy.integrate import odeint

#you can choose a better guess using fsolve instead of 0
def integral(y, _, F_l, M, cache=[0]):
    v, preva = y[1], cache[0]
    #use value for 'a' from the previous timestep
    F_r = (((1 - preva) / 3) ** 2 + (2 * (1 + preva) / 3) ** 2) * v
    #calculate the new value
    a = (F_l - F_r) / M
    cache[0] = a
    return [v, a]

y0 = [0, 5]
time = linspace(0., 10., 1000)
F_lon = 100.
mass = 1000.

dydt = odeint(integral, y0, time, args=(F_lon, mass))

rawDescription: Solve an implicit ODE (differential algebraic equation DAE)


code:
#!/usr/bin/env python3
from subprocess import Popen

def run(cmd, log_filename):
    with open(log_filename, 'wb', 0) as logfile:
        return Popen(cmd, stdout=logfile)

# start several subprocesses
processes = {run(['echo', c], 'subprocess.%s.log' % c) for c in 'abc'}
# now they all run in parallel
# report as soon as a child process exits
while processes:
    for p in processes:
        if p.poll() is not None:
           processes.remove(p)
           print('{} done, status {}'.format(p.args, p.returncode))
           break

rawDescription: Python subprocess return code without waiting


code: operations = {'+':operator.add,'-':operator.sub,} # ...

rawDescription: how to "add" things together python

description: "add" things together python


rawDescription: Matrix-like printing of 2D arrays in Python


code:
y_gray = cm.gray(y)  # RGBA image with gray levels
imshow(y_gray, interpolation='nearest')  # Image of one of the arrays
diff_points = numpy.empty_like(y_gray)  # Preparation of an overlay with marked points only
diff_points[x == y, 3] = 0  # Common points not overwritten: alpha layer set to 0
diff_points[x != y] = [0, 1, 0, 1]  # Green for points that differ
imshow(diff_points, interpolation='nearest')

rawDescription: Matplotlib: plot differences between two images


code:
from itertools import product

for x, y, z in product(range(11), repeat=3):
    print('%.2f' % (x/10.0) + ' %.2f' % (y/10.0) + ' %.2f' % (z/10.0))

rawDescription: Python 3: Why are my while loops exiting?


code:
angle = obj.get_angle()
angle += 180
while angle>360: angle += -360
print(angle)
#now you have the angle from it collides.

rawDescription: Directional collisions in PyGame?

description: Directional collisions in PyGame


code:
def get_polymorphic_class(klass, data):
  column = klass.__mapper__.polymorphic_on
  if column is None:
    # The column is not polymorphic so the Class can be returned as-is
    return klass
  identity = data.get(column.name)
  if not identity:
    raise ValueError('Missing value for "' + column.name + '"', data)
  mapper = klass.__mapper__.polymorphic_map.get(identity)
  if mapper:
    return mapper.class_
  else:
    raise ValueError('Missing polymorphic_identity definition for "' + identity + '"')
  return klass

def insert(klass, data):
  klass = get_polymorphic_class(klass, data)
  e = klass(**data)
  session.add(e)
  session.commit()
  return e

rawDescription: SQLAlchemy cascading polymorphic column updates


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

x = np.arange(10)
y = np.random.random(10)
size = np.random.randint(150, size=10)
colors = np.random.choice(["r", "g", "b"], size=10)

fig = plt.figure()
plt.xlim(0, 10)
plt.ylim(0, 1)
graph = plt.scatter([], [])

def animate(i):
    graph.set_offsets(np.vstack((x[:i+1], y[:i+1])).T)
    graph.set_sizes(size[:i+1])
    graph.set_facecolors(colors[:i+1])
    return graph

ani = FuncAnimation(fig, animate, repeat=False, interval=200)
plt.show()

rawDescription: How can i make points of a python plot appear over time?

description: Make points of a python plot appear over time


code:
def test1():  # concat
    l = []
    for i in range(1000):
        l += [i]

rawDescription: Python concatenation vs append speed on lists


code:
import os

paths = [os.path.join(r'F:\Sheyenne\Statistics\IDL_stats', name)
         for name in ['NDVI', 'NDII']]
dfs = [get_df(path) for path in paths]

rawDescription: Function which changes strings of filenames based on a list


code:
import datetime
datetime
from datetime import datetime
datetime

rawDescription: How to get a dot notation of a python module?

description: Get a dot notation of a python module


rawDescription: Python - Count number of integers in a string?


code:
df = pd.DataFrame({"A": [1,2,2], "B": [2,3,1]})
pd.algos.is_monotonic_int64(df.A.values, False)[0]
pd.algos.is_monotonic_int64(df.B.values, False)[0]

rawDescription: Check whether non-index column sorted in Pandas


code: version = '''@PACKAGE_VERSION@'''

rawDescription: Accessing autoconf defined symbols in python


rawDescription: running median excluding zeros

description: Running median excluding zeros


code:
import mod
import sys
del sys.modules["mod"]
import mod as mod2

rawDescription: Python: How to load a module twice?

description: Python: How to load a module twice


rawDescription: How to match every thing except some character ? regex

description: Match every thing except some character ? regex


code:
myButton = Button(root)
myButton.pack()

rawDescription: Change the value of a variable with a button (Tkinter)


code:
name('Ż') == 'LATIN CAPITAL LETTER Z WITH DOT ABOVE'
name('ł') == 'LATIN SMALL LETTER L WITH STROKE'
lookup('LATIN CAPITAL LETTER Z') == 'Z'
lookup('LATIN SMALL LETTER L') == 'l'

rawDescription: Translating letters not in 7bit ASCII to ASCII (like ń to n and ą to a)


code:
from rpy2.robjects.vectors import FloatVector, IntVector
pot = FloatVector((2.0, 3.2, 4, 5, 6, 7))
ts = IntVector((1,6,7,19,20,30))
pot.slots['times'] = ts

rawDescription: How to set an attribute to a vector in rpy2

description: Set an attribute to a vector in rpy2


code:
from App.config import getConfiguration

product_config = getattr(getConfiguration(), 'product_config', {})
config = product_config.get('pd.prenotazioni', {})
logfile = config.get('logfile')

rawDescription: How to get the location of a Zope installation from inside an instance?

description: Get the location of a Zope installation from inside an instance


code:
from django.template import Context, Template
t = Template(html)
c = Context({'HEADER':html_header,'FOOTER':html_footer})
return HttpResponse(t.render(c))

rawDescription: Render to template and get a response

description: Render to template and get a response


code:
import os
import urllib
image_url = "https://www.google.com/images/srpr/logo3w.png"
image_filename = os.path.basename(image_url)
urllib.urlretrieve(image_url, image_filename)

rawDescription: How to grab the output from python subprocess

description: Grab the output from python subprocess


rawDescription: 2D Numpy Array of Strings WITH column access


code: pd.read_csv("log.txt", sep='|')

rawDescription: Output and Import list of lists to Pandas DataFrame


rawDescription: Confused about Python’s id()

description: Confused about Python’s id()


code:
import Image

def find_centroid_faster(im, rez):
    width, height = im.size
    XX, YY, count = 0, 0, 0
    for x in xrange(0, width, rez):
        for y in xrange(0, height, rez):
            if im.getpixel((x, y)) == 255:
                XX += x
                YY += y
                count += 1
    return XX/count, YY/count

rawDescription: Finding a specific index in a binary image in linear time?


code:
class App(...):
  def __init__(self, a, b):
    pass

  def do_something(self, a):
    pass

app_instance = App()

def do_something_else(self, b):
  pass

App.do_something_else = do_something_else

app_instance.do_something_else('b')

rawDescription: How can I extend a class instance?

description: Extend a class instance


code:
class User(Base):
   __tablename__ = 'users'
   id = Column(Integer, primary_key=True)
   url_pic = Column(String(50), nullable=False)
   pic = Column(LargeBinary, nullable=False)
   ...

rawDescription: Flask-Admin upload and insert in database automatically


code: grouped = df.groupby('Cust_No')

rawDescription: Finding the closest date given a date in a groupby dataframe (Python)


code: t_EXPRESSION = r'\[.*?\]'

rawDescription: Does ply.lex Parse The Same Token Once?

description: Does ply.lex Parse The Same Token Once


code: s.format(name='John', age=42)

rawDescription: Python pattern replacement

description: Python pattern replacement


code:
def argmax(**kw):
  return max(kw, key=kw.get)

argmax(foo=3, bar=5, frotz=1, kaka=-3)

rawDescription: Create function in python to find the highest of all function arguments, and return the "tag" of the value


code:
def some_service_function(kwargs): # <- note the lack of **
    foo = kwargs.get('foo')
    bar = kwargs.get('bar')

rawDescription: Passing in **kwargs from Flex over PyAMF


code:
a = []
b = [] #Note: Do not do a = b = [], it will assign a and b to a list with the same ID

rawDescription: Remove item from Object set that doesn't exist in query set


code:
with open('somefile.txt', 'r') as f:
   reader = csv.DictReader(f, delimiter='\t')
   rows = list(reader) # If your file is not large, you can
                       # consume it entirely

   # If your file is large, you might want to
   # step over each row:
   #for row in reader:
   #    print(row['A'])

for row in rows:
   print(row['A'])

rawDescription: Storing each column in a separate dictionary using python


code:
def build_set(filename):
    # A set stores a collection of unique items.  Both adding items and searching for them
    # are quick, so it's perfect for this application.
    found = set()

    with open(filename) as f:
        for line in f:
            # [:2] gives us the first two elements of the list.
            # Tuples, unlike lists, cannot be changed, which is a requirement for anything
            # being stored in a set.
            found.add(tuple(sorted(line.split()[:2])))

    return found

set_more = build_set('100rwsnMore.txt')
set_del = build_set('100rwsnDeleted.txt')

with open('results.txt', 'w') as out_file:
   # Using with to open files ensures that they are properly closed, even if the code
   # raises an exception.

   for res in (set_more - set_del):
      # The - computes the elements in set_more not in set_del.

      out_file.write(" ".join(res) + "\n")

rawDescription: Compare two different files line by line and write the difference in third file - Python


code: dictionary = {str(i) for i in dictionary}

rawDescription: Check variables against a dictionary, and print the dictionary contents remaining


code:
def test_empty(self):
    Base.assignment = {}
    assert len(Base().assignment.values()) == 0

rawDescription: Better way to mock class attribute in python unit test


code:
def main():
    harper = readFile("Harper's Speech.txt")
    newWords = cleanUpWords(harper)
    print(numWords(newWords), "Words.") # use newWords here!

rawDescription: Trying to use output of one function to influence the next function to count words in text file


code:
def get_dictionary_word_list():
    with open('dictionary.txt') as f:
        return f.read().split() # need parens to call the split method

def anagram(str1,str2):
    return sorted(str1) ==  sorted(str2)

def find_anagrams(s):
    return [word for word in get_dictionary_word_list() if anagram(word,s)]

rawDescription: How to define a function that returns a list of all words in a file that are anagrams of a input string in python

description: Define a function that returns a list of all words in a file that are anagrams of a input string in python


code:
mylst = []
d1[1] = mylst[:]      # make a copy
mylst.append('Joe')
d1[1]                 # => []     # what you expected

rawDescription: python variable length values in dictionary

description: Python variable length values in dictionary


code:
import copy

a = [1,2,3]

def b(x):
    z = copy.deepcopy(x)
    z.append(10)
    return z

b(a)
print(a)

rawDescription: Function editing lists in Python

description: Function editing lists in Python


code:
elems = driver.find_elements_by_partial_link_text('sometext')
if elems:
    my_elem = elems[-1]

rawDescription: How can I return the last element that fits under the criteria for driver.find_element_by_partial_link_text?

description: Return the last element that fits under the criteria for driver.find_element_by_partial_link_text


code:
pattern = "(this)(.*)(string)"
re.sub(pattern,
       lambda m: ''.join('<markup>%s</markup>' % s if n % 2 == 0
                         else s for n, s in enumerate(m.groups())),
       text)

rawDescription: replacing all regex matches in single line

description: Replacing all regex matches in single line


code:
from collections import Counter # needs 2.7
from operator import itemgetter
def get_ngrams(strg, n, top=10, min_count=2):
    counter = Counter()
    for i in xrange(len(strg) - n + 1):
        gram = strg[i:i+n]
        counter[gram] += 1
    sort_these = [(gram, count) for gram, count in counter.iteritems() if count >= min_count]
    best = sorted(sort_these, key=itemgetter(1), reverse=True)[:top]
    return best

rawDescription: How to find recurring patterns on a hexdump?

description: Find recurring patterns on a hexdump


rawDescription: Selecting One String from data list in Python


code:
if logger:
    logger.debug('message')

rawDescription: Avoid check if logger exists

description: Avoid check if logger exists


code:
from subprocess import Popen, PIPE
from StringIO import StringIO

buf = StringIO()
im.save(buf, 'PPM')

p = Popen(["gocr", "-"], stdin=PIPE)
p.communicate(input=buf.getvalue())

rawDescription: Piping image on Windows

description: Piping image on Windows


code:
for character in phrase:
    x = ord(character)

    if character == ' ':
        result += ' '
    else:
        result += chr(x + shift)

rawDescription: Caesar Cipher Python - Additional Features


code: row[2] = name_to_abbr.get(row[1].upper(), "")

rawDescription: Translating State Names in Python

description: Translating State Names in Python


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(requests.get('http://bodetree.com/what-is-causing-your-headaches-startup-pain-points/', timeout=7.00).text)

bullets = soup.select("div.entry-content ul li")
print([bullet.get_text() for bullet in bullets])

rawDescription: How to filter out unwanted tags within tags

description: Filter out unwanted tags within tags


code:
def remove_keys(obj, rubbish):
    if isinstance(obj, dict):
        obj = {
            key: remove_keys(value, rubbish)
            for key, value in obj.iteritems()
            if key not in rubbish}
    elif isinstance(obj, list):
        obj = [remove_keys(item, rubbish)
                  for item in obj
                  if item not in rubbish]
    return obj

rawDescription: How to recursively remove certain keys from a multi-dimensional(depth not known) python dictionary?

description: Recursively remove certain keys from a multi-dimensional(depth not known) python dictionary


code:
import pandas as pd
idx = pd.IndexSlice
df.loc[(cond1) & (cond2), idx[:,'column_name']]

rawDescription: extract the subset of a pandas multi index data frame

description: Extract the subset of a pandas multi index data frame


rawDescription: Optional dot in regex

description: Optional dot in regex


rawDescription: Value in dict won't let me change it

description: Value in dict won't let me change it


rawDescription: fast way to compare whether the number is in the list of ranges in python

description: Fast way to compare whether the number is in the list of ranges in python


rawDescription: Use pandas (and glob?) to merge numerous (csv) data text files from a directory.


code:
df = pd.DataFrame({'ID': a[:, 0], 'value': a[:, 1]})
df

rawDescription: NumPy : normalize column B according to value of column A


code:
with tarfile.open(...) as tar:
    while True:
        next = tar.next()
        stream = tar.extractfile(next)
        process_stream()
        iter+=1
        tar.members = []  # Clear members list
        if not iter%1000:
            objgraph.show_growth(limit=10)

rawDescription: Leaking TarInfo objects

description: Leaking TarInfo objects


code: global user

rawDescription: I need help understanding why the return value is different from what I expected. I am using the cmd module


code:
i = raw_input("what is your name\n")
print(i)
j = raw_input("What is your age\n")
print(j)

rawDescription: python subprocess: check to see if the executed script is asking for user input

description: Python subprocess: check to see if the executed script is asking for user input


code:
class Cls(object):
    foo = 1
    bar = 'hello'
    def func(self):
        return 'call me'
obj = Cls()

rawDescription: Iterate over object attributes in python


code:
bowler_scores = {}
for line in open('bowlingscores.txt', 'rb'):
    line = line.strip()
    if line.isalpha():
        name = line.strip()
        bowler_scores[name] = [] #1
    elif line.isdigit():
        score = int(line)
        bowler_scores[name].append(score) #2

def avg(x, y):
    return x/float(y)

total = sum([sum(scores) for scores in bowler_scores.values()]) #3
num_scores = sum(len(value) for value in bowler_scores.values()) #4
total_avg = avg(total, num_scores) # 5

output = open('output.txt','wb')
for name, scores in bowler_scores.items(): #6
    bowler_avg = avg(sum(scores),len(scores)) #7
    if sum(scores) == 60:
        output.write('{0} {1} Perfect\r\n'.format(name, scores))
    elif bowler_avg > total_avg: #8
        output.write('{} {} Above average\r\n'.format(name, scores)) #9
    elif bowler_avg < total_avg:
        output.write('{} {} Below average\r\n'.format(name, scores))
output.close()

rawDescription: having trouble outputting an answer to a text file

description: Having trouble outputting an answer to a text file


code:
import fileinput
for line in fileinput.input("in.txt"): # single filename string
    print (line)

rawDescription: argument type of fileinput.input() in python

description: Argument type of fileinput.input() in python


code: f = scipy.interpolate.interp1d(t, X)

rawDescription: Spline of curve (python)

description: Spline of curve (python)


code:
slices_start.searchsorted(4) #4
Out: 2

rawDescription: Python - slice array until certain condition is met