code:
import csv

list_of_months = ['January', 'February', 'March', 'April', 'May', 'June',
                  'July', 'August', 'September', 'October', 'November', 'December']
list_of_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
list_of_hours = list(range(24))

# ALL POSSIBLE COMBINATIONS
combn = [[m, d, h] for m in list_of_months for d in list_of_days for h in list_of_hours]

# RETRIEVE CSV DATA
data = []
with open('CSVData.csv', 'rt') as csvfile:
    csvReader = csv.reader(csvfile)
    next(csvReader)
    for row in csvReader:
        data.append(row)

# ITERATE OVER COMBINATIONS AND CSV DATA CONDITIONALLY APPENDING AVERAGES
avgs = []
for c in combn:
    cntval = 0; sumval = 0
    for d in data:
        if c[0] == d[1] and c[1] == d[2] and c[2] == int(d[3]):
            sumval = sumval + float(d[4])
            cntval += 1

    if cntval > 0:
        avgs.append([c[0], c[1], c[2], sumval/cntval])

for a in avgs:
    print(a)

rawDescription: Calculate mean over values in lines of CSV file if month, week day, and time match a conditon


code:
c.x += 4
# is equivalent to
c.x.__iadd__(4)

rawDescription: make python @property handle +=, -= etc

description: Make python @property handle +=, -= etc


rawDescription: Fast way to find locally maximal gradient values in a numpy array?


code:
@property
def y(self):
    return self.data.ix['bar', 'y']

rawDescription: Dynamically Generating Pandas Views

description: Dynamically Generating Pandas Views


code:
code = 'return_val = pbinom(100, 20000, 100./20000., 0, 1);'
support_code = 'extern "C" double pbinom(double x, double n, double p, int lower_tail, int log_p);'
weave.inline(code, support_code=support_code,
    library_dirs=[libpath], libraries=["Rmath"], runtime_library_dirs=[libpath])

rawDescription: How do I use scipy.weave.inline together with external C libraries?

description: Use scipy.weave.inline together with external C libraries


code: print("Inside C")

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


code:
_no_alter = set(['tables', 'which', 'do not', 'have', 'a created_at', 'column'])
Base.metadata.create_all(engine)
for table in Base.metadata.tables.keys():
    if table not in _no_alter:
      engine.execute(text('ALTER TABLE {} MODIFY created_at TIMESTAMP NOT NULL DEFAULT 0'.format(table)))

rawDescription: SqlAlchemy TIMESTAMP 'on update' extra

description: SqlAlchemy TIMESTAMP 'on update' extra


code:
stage1
stage2

rawDescription: how to express `there is a child node in current node` in lxml

description: Express `there is a child node in current node` in lxml


code: d

rawDescription: Python: zip 2 lists into a dictonary, del the duplicated keys but keep the values


code:
keyword_dictionary = {'mo-ped': 'Vehicle', 'group': 'People', 'spaghetti': 'Food', 'f-1': 'Vehicle', '6': 'People',
                      '5': 'People', 'five': 'People', 'gothic': 'Buildings', 'seven': 'People', 'adults': 'People',
                      'burrito': 'Food', 'martini': 'Signage', 'f one': 'Vehicle', 'ten': 'People', 'instrument': 'DJ',
                      'dress': 'Person', 'drink': 'Bottle', 'mushroom': 'Food', 'cat': 'Animal', 'glass': 'Glass',
                      'animal': 'Animal', 'pizza': 'Food', 'formula': 'Vehicle', 'meal': 'Food', 'curry': 'Food',
                      '3': 'People', 'sign': 'Signage', 'f1': 'Vehicle', 'biscuit': 'Food', 'bottles': 'Signage',
                      'pasta': 'Food', 'card': 'Signage', 'sculpture': 'Art', '8': 'People', 'apples': 'Food', '9':
                          'People', 'nacho': 'Food', 'mat': 'Signage', 'bottle': 'Bottle', 'shirt': 'Person', 'halter':
                          'Person', 'jockey': 'DJ', 'six': 'People', 'beef': 'Food', 'party': 'Party', 'container': 'Glass',
                      'women': 'People', 'four': 'People', '10': 'People', 'attractive': 'Person', 'mo ped': 'Vehicle',
                      'blackboard': 'Signage', 'two': 'People', 'f-one': 'Vehicle', '4': 'People', 'car': 'Vehicle',
                      'cheese': 'Food', 'plate': 'Food', 'food': 'Food', 'smiling': 'Person', 'bodycon': 'Person',
                      'jelly': 'Food', 'button': 'Person', 'men': 'People', 'people': 'People', 'eight': 'People',
                      'sushi': 'Food', 'chalkboard': 'Signage', 'cake': 'Food', 'sorbet': 'Food', 'turntable': 'DJ',
                      '2': 'People', 'skyscraper': 'Buildings', 'nine': 'People', 'meatballs': 'Food', '7': 'People',
                      'art': 'Art', 'building': 'Buildings', 'sleeveless': 'Person', 'lamb': 'Food', 'disc': 'DJ',
                      'scooter': 'Vehicle', 'asian': 'Food', 'chicken': 'Food', 'food pyramid': 'Food', 'person':
                          'Person', 'ad': 'Signage', 'spectacles': 'Person', 'glasses': 'Glass', 'dog': 'Animal',
                      'logo': 'Signage', 'mixer': 'DJ', 'dj': 'DJ', 'architecture': 'Buildings', 'three': 'People',
                      'fearns': 'Art', 'taco': 'Food', 'f 1': 'Vehicle', 'steak': 'Food', 'cup': 'Glass', 'man':
                          'Person', 'woman': 'Person', 'advert': 'Signage', 'candy': 'Food', 'meat': 'Food',
                      'adult': 'Person', 'moped': 'Vehicle', 'Luck is overrated': 'Slogan'}

with open("test.txt") as termsdesk:
    for line in termsdesk:
        for word in line.split():
            if word in keyword_dictionary:
                print(keyword_dictionary[word])

rawDescription: Python - reading complex lines of text into dictionary


code:
l = [{"pk": d["pk"], "url": d["fields"]["url"], "image": d["fields"]["image"], "name": d["fields"]["name"]} for d in l]
new_data = dict((d["pk"], d) for d in l)
new_data

rawDescription: Deserialize list of nested dictionaries to a simpler form


code:
for combo in ordered_op(good, bad):
    print(combo)

for combo in ordered_op(bad, good):
    print(combo)

rawDescription: all combinations of differences of two lists

description: All combinations of differences of two lists


code:
def quit(self):
    """Quits the driver and close every associated window."""
    try:
        RemoteWebDriver.quit(self)
    except (http_client.BadStatusLine, socket.error):
        # Happens if Firefox shutsdown before we've read the response from
        # the socket.
        pass
    self.binary.kill()
    try:
        shutil.rmtree(self.profile.path)
        if self.profile.tempfolder is not None:
            shutil.rmtree(self.profile.tempfolder)
    except Exception as e:
        print(str(e))

rawDescription: Python Selenium: How to check whether the WebDriver did quit()?


code:
key = [ord(d) for d in decrypt]
print(key)

rawDescription: Python: Sum of numbers

description: Python: Sum of numbers


code: set('ab') < set('abc')

rawDescription: Comparing sets in python nlp

description: Comparing sets in python nlp


code: df.loc['one', 'white']

rawDescription: Pandas `DataFrameGroupBy` and `SeriesGroupBy`


code: list_a = map(str, list_a)

rawDescription: output list of special letters string with python

description: Output list of special letters string with python


code:
data = np.array([10, 20, -30], dtype=np.int16)
ii = np.iinfo(data.dtype)
ii.max
ii.min
ii.bits

rawDescription: Determine maximum allowed sample value in wave file in Python


code:
(u'January 1, 2 & 3:', u'Alvin and the Chipmunks: The Road Chip')
(u'January 8, 9 & 10:', u"Daddy's Home")
(u'January 15, 16 & 17:', u'Star Wars: The Force Awakens')
(u'January 22, 23 & 24:', u'Star Wars: The Force Awakens 3D')
(u'January 29, 30 & 31:', u'Norm of the North')
(u'February 5, 6 & 7:', u'The Forest')
(u'February 12, 13 & 14', u'Kung Fu Panda 3')
(u'February 19, 20 & 21', u'Kung Fu Panda 3 3D')
(u'February 26, 27 & 28', u'Ride Along 2')
(u'March 4, 5 & 6', u'Deadpool')
(u'March 11, 12 & 13', u'Gods of Egypt')
(u'March 18, 19 & 20', u'Zootopia')
(u'March 25, 26 & 27', u'Zootopia 3D')
(u'April 1, 2 & 3', u'The Divergent Series: Allegiant')
(u'April 8, 9 & 10', u'Miracles From Heaven')
(u'April 29, 30 & May 1', u'Batman v Superman')

rawDescription: Using BeautifulSoup to find specific text on a webpage


rawDescription: How to convert DMS to Radian with a given format : DD-MM-SS in python

description: Convert DMS to Radian with a given format : DD-MM-SS in python


code:
result = {}

for fac, member, role in yourlist:
    fac_data = result.setdefault(fac, {})
    fac_data.setdefault(role, []).append(member)

rawDescription: Group a list of tuples to dictionary in Python


code:
import selenium
from selenium import webdriver
from pyvirtualdisplay import Display

try:
    display = Display(visible=0, size=(800, 600))
    display.start()
    browser = webdriver.Firefox()
    browser.get('mikekus.com')

except KeyboardInterrupt:
    browser.quit()
    display.stop()

rawDescription: How to emulate a browser with JavaScript support via Mechanize?

description: Emulate a browser with JavaScript support via Mechanize


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

alpha = 1
t = np.linspace(0, 2*np.pi, num=1000)

x = alpha * np.sqrt(2) * np.cos(t) / (np.sin(t)**2 + 1)
y = alpha * np.sqrt(2) * np.cos(t) * np.sin(t) / (np.sin(t)**2 + 1)

plt.plot(x, y)
plt.show()

rawDescription: Pyplot lemniscate

description: Pyplot lemniscate


rawDescription: Python - Remove list(s) from list of lists (Similar functionality to .pop() )


code:
keys = {'red', 'green', 'blue', 'yellow', 'orange', 'pink', 'black'}
d = dict.fromkeys(keys)  # dict is pre-sized to 32 empty slots

rawDescription: Improving performance of very large dictionary in Python


code:
seq_record=SeqIO.read(handle,"gb")
nucleotide_accession = seq_record.annotations["db_source"]

rawDescription: Retrieve DNA sequence using a gene identifier of a protein


rawDescription: Write a loop using python

description: Write a loop using python


code:
def remove_letters(str1,str2):
    str2_list = list(str2)
    for char in str2:
        if char in str1:
             str2_list.remove(char)
    return "".join(str2_list)

rawDescription: Removing letters from a string that occur in the previous string


code:
with proc.stdout as f:
    program_output = f.read()

rawDescription: Having multiple processes/threads running at all times, accessing a sqlite3 db until a condition is met


code: b = [list(t) for t in zip(*(col for col in zip(*a) if col[0] == 2))]

rawDescription: Create new list based on values taken from sublist


code:
job = et.Element('JOB')
for itemnumber,(salesman,quantity) in D.items():
    item = et.SubElement(job,'ITEM')
    et.SubElement(item,'NUMBER').text = str(itemnumber)
    et.SubElement(item,'SALESMAN').text = str(salesman)
    et.SubElement(item,'QUANTITY').text = str(quantity)

rawDescription: How to copy certain information from a text file to XML using Python?

description: Copy certain information from a text file to XML using Python


rawDescription: How do I easily (and efficiently) delete a single element from array?

description: Easily (and efficiently) delete a single element from array


code: x if isinstance(x, list) else [x, x]

rawDescription: Zip list of scalars and lists

description: Zip list of scalars and lists


code: df.columns = pd.MultiIndex.from_tuples([('JAS', 'bid'), ('JAS', 'ask')])

rawDescription: How to read csv file into pandas DataFrame with multiple row index level?

description: Read csv file into pandas DataFrame with multiple row index level


code:
def max_alpha(a, b):
    # Assumption: 'a' and 'b' are of same size
    im_a = a.load()
    im_b = b.load()
    width, height = a.size

    alpha = Image.new('L', (width, height))
    im = alpha.load()
    for x in xrange(width):
        for y in xrange(height):
            im[x, y] = max(im_a[x, y], im_b[x, y])
    return alpha

rawDescription: PIL merge of two images with alpha channels - not working as expected


code:
y_min = 10
y_max = 50
y_list = [100*sin(x) for x in range (0,100)]

mod_y = [0 if y < y_min else y - y_min for y in y_list]
mod_y = [y_max - y_min if y > y_max else y - y_min for y in mod_y]

scipy.integrate.cumtrapz(mod_y)

rawDescription: May I use a integration limit on scipy cumtrapz?


code: pd.merge(frame_1, frame_2, left_on = 'county_ID', right_on = 'countyid')

rawDescription: Joining pandas dataframes by column names


code:
@app.route('/user/<int:id>', strict_slashes=False)
@app.route('/user/<int:id>/<username>', strict_slashes=False)
def profile(id, username=None):
    user = models.User.query.get_or_404(id)
    if user.clean_username != username:
        return redirect(url_for('profile', id=id, username=user.clean_username))
    return render_template('profile.html', user=user)

rawDescription: Flask redirecting multiple routes

description: Flask redirecting multiple routes


code:
import networkx as nx
import matplotlib.pyplot as plt

hrc_dict = {('Hillary Clinton', 'Cheryl Mills'): 355, ('Hillary Clinton', 'l'): 1, ('Linda Dewan', 'Hillary Clinton'): 1, ('Hillary Clinton', 'Capricia Marshall'): 9, ('Phillip Crowley', 'Hillary Clinton'): 2, ('Cheryl Mills', 'Anne-Marie Slaughter'): 1}

G = nx.Graph()

# To add the a node for each of the email parties:
srcs, dests = zip(* [(fr, to) for (fr, to) in hrc_dict.keys()])
G.add_nodes_from(srcs + dests)
# (but it isn't needed IF the following method is used
#  to add the edges, since add_edge also creates the nodes if
#  they don't yet exist)

# note the use of the attribute "weight" here
for (s,r), count in hrc_dict.items():
    G.add_edge(s, r, weight=count)

# produce info to draw:
# a) if weight was used above, spring_layout takes
#    into account the edge strengths
pos = nx.spring_layout(G)

# b) specifiy edge labels explicitly
# method from https://groups.google.com/forum/#!topic/networkx-discuss/hw3OVBF8orc
edge_labels=dict([((u,v,),d['weight'])
             for u,v,d in G.edges(data=True)])

# draw it
plt.figure(1);
nx.draw_networkx(G, pos, with_labels=True)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)

plt.axis('equal') # spring weighting makes more sense this way
plt.show()

rawDescription: How to add nodes and edges to a network analysis graph in Networkx?

description: Add nodes and edges to a network analysis graph in Networkx


code:
from framework import game

game.foo()

rawDescription: Organizing source code in python

description: Organizing source code in python


code:
def mousePressEvent(event):
  """
    User has clicked inside the widget
  """
  # get mouse position
  x = event.x()
  y = event.y()
  # find coordinates of grid rectangle in your grid
  # copy and store this grid rectangle

rawDescription: Make certain regions of an image selectable


code:
content = set(['aba', 'abanga', 'abaptiston', 'abarelix'])
unwanted_words = set(['aba', 'aca', 'ada'])
content.difference(unwanted_words)

rawDescription: Python: search and replace - string delineation issue


code:
L = ['a', 'b',['aa','bb','cc'], 'c']

def lookups( L ):
    """ returns `item`, `code` tuples """
    for i, item in enumerate(L):
        if isinstance(item, list):
            for j, sub in enumerate(item):
                yield sub, "%02d%02d" % (i,j)
        else:
            yield item, "%02d" % i

rawDescription: Most optimal way to reverse search list of similar strings


code:
class SomeObjectAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        # do any pre-save stuff here
        obj.save()

rawDescription: How to implement a script while saving a file in django admin panel?

description: Implement a script while saving a file in django admin panel


code:
n=0
for x in List:
    print(n, x)
    n += 1

rawDescription: Print lines with numbers infront

description: Print lines with numbers infront


rawDescription: Copying file without previous meta data

description: Copying file without previous meta data


code:
import pprint
from Tkinter import *

root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
pprint.pprint(w.config())
root.mainloop()

rawDescription: Is it possible to get widget settings in Tkinter?


rawDescription: using python's stats.kendalltau function

description: Using python's stats.kendalltau function


code: zscores = mstats.zscore(mdata, axis=1, ddof=1)

rawDescription: How to apply a function on a subset of numpy.ndarray object

description: Apply a function on a subset of numpy.ndarray object


code: {d['name']: d['sex'] for d in input_structure}

rawDescription: turn tuple of dicts into single dict

description: Turn tuple of dicts into single dict


code: np.kron(np.kron(a,b), c)

rawDescription: build matrix from blocks

description: Build matrix from blocks


code: h = T/N

rawDescription: for-loops in Python modules

description: For-loops in Python modules


rawDescription: python range creation best practice

description: Python range creation best practice


rawDescription: Is it possible to np.concatenate memory-mapped files?


code:
#!/usr/bin/python

import re

def write_html(filename, title, content):

    # prepare the content... inject the title into the
    # content.

    content = re.sub(r'(?<=<title>").*?(?="</title>)', title, content)

    wfh = open(filename, 'w')
    wfh.write(content)
    wfh.close

if __name__ == '__main__':

    name = 'hello.html'
    title = "This is a terrible title!"
    content = '<content><title>"TitleTitle"</title>' \
              '
"Hi brah!"
</content>'

    write_html(name, title, content)

rawDescription: How to write HTML into a function?

description: Write HTML into a function


code: A.m.im_func is A.m.im_func

rawDescription: Why is a method not identical to itself?

description: Why is a method not identical to itself


code: BOARD[rand_row][rand_col] == 'O'

rawDescription: Python: changing element of a list at a random index


rawDescription: Compute the number of consecutive identical values in a list


code:
df
df.apply(lambda x: x.value_counts()).fillna(0)

rawDescription: How to get and show counts of values each column

description: Get and show counts of values each column


code:
@contextlib.contextmanager
def masking(namespace, mask):
    # If you don't have a fixed set of maskable variables, make it
    # an instance/global/local variables, like `_names`, or just
    # [name for name, value in namespace.items() if isiinstance(value, np.ndarray)]
    names = 'tinc agi dec exem'.split()
    stash = {name: namespace[name] for name in names}
    for name in names:
        namespace[name] = namespace[name][mask]
    try:
        yield
    finally:
        for name in names:
            namespace[name] = stash[name]

rawDescription: Apply a mask to multiple lines (syntactic sugar?)


code: for i in targets: print( i, targets[i])

rawDescription: How can i convert the list into three lists based on criteria and put in dictionary

description: Convert the list into three lists based on criteria and put in dictionary


code:
import wx
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub
from threading import Thread
import threading
import time

class gui(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, None, id, title, size=(500,400))
        myPanel = wx.Panel(self, -1, size=(300,200))
        image1 = wx.Image('green.bmp', wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.bitmap2 = wx.StaticBitmap(myPanel, -1, image1, (0, 0))
        pub.subscribe(self.addImage, 'Update')
        self.myButton = None

    def addImage(self):
        # Don't keep adding children to bitmap2
        if self.myButton:
            self.myButton.Destroy()
        self.myButton = wx.Button(self.bitmap2, -1, size =(30,30), pos=(20,20))
        image2 = wx.Image('blue.bmp', wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        self.bitmap1 = wx.StaticBitmap(self.myButton, -1, image2, (0, 0))

class myThread(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.start()
    def run(self):
        while True:
            time.sleep(2)
            wx.CallAfter(pub.sendMessage, 'Update')

if __name__=='__main__':
    app = wx.App()
    frame = gui(parent=None, id=-1, title="Test")
    frame.Show()
    myThread()
    app.MainLoop()

rawDescription: Avoiding unnecessary memory consumption in Python and wxPython


code:
def add8_from_bin8(a,b,c0):
    add8(*(a + b + [c0]))

add8_from_bin8(intTObin8(1), intTObin8(1), 0)

rawDescription: How to pass multiple params to function in python?

description: Pass multiple params to function in python


rawDescription: How do I take a list of lists and rearrange them in python

description: Take a list of lists and rearrange them in python


code:
import itertools

notes = ['e', 'B', 'G', 'D', 'A', 'E']
with open('tab.txt') as fp:
    # Read-in 6 lines
    lines = itertools.islice(fp, 0, 6)

    # Holds all the notes.
    frets = []

    # Process the lines, append all notes to frets.
    for note, line in itertools.izip(notes, lines):
       frets.extend(parse_line(line, note))

    # Sort the frets by position.
    frets.sort()

    # Drop the positions.
    frets = [fret for pos, fret in frets]

rawDescription: guitar tab to uke tab program help

description: Guitar tab to uke tab program help


code:
def get_prep_lookup(self, lookup_type, value):
    # For "__month", "__day", and "__week_day" lookups, convert the value
    # to an int so the database backend always sees a consistent type.
    if lookup_type in ('month', 'day', 'week_day'):
        return int(value)

rawDescription: Exclude weekends in python django query set


rawDescription: How to efficiently handle european decimal separators using the pandas read_csv function?

description: Efficiently handle european decimal separators using the pandas read_csv function


code: min(lst, key=lambda item: len(item[2]))

rawDescription: How to find index of item with shortest list inside?

description: Find index of item with shortest list inside


code: df3 = df3.sort()

rawDescription: Remove rows with duplicate indices (Pandas DataFrame and TimeSeries)


code:
def testlogin(browser):
    import hlogin # this is a file that contains my hoovers login credentials

    login_url = "https://subscriber.hoovers.com/H/login/login.html"
    browser.open(login_url)
    form = browser.get_form(id='loginForm')  # gets login form ID
    form['j_username'].value = hlogin._hname  # fills in hoovers login name
    form['j_password'].value = hlogin._hpass  # fills in hoovers password
    browser.submit_form(form)  # submits login

rawDescription: Login function in separate file using RoboBrowser


code: quals = get_entire_resultset( amt.get_qualifications_for_qualification_type, qualid )

rawDescription: An elegant way of page-to-page iterating through boto.resultset.ResultSet


rawDescription: matlab operations of 2 numpy arrays of same shape in python

description: Matlab operations of 2 numpy arrays of same shape in python


code: titlelist=[elem['title'] for elem in soup.findAll('td', attrs={X : Y})]

rawDescription: Extract information within tag

description: Extract information within tag


code: {'sellPrice': 209, 'meanPrice': 378, 'buyPrice': 224}

rawDescription: Retrieve multiple values from JSON

description: Retrieve multiple values from JSON


code:
for ccy in ccyAr:
    for d in data:
        table['ccy']['d'] = 0

rawDescription: Create and instantiate python 2d dictionary


rawDescription: django get json values

description: Django get json values


code:
t0 = time.time()

for i in xrange(1000):
    binary_search([1]*1000000,2)

t1 = time.time()
avg = (t1 - t0)/1000

print( "Average Time Taken",avg )

rawDescription: how to run a function multiple times

description: Run a function multiple times


code:
class Same(object):
    def __init__(self, value):
        self.value = value
    def __hash__(self):
        return 42
    def __eq__(self, other):
        return True
    def __repr__(self):
        return 'Same(%r)' % self.value
set([Same(2), Same(1)])
set([Same(1), Same(2)])

rawDescription: Python - When duplicate items are identified, which object does a set or frozenset take?


code:
im = plt.imread('/path/to/image.png')
# Plot your heatmap on big_ax and colorbar on cbar_ax
heatmap = big_ax.imshow(np.random.rand(10, 10), aspect='auto', origin='lower')
cbar = fig.colorbar(heatmap, cax=cbar_ax)

# Show your images on top_ax and right_ax
top_ax.imshow(im, aspect='auto')

# need to rotate my image.
# you may not have to if you have two different images
from scipy import ndimage
right_ax.imshow(ndimage.rotate(im, 90), aspect='auto')

# Clean up the image axes (remove ticks, etc.)
right_ax.set_axis_off()
top_ax.set_axis_off()

# remove spacing between axes
fig.subplots_adjust(wspace=0.05, hspace=0.05)

rawDescription: How to plot heat map with matplotlib?

description: Plot heat map with matplotlib


code:
perm = np.lexsort(a[:, 3::-1].T)
a[perm]

rawDescription: Filter a numpy array based on largest value


code:
import re
email_string = "az <az@example.com>"
re.findall(r'<([^>]+)>', email_string)

rawDescription: How to eliminate email formatting in received email?

description: Eliminate email formatting in received email


code:
proc = subprocess.Popen(["/path/to/myCprogram", "/path/to/file.c"],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err_output = proc.communicate()
# output will now contain the stdout of the program in a string

rawDescription: Simplest way to integrate python gui app with c console app


rawDescription: Split list into list of lists by regex

description: Split list into list of lists by regex


code:
from cocos.director import director
from cocos.layer import *
from cocos.scene import Scene
from pyglet.window import key
from pyglet.window.key import KeyStateHandler

class MyLayer(Layer):

    def __init__(self):
        super(MyLayer, self).__init__()
        self.keys = KeyStateHandler()
        director.window.push_handlers(self.keys)
        self.schedule(self.act_on_input)

    def act_on_input(self, dt):
        if self.keys[key.SPACE]:
            print('Space!')

def main():
    director.init(resizable=False, width=1024, height=786)
    title_scene = Scene(MyLayer())
    director.run(title_scene)

if __name__ == '__main__':
    main()

rawDescription: Key polling with cocos2d-python and pyglet


code:
views.py
from django.core.exceptions import PermissionDenied
def cars(request, car_id):
    ...
    if request.user != car.owner:
        raise PermissionDenied
    ...

rawDescription: Limit url acces with Django

description: Limit url acces with Django


code:
mapp=map(lambda x,y,z:"; ".join((x,y,str(z))),name,country,age)
for x in mapp:
    print(x)

rawDescription: Can i integrate multiple lists in python?

description: Integrate multiple lists in python


code:
#from math import ceil

def isqrt(n):
  x = n
  y = (x + n // x) // 2
  while y < x:
    x = y
    y = (x + n // x) // 2
  return x

def fermat(n, verbose=True):
    a = isqrt(n) # int(ceil(n**0.5))
    b2 = a*a - n
    b = isqrt(n) # int(b2**0.5)
    count = 0
    while b*b != b2:
        if verbose:
            print('Trying: a=%s b2=%s b=%s' % (a, b2, b))
        a = a + 1
        b2 = a*a - n
        b = isqrt(b2) # int(b2**0.5)
        count += 1
    p=a+b
    q=a-b
    assert n == p * q
    print('a=',a)
    print('b=',b)
    print('p=',p)
    print('q=',q)
    print('pq=',p*q)
    return p, q

n=103591*104729
fermat(n)

rawDescription: Fermat Factorisation with Python

description: Fermat Factorisation with Python


code:
prog = Programs()
prog.name
prog.ask()
prog.name

rawDescription: How to get user input within a Method (python)

description: Get user input within a Method (python)


code: 1.2738 * (list_of_items)

rawDescription: Matrix scalar multiplication

description: Matrix scalar multiplication


code:
sizes = ('small', 'medium', 'large', 'extralarge', 'mega')
sizemap = {size: value for value, size in enumerate(sizes)}

rawDescription: JSON dictionary lookup

description: JSON dictionary lookup


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


rawDescription: delete items at the same position (index) from two synchronized lists?

description: Delete items at the same position (index) from two synchronized lists


rawDescription: Sampling histograms such that the sum over the sample is uniform


code: { k:a.get(k,'') + '\t' + b.get(k,'') for k in set(it.chain(a.keys(), b.keys())) }

rawDescription: joining two dictionaries and handling its common value

description: Joining two dictionaries and handling its common value


code:
# create an in-memory "file":
f = cStringIO.StringIO()

# attach it to a writer:
w = csv.writer(f)

# write something:
w.writerows([[1,2,3],[4,5,6],[7,8,9]])

# read the content:
content = f.getvalue()

rawDescription: Python MySQL query to CSV in memory

description: Python MySQL query to CSV in memory


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cgi
import uuid
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text      import MIMEText
from email.mime.image     import MIMEImage
from email.header         import Header

img = dict(title=u'Picture report…', path=u'TESTING.png', cid=str(uuid.uuid4()))

msg = MIMEMultipart('related')
msg['Subject'] = Header(u'Report…', 'utf-8')
msg['From'] = gmail_user
msg['To'] = ", ".join([to])
msg_alternative = MIMEMultipart('alternative')
msg.attach(msg_alternative)
msg_text = MIMEText(u'[image: {title}]'.format(**img), 'plain', 'utf-8')
msg_alternative.attach(msg_text)

msg_html = MIMEText(u'
'
                     '

'
                    .format(alt=cgi.escape(img['title'], quote=True), **img),
                    'html', 'utf-8')
msg_alternative.attach(msg_html)

with open(img['path'], 'rb') as file:
    msg_image = MIMEImage(file.read(), name=os.path.basename(img['path']))
    msg.attach(msg_image)
msg_image.add_header('Content-ID', '<{}>'.format(img['cid']))

rawDescription: Send e-mail to Gmail with inline image using Python


code:
import ctypes
memfield = (ctypes.c_char).from_address(0x0A7F03E4)

rawDescription: How to change the value stored in memory adress?

description: Change the value stored in memory adress


code:
def get_bin(x, bin_width, start=0):
    return (x - start) // bin_width

rawDescription: dividing floating points into buckets

description: Dividing floating points into buckets


code: [t[0] for t in re.findall(r'((.)\2+)', strin)]

rawDescription: Find all countinuous repeating characters using a simpler solution or preferably a regex


rawDescription: Use colormaps along with matplotlib cycler


code:
def csvContainer(*cols):
    container = [
        [x for x in items if x is not None] for items in
        itt.izip_longest(*cols)
        ]

rawDescription: Better conditional lists

description: Better conditional lists


code:
import pandas as pd
import numpy as np
from itertools import product

np.random.seed(1)

periods = range(0,3)
categories = list('ABC')

rows = list(product(periods, categories)) * 2
n = len(rows)

df = pd.DataFrame({'Projected': np.random.randn(n),
                   'Actual': np.random.randn(n),
                   'Previous': np.random.randn(n)},
                  index = pd.MultiIndex.from_tuples(rows))
df.index.names = ['Period', 'Category']
summed = df.groupby(level=['Period', 'Category']).sum()
summed['tuple'] = zip(*[summed[c] for c in ['Projected', 'Actual', 'Previous']])
result = summed['tuple'].unstack('Period')

rawDescription: Pivot a pandas dataframe and get the non-axis columns as a series


code:
import model.client
o = model.client.clientclass()

rawDescription: python MySQL module class file name

description: Python MySQL module class file name


code: tap(2, lambda x: print(x)) + 3

rawDescription: Ruby's tap idiom in Python

description: Ruby's tap idiom in Python


code: exec('sudo -u#1000 -s python path/to/DocumentConverter.py filename.docx filename.pdf');

rawDescription: Docx to pdf using openoffice headless way too slow


code: sorted(get_files("."),key = os.path.getmtime,reverse = True)[:5]

rawDescription: How to retrieve the most recently created files in a directory

description: Retrieve the most recently created files in a directory


code:
for key in nameData:
    namelist.write('\n' 'KPLR00' + key + '-2009131105131')

rawDescription: Looping a write command to output many different indices from a list seperately in Python


code:
transformed = ({k: func(v) if k in keys_for_func else v for k, v in d.items()}
               for d in all_dicts)
result = list(map(itemgetter(*keys_of_interest), transformed))

rawDescription: Filter item from a dict and process a subset


rawDescription: Calculate sums with large binomial coefficients


rawDescription: Pandas get specific rows from HDF5 by index


code: from tkinter.filedialog import askopenfilename

rawDescription: How to save text form a textbox (String and Int) in python 3.x tkinter

description: Save text form a textbox (String and Int) in python 3.x tkinter


code:
from pyspark.sql.functions import *

data = data.select(col("Name").alias("name"), col("askdaosdka").alias("age"))
data.show()

# Output
#+-------+---+
#|   name|age|
#+-------+---+
#|Alberto|  2|
#| Dakota|  2|
#+-------+---+

rawDescription: How to change dataframe column names in pyspark?

description: Change dataframe column names in pyspark


rawDescription: Inline SVG Served By Python Script in Google App Engine Not Appearing


children: B C

rawDescription: Python library for creating tree graphs out of nested Python objects (dicts)


code: dependent = employee.dependent.get(id = id)

rawDescription: Creating an edit form from model containing Foreignkey?


code:
class MyModel1(BaseModel): # inherit the base model class

    # define other non-common fields here
    ...

class MyModel2(BaseModel): # inherit the base model class

    # define other non-common fields here
    ...

rawDescription: Django: how to create custom "base" model


code:
if __name__ == '__main__':
    app.debug = True
    app.run(threaded=True)

rawDescription: How to implement server push in Flask framework?

description: Implement server push in Flask framework


code:
def map_reduce(data, mapper, reducer):
    d = {}
    for elem in data:
        key, value = mapper(elem)
        d.setdefault(key, []).append(value)
    for key, grp in d.items():
        d[key] = reducer(key, grp)
    return d

rawDescription: Iterate within directory to zip files with python


code:
def r_pad_string2(s, fillchar='.'):
    lines = s.splitlines()
    max_len = max(len(l) for l in lines)
    return '\n'.join(l.ljust(max_len, fillchar) for l in lines)

rawDescription: Pad right multi-line string

description: Pad right multi-line string


rawDescription: How do I fetch url with urllib2 without declaring a url scheme?

description: Fetch url with urllib2 without declaring a url scheme


code: a if b else c if d else e

rawDescription: pandas if then statement without looping

description: Pandas if then statement without looping


code: [OrderedDict(row) for i, row in df.iterrows()]

rawDescription: How to turn pandas dataframe row into ordereddict fast

description: Turn pandas dataframe row into ordereddict fast


code:
x = 0
def outer():
    x = 1
    def inner():
        x = 2
        print("inner:", x)

    inner()
    print("outer:", x)

outer()
print("global:", x)

# inner: 2
# outer: 1
# global: 0

rawDescription: Python nonlocal statement

description: Python nonlocal statement


code:
from itertools import permutations

def take(l, partition):
  offsets = [0]
  for x in partition:
    offsets.append(offsets[-1]+x)
  for p in permutations(l):
    yield frozenset([frozenset(p[offsets[i]:offsets[i+1]]) for i in range(len(offsets)-1)])

for x in frozenset(take([1,2,3,4,5],(3,1,1))):
  print([[z for z in y] for y in x])

rawDescription: Set partition with fixed size

description: Set partition with fixed size


rawDescription: How to modify a text file using Python

description: Modify a text file using Python


code:
image = "insert image"
rect = image.get_rect ()

rawDescription: How to centre an image in pygame?

description: Centre an image in pygame


code:
corpusFile = codecs.open(filename, mode = 'w', encoding = 'utf-8')
# ...
tagged_token = '\xdcml\xe4ut'
tagged_token = tagged_token.decode('ISO-8859-1')
corpusFile.write(tagged_token)
corpusFile.write(u'\n')

rawDescription: Wanted Python to create a UTF-8 File, got an ANSI one. Why?


code:
import csv
from itertools import count
from collections import defaultdict
from functools import partial

counts = defaultdict(partial(count, 1))  # create a new count starting at 1

with open(output_csv_filename, 'wb') as outfile:
    writer = csv.writer(outfile)
    for row in your_list_of_rows:
        row[9] = next(counts[row[2]])  # get the next count value
        writer.writerow(row)

rawDescription: Re Ranking data within a csv after row removal


code: re.search(r'\b(?:[a-zA-Z0-9]\s){2,}', 'My name is arun its A R U N jayapal. I am going to London.').group()

rawDescription: regex to match a series of single Character followed by a single space

description: Regex to match a series of single Character followed by a single space


rawDescription: Splinter saves bodiless html

description: Splinter saves bodiless html


code:
from django.db.models.expressions import Func
# SQLite function to force a date time subtraction to come out correctly.
# This just returns the expression on every other database backend.
class ForceDate(Func):
    function = ''
    template = "%(expressions)s"
    def __init__(self, expression, **extra):
        self.__expression = expression
        super(ForceDate, self).__init__(expression, **extra)

    def as_sqlite(self, compiler, connection):
        self.function = 'julianday'
        self.template = 'coalesce(%(function)s(%(expressions)s),julianday())*24*60*60*1000*1000' # Convert julian day to microseconds as used by Django DurationField
        return super(ForceDate, self).as_sql(compiler, connection)

rawDescription: Datetime differences in Django using SQLite


code:
with tarfile.TarFile('package.tgz', 'w:gz') as tar:
    for pathname in pathnames:
        tar.add(pathname)

rawDescription: Create a package files python

description: Create a package files python


code:
from __future__ import print_function
import sys

# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
sys.path.extend(['.', '..'])

from pycparser import c_parser, c_ast, parse_file

class IfVisitor(c_ast.NodeVisitor):
    def __init__(self):
        pass

    def visit_If(self, node):
        node.show()
        self.generic_visit(node);

def start(filename):
    ast = parse_file(filename, use_cpp=True)
    v = IfVisitor()
    v.visit(ast)

if __name__ == "__main__":
    if len(sys.argv) > 2:
        filename = sys.argv[1]
    else:
        filename = 'examples/c_files/test.c'

    start(filename)

rawDescription: pycparser nested node visitor

description: Pycparser nested node visitor


rawDescription: Python searching patterns in lists of strings


code:
df[['one', 'two']].values.tolist()
df[['one', 'two', 'four']].values.tolist()

rawDescription: Make Tuples from Specific Pandas Columns


code:
col_names = [id1,id2,id3,id4,id5,id6,val1,val2,val3]
left.columns = col_names
right.columns = col_names
middle.columns = col_names

rawDescription: Union all type query with python pandas

description: Union all type query with python pandas


code:
os.listdir(".")
os.listdir(u".")

rawDescription: open file with a unicode filename?

description: Open file with a unicode filename


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, filtfilt

def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filtfilt(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y = filtfilt(b, a, data)
    return y

data = np.loadtxt('data.dat', skiprows=2, delimiter=',', unpack=True).transpose()
time = data[:,0]
pressure = data[:,1]
cutoff = 1500
fs = 50000
pressure_smooth = butter_lowpass_filtfilt(pressure, cutoff, fs)

figure_pressure_trace = plt.figure()
figure_pressure_trace.clf()
plot_P_vs_t = plt.subplot(111)
plot_P_vs_t.plot(time, pressure, 'r', linewidth=1.0)
plot_P_vs_t.plot(time, pressure_smooth, 'b', linewidth=1.0)
plt.show()
plt.close()

rawDescription: How to filter/smooth with SciPy/Numpy?

description: Filter/smooth with SciPy/Numpy


code:
def neg_log_likelihood(scale):
    total = 0.0
    for x, count in counter.iteritems():
       total += (math.log(scale) + x / scale) * count
    return total

rawDescription: Fit a distribution to a Counter in scipy


code:
from PIL import Image, ImageOps, ImageDraw

size = (128, 128)
mask = Image.new('L', size, 255)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + size, fill=0)
im = Image.open('image.jpg')
output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.paste(0, mask=mask)
output.convert('P', palette=Image.ADAPTIVE)
output.save('output.gif', transparency=0)

rawDescription: How do I generate circular thumbnails with PIL?

description: Generate circular thumbnails with PIL


code:
dom = conn.lookupByName(the_domain_name)
dom.create() # start the domain

rawDescription: Python - libvirt

description: Python - libvirt


code: x = x + datetime.timedelta(days = -1)

rawDescription: Getting the RFC 3339 timestamp for a day ago


code:
nums = (13, 42)
'{0} is {1}'.format('my stuff', ''.join('{:02X}'.format(a) for a in nums))

rawDescription: python .format() repeated fields?

description: Python .format() repeated fields


code:
url(r'^form', 'my_view', {"exportCSV": False}, name="form"),
url(r'^csv', 'my_view', {"exportCSV": True}, name="export"),

rawDescription: Generating CSV file with Django (dynamic content)


code:
import re
re.findall(r'\b%s\b' % p[0], text1)
re.findall(r'\b%s\b' % p[0], text1, re.I)
re.findall(r'\b%s\b' % p[1], text1, re.I)
re.findall(r'\b%s\b' % p[2], text1, re.I)

rawDescription: How can I count phrases and use the phrases as headers in Python?

description: Count phrases and use the phrases as headers in Python


code: Thread(target=run, args = (args.arg1, args.arg2))

rawDescription: Python: terminate a multithreading program after some time using daemon thread


code:
from django.contrib.contenttypes.admin import GenericTabularInline

class LinkedItemAdmin(GenericTabularInline):
    model = LinkedItem

    # choosing the field and display
    field = ['ingredient']
    filter_horizontal = ['ingredient']

    # These help with removing some potential issues in the admin
    extra = 0
    min_num = 1
    max_num = 1
    can_delete = False

rawDescription: How to access a ManyToManyField between two apps using ContentTypes for Django admin?

description: Access a ManyToManyField between two apps using ContentTypes for Django admin


code: np.array((a, b, c)).T

rawDescription: How to add to arrays such that matching elements become their own arrays

description: Add to arrays such that matching elements become their own arrays


code:
# DO NOT
channel.basic_consume(callback_func, queue, no_ack=True)

rawDescription: How to consume RabbitMQ messages via pika for some limited time?

description: Consume RabbitMQ messages via pika for some limited time


code:
t = (a, b)
n = Node(a, b)
existing_nodes.get(t, n)

rawDescription: Dictionary of Objects to access by Reference


rawDescription: How to split one list in a list of x list with python?

description: Split one list in a list of x list with python


code:
latest_c = select([child.c.id]).\
                where(child.c.parent_id==parent.c.id).\
                order_by(child.c.sortkey.desc()).\
                limit(1).\
                correlate(parent).\
                as_scalar()

mapper(Parent, parent, properties={
    'all_c':relation(Child),
    'latest_c':relation(Child,
                            primaryjoin=and_(
                                child.c.id==latest_c,
                                child.c.parent_id==parent.c.id
                            ),
                            uselist=False
    )
})

rawDescription: How do I define a SQLAlchemy relation representing the latest object in a collection?

description: Define a SQLAlchemy relation representing the latest object in a collection


rawDescription: How to calculate difference on previous within set of grouped rows in a dataframe

description: Calculate difference on previous within set of grouped rows in a dataframe


code:
final_qs = qs_list[0]
for qs in qs_list[1:]:
    final_qs |= qs

rawDescription: Pythonic List Iteration

description: Pythonic List Iteration


rawDescription: Digram list manipulation with Python

description: Digram list manipulation with Python


code:
unique_idx, _ = np.unique(avg_idx, return_inverse=True)
mov_avg = np.bincount(_, weights=avg_val.ravel())

rawDescription: Efficiently take moving average of sparse data and filter above threshold in python


code:
img = np.random.random_integers(0, 255, (15, 12, 3))
img.shape
converted = img * mask[:, :, None]
converted.shape

rawDescription: Copy channels in Numpy array

description: Copy channels in Numpy array


code:
img = i.find('img')
textPath = img.get('src')

rawDescription: Parsing XML node and substring from value


code: df.index.map(lambda t: t.replace(year=2013, month=2, day=1))

rawDescription: Change date of a DateTimeIndex

description: Change date of a DateTimeIndex


code: level=list(range(1, df2.index.nlevels))

rawDescription: reindex pandas MultiIndex on specific level

description: Reindex pandas MultiIndex on specific level


rawDescription: how to get all objects by instance in django

description: Get all objects by instance in django


code: df.columns[df.max() > 0]

rawDescription: Python Pandas drop columns based on max value of column


code:
s3 = s2.decode('utf8')
s3

rawDescription: python 3, unicode conversion, two \u0000 as one character

description: Python 3, unicode conversion, two \u0000 as one character


code:
result = []
for _, s in another_list:
    item = ()
    for lst in nested_list:
        count = 0
        for c in s:
            if c in lst:
                count += 1
        item += (count,)
    result.append(item)

rawDescription: Counting occurrences in nested lists

description: Counting occurrences in nested lists


code: words_starting_with_vowel = [word for word in words if word[0] in 'aeiou']

rawDescription: How to use Python to find out the words begin with vowels in a list?

description: Use Python to find out the words begin with vowels in a list


code:
common = Counter(m for m in message if m.isalpha()) \
                .most_common(3)

rawDescription: Isolating and filtering results from .most_common() in python


code:
id_i_know = 2
driver.find_element_by_css_selector("[id=RECORD_%d] a.smallV110" % id_i_know)

rawDescription: Selenium Find Sub-Child href Element

description: Selenium Find Sub-Child href Element


code:
boros = GeoDataFrame.from_file('nybb.shp')
boros.set_index('BoroCode', inplace=True)
boros.sort()
boros

rawDescription: How to generate simple polygons with equal area but varying edge

description: Generate simple polygons with equal area but varying edge


code:
from django.db.models import Q

Incident.objects.filter(
     Q(incident_id=incident_id) | Q(equipment_id=equipment_id)
)

rawDescription: Django form for querying database. Is form.py needed and how to leave fields empty for query?


code:
def flatten(a):
    b = []
    for c in a:
        if isinstance(c, list) and any(isinstance(i, list) for i in c):
            b.extend(flatten(c))
        else:
            b.append(c)
    return b

A = [ [[1,3]], [[3,5], [4,4], [[5,3]]] ]
flatten(A)

rawDescription: Python flatten list (but not all the way)


code: [re.search('(\w*)', i).group(1) for i in re.split('\nclass ', a) if re.search('\n\s*public static void main', i)]

rawDescription: Extracting java main class name in python


code:
element = driver.find_element_by_css_selector("[id^='operations_edit_process_list_task']")
id = element.get_attribute("id")
# do whatever you want with the id value

rawDescription: Selenium Xpath how do i get the value of an html id tag using starts-with


code:
sending_button.deleteLater()
if labelWidget:
   labelWidget.deleteLater()

rawDescription: Layout not adding correctly, seems that its not erasing previous widgets


code:
def memo(f):
    @functools.wraps(f)
    def func(*args):
        if args not in func.cache: # access attribute
            func.cache[args] = f(*args)
        return func.cache[args]
    func.cache = {} # add attribute
    return func

rawDescription: Can a function in python behave like a class?


code:
list_of_words = ['One', 'Two', 'Three', 'Four', 'Five']
[w[:-2] for w in list_of_words]

rawDescription: Slice every string in list in Python

description: Slice every string in list in Python


code:
json_docs = [json.dumps(doc, default=json_util.default) for doc in stories]

resp = jsonify(data=json_docs)

rawDescription: PyMongo and Flask's Jsonify contains escape slashes


code: dateList = [(d, d.weekday()) for d in dateList]

rawDescription: List of (date, day_of_week) tuples

description: List of (date, day_of_week) tuples


code:
for p in something:
  print(" ".join(map(str, something_else)))

rawDescription: Printing a simple table in Python

description: Printing a simple table in Python


code:
tree = etree.parse("some_file.xml")
etree_to_dict(tree.getroot())

rawDescription: Converting xml to dictionary using ElementTree


rawDescription: Permissions Error: Within a python script, I need to find a server file in unix system and open it to run commands for the user


code:
variable1 = "fi" #start the variable, they can come from the main program instead
variable2 = 2

datatowrite = str(variable1) + "\n" + str(variable2) #converts all the variables to string and packs them together broken apart by a new line

f = file("/file.txt",'w')
f.write(datatowrite) #Writes the packed variable to the file
f.close() #Closes the file !IMPORTANT TO DO!

rawDescription: Change variable permanently

description: Change variable permanently


rawDescription: Colletting element from different DataFrames into arrays


code:
[key for key, group in groupby(li)
        if (next(group) or True) and next(group, None) is None]

rawDescription: Elegant way to remove contiguous repeated elements in a list?


code:
globals()['clarence'] = SuperClass()
clarence.print_hello()

rawDescription: Instantiate a class to an unknown variable name in python3


rawDescription: Django: How to get the root path of a site in template?


code:
import random

sentence = 'Can I have some {} and {}?'

replacements = [
['pulka', 'butter kp', 'wheat parota', 'chapati', 'gobi parota', 'onion parota', 'paneer parota', 'kerala parota', 'aloo parota', 'plain naan', 'butter naan', 'garlic naan', 'plain kulcha', 'butter kulcha', 'lacha parota', 'tandoori roti', 'tandoori butter roti', 'roti'],
['paneer butter masala', 'palak paneer', 'kadai paneer', 'hydrabadi paneer', 'kadai gobi', 'aloo gobi', 'aloo mattar', 'mix veg curry', 'baby corn masala', 'dal fry', 'palak dal', 'dal tadka', 'mushroom masala', 'gobi masala', 'paneer tikka masala', 'mushroom tikka masala', 'aloo gobhi']
]

rawDescription: Python multiple string replacement

description: Python multiple string replacement


code:
def get_key_str(low="a", high="z"):
    if low == "":
        low = "a"
    assert(low < high)
    for i, (a, b) in enumerate(zip(low, high)):
        if a < b:
            mid = chr((ord(a) + ord(b))//2) # get the character half-way between a and b
            if mid != a:
                return low[:i] + mid
            else:
                return low[:i+1] + get_key_str(low[i+1:], "z")
    return low + get_key_str("a", high[len(low):])

rawDescription: Efficient way of keeping numbers in order


code:
lst_mw = re.findall(r"([A-Z][a-z]?)(\d*)", input_mw)
                    # ^ single uppercase and optional second lowercase
                                 # ^ as many digits as available

rawDescription: turn a number in an element of a string into a coefficient python

description: Turn a number in an element of a string into a coefficient python


code:
condition = df['col A'].abs() >= df['col B'].abs()
df['new col'] = np.where(condition, df['col A'], df['col B'])

rawDescription: Python Pandas: Using an array to choose different columns for each value of a new column


code:
import pandas as pd
import re
import decimal
D = decimal.Decimal

def make_parser(cls):
    def parse_commas(text):
        return cls(re.sub(r'[^-+\d.]', '', text))
    return parse_commas

to_int = make_parser(int)
to_decimal = make_parser(D)

data = pd.read_csv('data', parse_dates=[[0,1]], infer_datetime_format=True
                   , converters={4: to_int, 5: to_decimal, 6: to_int})

print(data)

rawDescription: Importing financial data into Python Pandas using read_csv


code:
#if separator is not ',' use sep=";" for ';' or sep="\s+" for whitespace
library = pd.read_csv("Library.txt")
query = pd.read_csv("Querry.txt")

mouse_lib = library['Mouse'].str.split(r"\$\|\$", expand=True).stack()
human_lib= library['Human'].str.split("\$\|\$", expand=True).stack()

df = pd.concat([human_lib, mouse_lib], axis=1, keys=['human','mouse']).reset_index(drop=True, level=1)

rawDescription: Find if a pattern matches then outputting split data from another column - $|$ separator failure


rawDescription: Sort Python Dictionary by first four characters in Key


rawDescription: Displaying dictionary value in django template


code:
def json_serialize(ip, mac, nic):
    net_info = []
    for ipaddr, macaddr, nicname in zip(ip, mac, nic):
        net_info.append({
            'interface_name': nicaddr,
            'mac': macaddr,
            'ip': ipaddr
        })
    return json.dumps({'net_info': net_info})

rawDescription: Python, String to JSON?

description: Python, String to JSON


code:
from distutils.core import setup

setup(name='xyz',
      py_modules=['xyz']
)

rawDescription: Best way to structure a larger project

description: Structure a larger project


code:
def isValidPassword(userPassword,hashKeyInDB):
     result = crypt(userPassword,hashKeyInDB,iterations = 1000)
     return reesult == hashKeyInDB #hashKeyInDB in this case is $p5k2$3e8$her4h.6b$.p.OE5Gy4Nfgue4D5OKiEVWdvbxBovxm

rawDescription: Verifying a PBKDF2 password hash in python-pbkdf2


code:
txt = []
for i in html:
    if i == '<':
        delete = True
        continue
    if i == '>':
        delete = False
        continue
    if delete == True:
        continue

    txt.append(i)

rawDescription: Removing html tags using python?

description: Removing html tags using python


code: a + np.repeat(b, a.shape[1]).reshape(a.shape)*[0,1,0]

rawDescription: Summing a 1D array with a col of a 2D array


code: c

rawDescription: Comparing and editing three lists of different lenght in python?


code:
t = (s - pd.Timedelta('11 hours')).dt.time
t.head()

rawDescription: Arithmetic on array of timestamps without year, month, day


code:
from itertools import combinations

def apply_pairwise(func, a):
    "For each row, call func with every possible combination of two values"

    stack = []
    for col_a, col_b in combinations(range(a.shape[0]), 2):
        stack.append(np.hstack([a[col_a], a[col_b]]))

    combined = np.vstack(stack)

    def unpack_row(row):
        "Calls func with the values of a given numpy array as arguments"
        return func(*row.tolist())

    return np.apply_along_axis(unpack_row, 1, combined)

rawDescription: How can I apply a function one column at a time?

description: Apply a function one column at a time


code:
import os
os.remove(file_to_remove)

rawDescription: Merging text files and delete file when you are done


code:
class Enemy(pygame.sprite.Sprite):
    def __init__(self, gs=None):
        pygame.sprite.Sprite.__init__(self)
        self.images = [pygame.image.load("enemy.png"), pygame.image.load("dead.png")]
        self.current_image = self.images[0]
        self.rect = self.current_image.get_rectangle()

rawDescription: pygame: replacing image of an item/enemy

description: Pygame: replacing image of an item/enemy


code:
class OrderedAutocomplete(autocomplete_light.AutocompleteModelBase):
    ordered_search_fields = []

    def choices_for_request(self):
        """
        Return a queryset based on :py:attr:`choices` using options
        :py:attr:`split_words`, :py:attr:`search_fields` and
        :py:attr:`limit_choices`.
        """
        assert self.choices is not None, 'choices should be a queryset'
        q = self.request.GET.get('q', '')
        exclude = self.request.GET.getlist('exclude')

        base_split_words = self.split_words

        _choices = []
        for weight,opt in enumerate(self.ordered_search_fields):
            if len(_choices) >= self.limit_choices:
                break

            search_fields = opt['search_fields']
            self.split_words = opt['split_words'] or base_split_words

            conditions = self._choices_for_request_conditions(q,
                    search_fields)
            choices = self.order_choices(self.choices.filter(conditions).exclude(pk__in=exclude))
            if choices.count():
                _choices += list(choices)[0:self.limit_choices]

        return _choices[0:self.limit_choices]

rawDescription: Force django-autocomplete=light to return 'best' matches first


code:
x = [5, "b"]
y = [3, "a"]
z = ["b", 5]
map(type, x) == map(type, y)
map(type, x) == map(type, z)

rawDescription: check if two lists are equal by type Python

description: Check if two lists are equal by type Python


code:
cols = ~np.all(temp, axis=0)
cols

rawDescription: Python. Remove from array (presented as list of lists) rows and columns by condition


code:
import time
import logging
from datetime import timedelta
from threading import Thread
from tornado.httpserver import HTTPServer
import tornado.ioloop
import tornado.web

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

def blocking_task(callback, seconds=10):
    time.sleep(seconds)
    callback('slept for %d seconds' % seconds)

class CallbackRequestHandler(tornado.web.RequestHandler):
    wait = timedelta(seconds=1)

    @tornado.web.asynchronous
    def get(self):
        tornado.ioloop.IOLoop.current().add_callback(self.start_loop)

    def start_loop(self):
        self.task = Thread(target=blocking_task,
            kwargs={'callback': self.write})
        self.task.start()
        logger.info('starting %s', self.task)
        self.loop()

    def loop(self):
        if self.task.is_alive():
            logger.info('waiting on %s', self.task)
            tornado.ioloop.IOLoop.current().add_timeout(self.wait, self.loop)
        else:
            logger.info('finished on %s', self.task)
            self.finish()

tornado_app = tornado.web.Application([
    (r"/", CallbackRequestHandler),
])

if __name__ == "__main__":
    http_server = HTTPServer(tornado_app)
    http_server.listen(9090)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Python tornado can only open one page when processing


rawDescription: how to convert python hours to regular hours

description: Convert python hours to regular hours


code:
from django.db import models

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

rawDescription: How to move a model between two Django apps (Django 1.7)

description: Move a model between two Django apps (Django 1.7)


code: key = float(key)

rawDescription: Python simple if or logic statement

description: Python simple if or logic statement


code:
dec_table = {'11': 'a', '41': 'p', '44': 's'}
enc_str = "41114444"
dec_str = ""

while len(enc_str) > 0:
    sym = enc_str[:2]
    dec_str += dec_table[sym]
    enc_str = enc_str[2:]

print (dec_str)

rawDescription: Decryption algorithm for a previously made encryption algorithm - python


rawDescription: sorting a list containing dates as a substring

description: Sorting a list containing dates as a substring


code:
Symbol('1+2').replace(
lambda x: x.is_Symbol and S(x.name).is_Number,
lambda x: S(x.name))

rawDescription: Classifying free symbols from expressions


code:
# Delete result records ("tombstones") from database after 4 hours
# http://docs.celeryproject.org/en/latest/configuration.html#celery-task-result-expires
CELERY_TASK_RESULT_EXPIRES = 14400

rawDescription: Django Celery Periodic Tasks Run But RabbitMQ Queues Aren't Consumed


rawDescription: REGEX, pythonchallenge.com

description: REGEX, pythonchallenge.com


rawDescription: How to apply multiple functions to numpy array?

description: Apply multiple functions to numpy array


rawDescription: How to compute variance with missing value in a DataFrame - Python Pandas?

description: Compute variance with missing value in a DataFrame - Python Pandas


code:
def reverse(a,size):
    b = 0
    for i in range(size):
        b <<= 1
        b |= a >> i & 1
    return b

rawDescription: little endian bits in python

description: Little endian bits in python


code:
# -*- coding: utf-8 -*-
from tornado.concurrent import Future
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop

def async_fetch_future():
    http_client = AsyncHTTPClient()
    my_future = Future()
    fetch_future = http_client.fetch('http://www.google.com')
    fetch_future.add_done_callback(
        lambda f: my_future.set_result(f.result()))
    return my_future

response = IOLoop.current().run_sync(async_fetch_future)

print(response.body)

rawDescription: Can't call result() on futures in tornado


rawDescription: Python: flip a precise bit in a double

description: Python: flip a precise bit in a double


code:
with open("numbers.txt") as f:
    odds = []
    evens = []
    for num in f:
        num = int(num)
        if num % 2: # if there is a remainder num is odd
            odds.append(num)
        else: # else it must be even
            evens.append(num)

print("All even numbers: {}".format(evens))
print("All odd numbers: {}".format(odds))
print("Total amount of even numbers: {}".format(len(evens))) # len will be total even nums
print("Total amount of odd numbers: {}".format(len(odds)))

rawDescription: How do I determine how many odd and even numbers are in a text file?

description: Determine how many odd and even numbers are in a text file


rawDescription: Modifying a shared dict object among processes doesn't work


code:
import numpy as np
a = np.random.rand(10) - 0.5
a[a<0] = np.NaN

rawDescription: Matlab's Logicals for Array Indexing - Python Equivalent


code:
s = Series(list('aaabbaa')).astype('category',categories=list('ba'))
s.cat.codes

rawDescription: Is it possible to specify the order of levels in Pandas factorize method?


code:
import re
p = re.compile(r'(?<=\bYEAR=)[^;]+')
test_str = "1  0001    1   UG  science,ee;YEAR=onefour;standard->2;district->9"
robj = re.search(p, test_str)
if robj:
    print(robj.group(0))

rawDescription: Extract substring from a line in python, if another keyword is found


code:
import syntax
b = syntax.Block()
b

rawDescription: Conveniently import several classes from modules in a Python package


code:
import urllib2
url = 'http://stackoverflow.com/questions/13431060/python-html-parsing'
req = urllib2.Request(url)
req.get_method = lambda : 'HEAD'
response = urllib2.urlopen(req)
content_type = response.headers.getheader('Content-Type')
print(content_type)

rawDescription: python html parsing

description: Python html parsing


code:
file_info = os.stat("/path/to/file")
size = file_info.st_size

rawDescription: how can you overwrite a file line with zeros

description: Overwrite a file line with zeros


rawDescription: How to rapidly create array of N 3x3 matrices from 9 arrays of size N?

description: Rapidly create array of N 3x3 matrices from 9 arrays of size N


code:
poolA =  ['AAG', 'TAC', 'CGG', 'GAT', 'TTG', 'GTG', 'CAT', 'GGC', 'ATT', 'TCT']

from Bio.Seq import Seq
from Bio.Alphabet import IUPAC

[str(Seq(seq, IUPAC.unambiguous_dna).complement()) for seq in poolA]

rawDescription: Converting letters using a dictionary

description: Converting letters using a dictionary


code:
class RedirectText:
    def __init__(self,aWxTextCtrl):
        self.out=aWxTextCtrl

    def write(self,string):
        self.out.WriteText(string)

rawDescription: Redirect command prompt output to a python generated window


code:
# this call to Popen actually returns a
# Popen object with a number of methods and attributes
# to interact with the process that was just created
p = Popen(cmd, shell=True, stdout=PIPE)

# communicate() is a method of a Popen object which
# allows you to wait for the return output of the pipes
# that you named (or send data to stdin)
# It blocks until data is ready and returns a tuple (stdout, stderr)
stdout, stderr = p.communicate()

# We only wanted the stdout in this case, so we took the first index
output = p.communicate()[0]

# output is a string, and strings have the strip() method to remove
# surrounding whitespace
stripped_output = output.strip()

rawDescription: Change DenyHosts report: Call external command from Python


code:
ourList =  [[1,2],[1,2],[1,4]]
c3 = np.empty(len(ourList), dtype=np.ndarray)
for i in xrange(len(ourList)):
    c3[i] = np.array(outList[i])
c3
c3[1] = np.array([5])
c3

rawDescription: Numpy - automatic implicit conversion of np.arrays into lists


code:
a_70 = np.nanpercentile(a, 70)
a_80 = np.nanpercentile(a, 80)

rawDescription: How to get the position in a certain percentile range of 2-d array with np.NAN in it

description: Get the position in a certain percentile range of 2-d array with np.NAN in it


rawDescription: Interpolating 3d data at a single point in space (Python 2.7)


code:
import sys
sys.stdout.write("hello")
sys.stdout.flush()
sys.stdout.write("bye")

rawDescription: Overwrite the previous print value in python?


rawDescription: pandas: filtering by group size and data value

description: Pandas: filtering by group size and data value


code:
class Real(Number):
    def __new__(cls, value):
        if cls is not __class__:
            # Subclass, create an instance
            return super().__new__(cls, value)

        if isinstance(value, int):
            return Int(value)
        elif isinstance(value, float):
            return Float(value)
        else:
            raise TypeError('Ты больше не можешь вести себя так!!!')

rawDescription: In python 3, how to create child class instance using some magic in parent __new__?


code:
class NewPipeline(object):
    def process_item(self, item, spider):
        name = item['name']
        self.file = open("pathToWhereYouWantToSave"+ name, 'wb')
        line = json.dumps(dict(item)) #change the item to a json format in one line
        self.file.write(line)#write the item to the file

rawDescription: Passing scraped data in piplines __init__ scrapy for python


code:
def query_tokens_by_user(user_id):
    min_key = ndb.Key(UserToken, "%s." % user_id)
    max_key = ndb.Key(UserToken, "%s/" % user_id)  # / is the next ASCII character after .
    return UserToken.query(UserToken.key > min_key, UserToken.key < max_key)

rawDescription: GAE webapp2 delete all UserTokens (drop all sessios) for specific user


code:
import numpy as np
out = a[np.where(t == 1),:,:]

rawDescription: Python time-lat-lon array manipulation and grouping


code:
DOWNLOADER_MIDDLEWARES = {
    'scrapyjs.SplashMiddleware': 725,
}

rawDescription: Why Scrapy cannot find href here?

description: Why Scrapy cannot find href here


code:
l = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
s = set()
for x in l:
    if x not in s:
        print("first occurrence of %s" % x)
        s.add(x)
    print(x)

rawDescription: First occurance of a number in python list


code:
self.userEventFilter = UserEventsFilter(self)
app = QtCore.QCoreApplication.instance()
app.installEventFilter(self.userEventFilter)

rawDescription: QProgressDialog not modal before minimum duration


code:
class Donor(models.Model):
    donor_first_name=models.CharField(max_length=50)
    donor_middle_name=models.CharField(max_length=50, blank=True, null=True)
    donor_last_name=models.CharField(max_length=50)

    def __str__(self):
        return "%s %s %s" % (self.donor_first_name, self.donor_middle_name, self.donor_last_name)

rawDescription: Instead of its id, I want to display Django values() on Foreign Key in template as object


code:
def gen_nonce(length):
   """ Generates a random string of bytes, base64 encoded """
   if length < 1:
      return ''
   string=base64.b64encode(os.urandom(length),altchars=b'-_')
   b64len=4*floor(length,3)
   if length%3 == 1:
      b64len+=2
   elif length%3 == 2:
      b64len+=3
   return string[0:b64len].decode()

rawDescription: What is the standard method for generating a nonce in Python?


code:
import base64

with open("my_file.txt") as f, open("original_b64.txt", 'w') as g:
    encoded = f.read()
    decoded = base64.b64decode(encoded)
    g.write(decoded)

rawDescription: Python: Decode base64 multiple strings in a file


code:
from subprocess import Popen, PIPE

opts = {"1": "ping", "2": "tracert"}

while True:
    print("""What did you want to run? (pick a number)
            (1) Ping
            (2) Traceroute""")
    runit = raw_input("> ")
    if runit in opts:
        host = raw_input("Enter a hostname to check\n> ")  # accept input for hostname
        p = Popen("cmd /c {} {}".format(opts[runit], host), shell=True, stdout=PIPE)
        with open("ping.txt", "w") as f:
            for line in iter(p.stdout.readline, ""):
                print(line)
                f.write(line)
        break
    print("Invalid option")

rawDescription: How do I write a command from Command Prompt to a file using Python?

description: Write a command from Command Prompt to a file using Python


code:
def skip_line_with(it, name):
    for line in it:
        if line.startswith(name):
            break
        yield line
    for line in it:
        yield line

with open('a.txt', 'r+') as f:
    replaced = list(skip_line_with(f, 'Name 2,'))
    f.seek(0)
    f.writelines(replaced)
    f.truncate()

rawDescription: Find the first instance of a variable in a .txt file and delete the line it is in


code: df.groupby(['c0'], as_index=False)['c6'].sum().apply(lambda x: 'abc' + x.astype(str) if x.name=='c6' else x)

rawDescription: How to append a string to int/float dataframes in Pandas

description: Append a string to int/float dataframes in Pandas


code:
from django.contrib import messages
messages.success(request, 'Form submitted successfully')

rawDescription: How to redirect twice in Django?

description: Redirect twice in Django


rawDescription: Counting a set of characters in a string


code: lines = [line.strip() for line in open(filename) if line.strip() and not line.startswith('com')]

rawDescription: Spliting a file into lines in Python using re.split


code:
self.ani = QPropertyAnimation(self, "color")
# etc

rawDescription: PySide QPropertyAnimation Not Starting

description: PySide QPropertyAnimation Not Starting


code: MenuHandler.callMenu({"New Game": {DEBUG: ["New Game"]}, "Load Game": {DEBUG: ["Load Game"]}}, "Pick something will ya")

rawDescription: Use 2 Strings to call Function X from Module Y


code:
conditions = {0: list('DFA'),
              1: list('ACEF'),
              2: list('CEF'),
              3: list('ABDF'),
              4: list('DEF'),
              5: list('AC'),
              6: list('ABCDE')}

rawDescription: Pandas compare each row to reference row - certain columns only


code:
import random

lowBound = 0
highBound = 100
response = ''
randomNumber = random.randint(lowBound,highBound)

while response != "yes":
    print ("Is it ", randomNumber, " ?")
    response = input()
    if response == "higher":
        lowBound = randomNumber + 1
        randomNumber = random.randint(lowBound,highBound)
    elif response == "lower":
        highBound = randomNumber - 1
        randomNumber = random.randint(lowBound,highBound)
    elif response == "yes":
        print ("Woohooo, I'm so bitchin'")
        break
    else:
        print ('Huh? "higher", "lower", or "yes" are valid responses.')

rawDescription: PYTHON - Reverse Number Guessing Game -

description: PYTHON - Reverse Number Guessing Game -


code:
import Camera

c2 = Camera.c1

rawDescription: Python class service

description: Python class service


rawDescription: Delete 0s that occur only at the beginning of a list


code: NON_SPECIAL = r'[^\'"]'

rawDescription: Match open and close brackets in garbled string


code:
def setdefault(self, key, default):
    try:
        return self[key]
    except KeyError:
        self[key] = default
        return default

rawDescription: How to convert a list of slash separated strings into a nested dictionary?

description: Convert a list of slash separated strings into a nested dictionary


code:
from inspect import getargspec

defaults = getargspec(my_function).defaults
my_variable = defaults[0]
my_function(my_variable)

rawDescription: python variable value to trigger parameter default

description: Python variable value to trigger parameter default


code:
from lxml import html

data = """

text1

text2

"""

tree = html.fromstring(data)
data = tree.xpath('//p/text()')
len(data)

data = [p.text_content() for p in tree.xpath('//p')]
len(data)

rawDescription: HTML parsing with lxml - how to keep empty content in resulting list?


code:
res['price'] = res['averageprice_x'] / res['averageprice_y']
res

rawDescription: Getting a new series conditional on some rows being present in Python and Pandas


code:
from struct import *
arg1, arg2, arg3, arg4, arg5 = unpack('!ddddi', buffer)

rawDescription: Python buffer decode

description: Python buffer decode


code:
def take_items(a):
    for x in a:
        if x[1] != 1:
            break
        yield x

rawDescription: testing for equality using itemgetter

description: Testing for equality using itemgetter


code: p[df.State, df.FutureState]

rawDescription: Create a vector with values from a Numpy array selected according to criteria in a Pandas DataFrame


code:
import  tarfile
tar = tarfile.open("test.tar")
tar.getmembers()

rawDescription: reading tar file contents without untarring it, in python script

description: Reading tar file contents without untarring it, in python script


code:
for tag in soup.find_all('li'):
    print(tag.get_text())

rawDescription: In Python BeautifulSoup4, How to extract the special text like this


code:
class Foo:
    pass

f = Foo()
f.thing = 'Jeff'

import ctypes
long_f = id(f)
y = ctypes.cast(long_f,ctypes.py_object).value
name = y.thing

rawDescription: How to create an object of an instance from string in Python

description: Create an object of an instance from string in Python


code:
# The pipe behaves like a file object in Python.
process = Popen(cmd, shell=True, stdout=PIPE)
process_output = ""
while process.poll():
     process_output += process.stdout.read(256)
s.write(process_output)

# Better yet.
process = Popen(cmd, shell=true, stdout=PIPE)
stdout, stderr = process.communicate() # will read and wait for process to end.
s.write(stdout)

rawDescription: Send output from a python server back to client


code:
for i in range(1, k+1):
    if k % i == 0:
        sx += i
for j in range(1, z+1):
    if z % j == 0:
        sy += j

rawDescription: How to stop a loop?

description: Stop a loop


code:
df_out = df.set_index(['Names']).stack().to_frame().reset_index()
df_out.columns = ['Names','month','value']

rawDescription: Groupby in Pandas yields Groupby Object rather than Dataframe


rawDescription: Saving output of a function as a variable and using it in another function


code:
def print_hierarchy(root, indent="1"):
    print('\t'.join([indent, root.name]))
    for index, child in enumerate(root.children, 1):
        print_hierarchy(child, ''.join(('\t', indent, '.', str(index))))

rawDescription: Printing a numbered outline of a hierarchical tree


code:
import itertools
def solve(size, symbols, todo = None):
  if todo is None: todo = frozenset(symbols)
  if size < len(todo): return
  if size == len(todo):
    yield from itertools.permutations(todo)  # use sorted(todo) here
                                             # for lexicographical order
    return
  for s in symbols:
    for xs in solve(size - 1, symbols, todo - frozenset((s,))):
      yield (s,) + xs

for x in solve(5, (1,2,3)):
  print(x)

rawDescription: iterate through all L length sequences of N symbols, that include all N symbols

description: Iterate through all L length sequences of N symbols, that include all N symbols


code:
from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, ForeignKey, Numeric, DateTime, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session, relationship

engine = create_engine('sqlite://', echo=True)
session = Session(bind=engine)
Base = declarative_base(bind=engine)

class CostCenter(Base):
    __tablename__ = 'cost_center'

    id = Column(Integer, primary_key=True)

class Expense(Base):
    __tablename__ = 'expense'

    id = Column(Integer, primary_key=True)
    cost_center_id = Column(Integer, ForeignKey(CostCenter.id), nullable=False)
    value = Column(Numeric(8, 2), nullable=False, default=0)
    date = Column(DateTime, nullable=False)

    cost_center = relationship(CostCenter, backref='expenses')

Base.metadata.create_all()

session.add_all([
    CostCenter(expenses=[
        Expense(value=10, date=datetime(2014, 8, 1)),
        Expense(value=20, date=datetime(2014, 8, 1)),
        Expense(value=15, date=datetime(2014, 9, 1)),
    ]),
    CostCenter(expenses=[
        Expense(value=45, date=datetime(2014, 8, 1)),
        Expense(value=40, date=datetime(2014, 9, 1)),
        Expense(value=40, date=datetime(2014, 9, 1)),
    ]),
    CostCenter(expenses=[
        Expense(value=42, date=datetime(2014, 7, 1)),
    ]),
])
session.commit()

base_query = session.query(
    Expense.date,
    func.sum(Expense.value).label('total')
).join(Expense.cost_center
).group_by(Expense.date)

# first query considers center 1, output:
# 2014-08-01: 30.00
# 2014-09-01: 15.00
for row in base_query.filter(CostCenter.id.in_([1])).all():
    print('{}: {}'.format(row.date.date(), row.total))

# second query considers centers 1, 2, and 3, output:
# 2014-07-01: 42.00
# 2014-08-01: 75.00
# 2014-09-01: 95.00
for row in base_query.filter(CostCenter.id.in_([1, 2, 3])).all():
    print('{}: {}'.format(row.date.date(), row.total))

rawDescription: GroupBy and Sum in SQLAlchemy?

description: GroupBy and Sum in SQLAlchemy


code:
dummy_cols = df.columns.difference(df[[value_col, id_col]].columns)
dfd = pd.get_dummies(df[dummy_cols | pd.Index([value_col])])

rawDescription: Pandas Groupby : group **by** a column containing tuples


code:
def slice_up(array):
    array_list = list(array)
    return sorted(array_list[2:-2:3] + array_list[:-2:3] + [array_list[-2]])

rawDescription: Creating new lists from values out of lists and arrays


code:
array([[False,  True, False],
   [False, False, False],
   [False, False, False],
   [ True, False, False]], dtype=bool)

rawDescription: Apply a pairwise shapely function on two numpy arrays of shapely objects


code:
d = {}

def dfs(x):
    if isleaf(x):
        d[x[0]] = x
        return
    for y in x[1]:
        dfs(y)
dfs(data)

res = [None] * (max(d) + 1)
for i, v in d.items():
    res[i] = v

rawDescription: Inserting an element in list, at exact location, without array sizing in Python?


rawDescription: Parsing Snort Logs with PyParsing

description: Parsing Snort Logs with PyParsing


rawDescription: using a variable keyword for an optional argument name with python argparse

description: Using a variable keyword for an optional argument name with python argparse


rawDescription: Converting date and time string to appropriate format for arithmetic calculations


code:
for start_ in start_positions:
    for  stop_ in stop_positions:
        if stop_ <= start_:
            continue
        else:
            print("{}...{}".format(start_, stop_))
            break

rawDescription: Creating a List of Lists for Three Reading Frames


code: mhl = {'m':np.mean, 'h':np.max, 'l':np.min}

rawDescription: Create multiple columns in pandas aggregation function


code: [sorted_and_merged(sublist) for sublist in completelist]

rawDescription: Python sort and merge with dense list of sublisted lists


code:
import os
os.startfile(filepath)

rawDescription: Wxpython cut copy paste and openfiledialog


code: plt.axhline(y=0.002, xmin=0, xmax=1, hold=None)

rawDescription: Plotting a horizontal line on multiple subplots in python using pyplot


code:
q = GqlQuery("SELECT * FROM Song WHERE composer = 'Lennon, John'")

q = GqlQuery("SELECT __key__ FROM Song WHERE composer = :1", "Lennon, John")

q = GqlQuery("SELECT * FROM Song WHERE composer = :composer", composer="Lennon, John")

rawDescription: pass a string variable into a gql query

description: Pass a string variable into a gql query


code:
C = np.array([A, B])
C = np.ma.masked_array(C, np.isnan(C))
C
np.mean(C, axis = 0)
np.ma.filled(np.mean(C, axis = 0), nan)

rawDescription: Average arrays with Null values

description: Average arrays with Null values


rawDescription: Finding common elements in a few lists out of all lists in python


code: l = [s.name for s in sections]

rawDescription: Checking if something exists in items of list variable in Django template


rawDescription: Is it possible to have Jinja2 ignore sections of a template that have {} in them (for instance, inline javascript)


code:
map_dict = {ord('A'):"A'", ord('B'):'BB', ord('C'):'CX', ord('D'):'KK'}
strs = 'ABCDEF'
strs.translate(map_dict)

rawDescription: Multiple-replace in python

description: Multiple-replace in python


rawDescription: Python Logging module not respecting setLevel below '30' (Warning)?


rawDescription: parsing parenthesized list in python's imaplib

description: Parsing parenthesized list in python's imaplib


code:
def func(row):
    xml = ['<item>']
    for field in row.index:
        xml.append('  <field name="{0}">{1}</field>'.format(field, row[field]))
    xml.append('</item>')
    return '\n'.join(xml)

rawDescription: How do convert a pandas/dataframe to XML?


code:
import colors
# colors doesn't know it has submodules 'blue' and 'red'
from colors import *
# if the colors __init__ has an __all__ declaration now it does know about them
hasattr(colors, "blue") # will work

rawDescription: Python call a package submodule with variable module name


code:
import re

user_pattern = re.compile('(\s|^)(@)(\w+)(\s|$)')
tweet = 'Hey @pssdbt, thats not what I wanted!'
tweet = user_pattern.sub('\1\2\3\4', tweet)

rawDescription: Linking a @username in Django Template Variables


code:
s
days = pd.date_range('2014-12-01', '2014-12-07')
s.reindex(days, method='ffill')

rawDescription: Sampling with the most recent value

description: Sampling with the most recent value


code: mask = np.empty(a.shape,dtype=bool)

rawDescription: trying to mask 2D numpy arrays based on values in one column

description: Trying to mask 2D numpy arrays based on values in one column


code:
distance = lambda i: int(math.fabs((len(word) / 2.) - i)) - 1
if len(word) % 2 == 1:
    offset = 1
else:
    offset = 0

for i in range(len(word) / 2 + offset):
    if i == len(word) - i - 1:
        print((i - offset) * " ", word[i])
    else:
        print(i * " ", word[i], (2 * distance(i) + offset) * " ", word[len(word) - i - 1], sep='')

rawDescription: I cannot figure out how to manipulate strings in a couple different ways


code:
haystack = 'dadad'
needle = 'dad'
sum(haystack[i:i+len(needle)] == needle for i in range(len(haystack)))

rawDescription: Count the number of times a particular string appears in a given word


code:
from Tkinter import *

def CreateTest():
    def saveTest():
        SaveTestButton.grid_remove()
        TestEntry.grid_remove() #ERROR
    TestEntry = Entry(master, text="", width = 100)
    TestEntry.grid(row=4,columnspan=6)
    Label(master, text="Enter Test Name:").grid(row=3, column=0)
    SaveTestButton = Button(master, text="Save to database", command=saveTest, fg="green", bg="white",    font="Helvetica 10 bold")
    SaveTestButton.grid(row=4, column=5)

master = Tk()
CreateTestButton = Button(master, text="Create Test", command = CreateTest, fg="red", bg="white",     font="Helvetica 10 bold")
CreateTestButton.grid(column=7, row=1)
mainloop()

rawDescription: grid_remove on an Entry widget

description: Grid_remove on an Entry widget


code:
for item1, item2 in product(list1, list2):
    pass

rawDescription: How to optimize the memory and time usage of the following algorithm in python

description: Optimize the memory and time usage of the following algorithm in python


rawDescription: Introspecting arguments from the constructor function __init__ in Python


code:
(u'Hartfield', u'United Kingdom')
(u'Edenbridge', u'United Kingdom')
(u'Sevenoaks', u'United Kingdom')

rawDescription: how to convert from longitude and latitude to country or city?

description: Convert from longitude and latitude to country or city


rawDescription: PyGObject Problems with a ComboBoxEntry

description: PyGObject Problems with a ComboBoxEntry


code:
class Representative(models.Model):
    parliament = models.CharField(max_length=128)
    name = models.CharField(max_length=128)
    country = models.CharField(max_length=128)
    party_group = models.CharField(max_length=128)
    national_party = models.CharField(max_length=128)
    position = models.CharField(max_length=128)

rawDescription: Populating a SQLite3 database from a .txt file with Python


code:
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class' : 'myfieldclass'})

rawDescription: How to markup form fields with <div class='field_type'> in Django

description: Markup form fields with <div class='field_type'> in Django


code:
import pandas as pd
df = pd.DataFrame({'A':['1', '<2', '3']})
df['A'] = df['A'].apply(lambda x: int(x[1:])-1 if x.startswith('<') else int(x))
print(df.dtypes)
# A    int64
# dtype: object

rawDescription: Python, pandas: how to remove greater than sign


code: return (myobject for _ in ".")

rawDescription: Single object iterator

description: Single object iterator


code:
df.loc[df.isnull().any(axis=1), "c"] = np.nan
df

rawDescription: How can I non-iteratively place a NaN in a DataFrame column if there is a corresponding NaN in any other columns?

description: Non-iteratively place a NaN in a DataFrame column if there is a corresponding NaN in any other columns


code: nyval = not myval

rawDescription: python how to "negate" value : if true return false, if false return true

description: Python how to "negate" value : if true return false, if false return true


code:
import numpy as np
import pylab

rawDescription: Creating a 2d mesh in python

description: Creating a 2d mesh in python


code:
class MyForm (forms.Form):
    def __init__ (self, title, desc, *args, **kwargs):
        self.title = title
        self.desc = desc
        super (MyForm, self).__init__ (*args, **kwargs) # call base class

rawDescription: How do I add plain text info to forms in a formset in Django?

description: Add plain text info to forms in a formset in Django


rawDescription: How to extract only text from the div containing more divs using scrapy

description: Extract only text from the div containing more divs using scrapy


code:
import random
import timeit

r = range(10000000)

setup = """
import numpy as np
l = list({!r})
s = set(l)
to_remove = {!r}
n = np.array(l)
n_remove = np.array(list(to_remove))
""".format(r, set(random.sample(r, 3)))

list_filter = "[x for x in l if x not in to_remove]"
set_filter = "s - to_remove"
np_filter = "n[np.in1d(n, n_remove, invert=True)]"

n = 1
l_time = timeit.timeit(list_filter, setup, number=n)
print("lists:", l_time)
s_time = timeit.timeit(set_filter, setup, number=n)
print("sets:", s_time)
n_time = timeit.timeit(np_filter, setup, number=n)
print("numpy:", n_time)

rawDescription: Difference operator between a List and a Set


code: server = DebugTCPServer((HOST, PORT), DebugMETCPHandler)

rawDescription: send a variable to a TCPHandler in python

description: Send a variable to a TCPHandler in python


rawDescription: How to evaluate an expression-tree in sympy?

description: Evaluate an expression-tree in sympy


rawDescription: Limiting the number of combinations /permutations in python


code:
column = v.feature_names_.index('foo')
values = X[:, column].todense() # get values
X[:, column] = 0 # remove them from X

rawDescription: Extracting a feature by feature name in scikit dict vectorizer


code:
urlpatterns += patterns('animals.views',
  url(r'^edit/(?P<object_id>\d+)$', 'edit_animal', name="edit_animal"),
)

rawDescription: In Django, how could one use Django's update_object generic view to edit forms of inherited models?


code:
def all_gt(nums, n):
    num2 = []
    for i in nums:
        if i > n:
            num2.append(i)
    return num2

rawDescription: Constructing a list from another list in python


code:
_do_atomic_job(start_x, start_y, end_x, end_y) # Separate coordinates
_do_atomic_job(start, end)                     # Better: start/end points
_do_atomic_job(rect)                           # Even better: rectangle

rawDescription: Overriding an inner function of a method in python


code:
import numpy as np
inarray = np.random.random(1000)
targarray = np.empty(len(inarray)//2+1, dtype='complex')
testarray = targarray  # just for checking the array wasn't overwritten
targarray[:] = np.fft.rfft(inarray)
targarray is testarray

rawDescription: needed: FFT implememtatin in Python using preallocated buffer to store results

description: Needed: FFT implememtatin in Python using preallocated buffer to store results


code:
def sentry_user_tween_factory(handler, registry):
    """ Returns a tween that does nothing but enhance the environ by information about the currently
        logged in user, which will be useful for the Sentry report in case there's an exception """
    def sentry_user_tween(request):
        user = request.session.get('user')
        if user:
            request.environ['myapp.user'] = (user.token, user.name, user.email)
        else:
            request.environ['myapp.user'] = (0, 'anonymous', None)
        # proceed with the next tween/handler
        response = handler(request)
        return response
    return sentry_user_tween

config.add_tween('myapp.sentry_user_tween_factory')

rawDescription: How do I report the currently logged in user to Sentry?

description: Report the currently logged in user to Sentry


code:
import numpy as np
import cv2

img = cv2.imread("e_5.jpg",0)
size = np.size(img)
skel = np.zeros(img.shape,np.uint8)

ret,img = cv2.threshold(img,127,255,0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
img = 255 - img
img = cv2.dilate(img, element, iterations=3)

done = False

while( not done):
    eroded = cv2.erode(img,element)
    temp = cv2.dilate(eroded,element)
    temp = cv2.subtract(img,temp)
    skel = cv2.bitwise_or(skel,temp)
    img = eroded.copy()

    zeros = size - cv2.countNonZero(img)
    if zeros==size:
        done = True

rawDescription: Problems during Skeletonization image for extracting contours


code: match = re.match(r"f?noi(\w+)[kv](\w*)", j)

rawDescription: Regular expression match a or b pattern

description: Regular expression match a or b pattern


code: [i for i in _ if i != 0]

rawDescription: Python strptime takes weekday name and returns tm_mday = 1 regardless of actual mday


code:
from collections import defaultdict

dataset = [('121', set(['NY'])), ('132', set(['CA', 'NY'])), ('198', set(['NY'])), ('676', set(['NY'])), ('89', set(['NY', 'CA']))]
output = defaultdict(list)
for value, key in dataset:
    output[frozenset(key)].append(value)

rawDescription: How do I convert a list of tuples with sets to a dictionary?

description: Convert a list of tuples with sets to a dictionary


code: e = projectile(self.canvas, self.projectiles)

rawDescription: Removing and deleting appended object - python


code: ';'.join(encode(i) for i in result)

rawDescription: Iterating through a list in Python

description: Iterating through a list in Python


code:
import matplotlib.pyplot as plt

def main():
    fig = plt.figure()
    plt.subplots_adjust(top=0.85) # use a lower number to make more vertical space
    plt.bar([1,2],[5,4])
    fig.canvas.mpl_connect('draw_event', on_draw)
    plt.title('this is a very long title and therefore it gets cropped which is an unthinkable behaviour as it loses the information in the title')
    plt.savefig('./test.png')

def on_draw(event):
    """Auto-wraps all text objects in a figure at draw-time"""
    import matplotlib as mpl
    fig = event.canvas.figure

    # Cycle through all artists in all the axes in the figure
    for ax in fig.axes:
        for artist in ax.get_children():
            # If it's a text artist, wrap it...
            if isinstance(artist, mpl.text.Text):
                autowrap_text(artist, event.renderer)

    # Temporarily disconnect any callbacks to the draw event...
    # (To avoid recursion)
    func_handles = fig.canvas.callbacks.callbacks[event.name]
    fig.canvas.callbacks.callbacks[event.name] = {}
    # Re-draw the figure..
    fig.canvas.draw()
    # Reset the draw event callbacks
    fig.canvas.callbacks.callbacks[event.name] = func_handles

def autowrap_text(textobj, renderer):
    """Wraps the given matplotlib text object so that it exceed the boundaries
    of the axis it is plotted in."""
    import textwrap
    # Get the starting position of the text in pixels...
    x0, y0 = textobj.get_transform().transform(textobj.get_position())
    # Get the extents of the current axis in pixels...
    clip = textobj.get_axes().get_window_extent()
    # Set the text to rotate about the left edge (doesn't make sense otherwise)
    textobj.set_rotation_mode('anchor')

    # Get the amount of space in the direction of rotation to the left and
    # right of x0, y0 (left and right are relative to the rotation, as well)
    rotation = textobj.get_rotation()
    right_space = min_dist_inside((x0, y0), rotation, clip)
    left_space = min_dist_inside((x0, y0), rotation - 180, clip)

    # Use either the left or right distance depending on the horiz alignment.
    alignment = textobj.get_horizontalalignment()
    if alignment is 'left':
        new_width = right_space
    elif alignment is 'right':
        new_width = left_space
    else:
        new_width = 2 * min(left_space, right_space)

    # Estimate the width of the new size in characters...
    aspect_ratio = 0.5 # This varies with the font!!
    fontsize = textobj.get_size()
    pixels_per_char = aspect_ratio * renderer.points_to_pixels(fontsize)

    # If wrap_width is < 1, just make it 1 character
    wrap_width = max(1, new_width // pixels_per_char)
    try:
        wrapped_text = textwrap.fill(textobj.get_text(), wrap_width)
    except TypeError:
        # This appears to be a single word
        wrapped_text = textobj.get_text()
    textobj.set_text(wrapped_text)

def min_dist_inside(point, rotation, box):
    """Gets the space in a given direction from "point" to the boundaries of
    "box" (where box is an object with x0, y0, x1, & y1 attributes, point is a
    tuple of x,y, and rotation is the angle in degrees)"""
    from math import sin, cos, radians
    x0, y0 = point
    rotation = radians(rotation)
    distances = []
    threshold = 0.0001
    if cos(rotation) > threshold:
        # Intersects the right axis
        distances.append((box.x1 - x0) / cos(rotation))
    if cos(rotation) < -threshold:
        # Intersects the left axis
        distances.append((box.x0 - x0) / cos(rotation))
    if sin(rotation) > threshold:
        # Intersects the top axis
        distances.append((box.y1 - y0) / sin(rotation))
    if sin(rotation) < -threshold:
        # Intersects the bottom axis
        distances.append((box.y0 - y0) / sin(rotation))
    return min(distances)

if __name__ == '__main__':
    main()

rawDescription: my matplotlib title gets cropped

description: My matplotlib title gets cropped


code:
self._action_group.add_actions([("ExamplePy", None, _("Clear document"),
        "<control>r", _("Clear the document"), # <- here
        self.on_clear_document_activate)])

rawDescription: How to add keyboard shortcuts / accelerator keys for a menu item created by a Gedit plugin

description: Add keyboard shortcuts / accelerator keys for a menu item created by a Gedit plugin


rawDescription: 3D distance vectorization

description: 3D distance vectorization


code:
previous = (df.day.diff() * df['value'].shift())
previous

rawDescription: Pandas create time series from day counts


code:
chars = {}
with open("B") as lookupfile:
    for number,line in enumerate(lookupfile):
        chars[line.strip()] = number

rawDescription: Python string comparison whilst in loop

description: Python string comparison whilst in loop


code:
import sys

mod = sys.modules[cls.__module__]

rawDescription: How to get a reference to the module of a class

description: Get a reference to the module of a class