rawDescription: How to check task status in Celery?

description: Check task status in Celery


code:
import csv
import tempfile
import shutil

filename = 'distMatrix.csv'
with open(filename, 'rb') as f, tempfile.NamedTemporaryFile(mode='wb', delete=False) as g:
    writer = csv.writer(g)
    for row in csv.reader(f):
        row = [element if int(element) < 10**6 else 0 for element in row]
        writer.writerow(row)

shutil.move(g.name, filename)

rawDescription: Python CSV edit fields with numbers greater than a specific number


code:
variable = ""
value = ""
r = ""
for key in form.keys():
        variable = str(key)
        value = str(form.getvalue(variable))
        r += "
"+ variable +", "+ value +"
\n"

fields = "
"+ str(r) +"
"

rawDescription: How to get form field names and values in Python?

description: Get form field names and values in Python


code:
import os, os.path

# Taken from http://stackoverflow.com/a/600612/119527
def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else: raise

def safe_open_w(path):
    ''' Open "path" for writing, creating any parent directories as needed.
    '''
    mkdir_p(os.path.dirname(path))
    return open(path, 'w')

with safe_open_w('/Users/bill/output/output-text.txt') as f:
    f.write(...)

rawDescription: Python: write file to directory doesn't exist


code:
setA = set(listA)
setB = set(listB)
setA.intersection(setB)

rawDescription: Optimal and efficient way to examine python lists


code:
from datetime import datetime
class EqualsAnyDatetime(datetime):
    def __eq__(self, other):
        return isinstance(other, datetime)

now = datetime.now()
any_datetime = EqualsAnyDatetime(1970, 1, 1)
now == any_datetime
any_datetime == now
now.__eq__(any_datetime)

rawDescription: Getting more control over the rich comparison operators in python2


rawDescription: Looping over list of lists (nested for-loops) doesnt work as I want it to


code:
weights = g.es["weight"]
line_graph_edges = []
for v in xrange(g.vcount()):
    incoming = g.incident(v, mode="in")
    outgoing = g.incident(v, mode="out")
    line_graph_edges.extend((e1, e2) for e1 in incoming for e2 in outgoing
        if weights[e1] < weights[e2])
line_graph = Graph(g.ecount(), line_graph_edges)

rawDescription: Line graph of a multigraph

description: Line graph of a multigraph


code:
import os
from win32com.client import GetObject

os.startfile(r'C:\path\to\ReutersExcel.exe')
xlApp = GetObject(None, 'Excel.Application')

rawDescription: Access data in Excel - Reuter from python


rawDescription: get index of character in python list

description: Get index of character in python list


code: items = Item.objects.all().annotate(null_position=Count('position')).order_by('-null_position', 'position')

rawDescription: Nested serializer ordering when there is no object


code:
import collections

d = {
    u'csrfmiddlewaretoken': [u'fhvpUorGAl7LMv4JIJRd0WOEHPkKn6iN'],
    u'actor_1': [u'first_actor'],
    u'actor_2': [u'fourth_actor']
}

collections.OrderedDict(sorted(d.items()))

rawDescription: How to sort keys of a dictionnary posted in url?

description: Sort keys of a dictionnary posted in url


code:
import compiler
eq= "sin(x)*x**2"
ast= compiler.parse( eq )

rawDescription: Equation parsing in Python

description: Equation parsing in Python


code:
import os
import sys
topdir = os.path.join(os.path.dirname(__file__), "..")
sys.path.append(topdir)

rawDescription: flask module import failure from test folder

description: Flask module import failure from test folder


rawDescription: python string substitution

description: Python string substitution


rawDescription: checking diagonals in 2d list (Python)

description: Checking diagonals in 2d list (Python)


code:
return [FormRequest.from_response(response,
            formdata={'search': 'you\'re search string'},
            callback=self.parse)]

rawDescription: How to crawl links to a particular domain by searching on Google?

description: Crawl links to a particular domain by searching on Google


code:
docfile = request.FILES['docfile']
filename = os.path.splitext(docfile.name)[0]
newfilename = 'ok_%s.txt' % filename

rawDescription: Python get file name and change & save it in variable


code: biggrasstile = pygame.transform.scale(grasstile, (16, 16))

rawDescription: How can I increase the size of a sprite inpygame?

description: Increase the size of a sprite inpygame


code:
import unittest
import HTMLTestRunner

class DynamicClassBase(unittest.TestCase):
    longMessage = True

def make_test_function(description, a, b):
    def test(self):
        self.assertEqual(a, b, description)
    return test

def main():
    tests_classes = []   # container for generated test classes
    testsmap = {
        'foo': [1, 1],
        'bar': [1, 2],
        'baz': [5, 5]}

    for name, params in testsmap.iteritems():
        test_func = make_test_function(name, params[0], params[1])
        klassname = 'Test_{0}'.format(name)
        globals()[klassname] = type(klassname,
                                    (DynamicClassBase,),
                                    {'test_gen_{0}'.format(name): test_func})
        test_classes_to_run.append(globals()[klassname])

    # solution starts here:
    loader = unittest.TestLoader()
    suites_list = []
    for test_class in test_classes_to_run:
        suite = loader.loadTestsFromTestCase(test_class)
        suites_list.append(suite)

    big_suite = unittest.TestSuite(suites_list)
    with open('results.html', 'w') as html_file:
        runner = HTMLTestRunner.HTMLTestRunner(stream=html_file,
                                           verbosity=2,
                                           title='demo title',
                                           description='demo descr')
        runner.run(big_suite)

if __name__ == '__main__':
    main()

rawDescription: Creating html results from tests generated dynamically


code:
import fractions
fractions.gcd(100, fractions.gcd(10, 20))
10

rawDescription: most efficient way find the greatest common factor of 3 numbers?

description: Most efficient way find the greatest common factor of 3 numbers


code: import collections; hasattr(collections, "MutableMapping")

rawDescription: Problems with vim and conque gdb plugin

description: Problems with vim and conque gdb plugin


code:
class A(object):

  def __init__(self):
    self.logger = logging.LoggerAdapter(log, {'session_id': random(1024)})

  def process(self):
    self.logger.info('hello')

rawDescription: Is it possible to inject a variable into python logger Filter


code:
l = list(str)
l[i] = 'e'
str = ''.join(l)

rawDescription: String manipulation in Python

description: String manipulation in Python


code:
def idbuttonclick(self, event):

    self.id_frame.destroy()
    self.id_frame = Frame(self.main_right_frame, borderwidth=5, height=50, background="white")
    self.id_frame.pack(side=TOP, fill=BOTH)

    if (self.gram_option.get()=="+" and
    self.meta_option.get()=="aerobe"):
        Label(self.id_frame, text = "Gram Positive Aerobe", background = "white").pack(side=TOP, anchor = N)

        bac=[('Aeromonas',0.95,0.05),
        ('Bacillus',0.05, 0.95),
        ('Hafnia',0.51, 0.51)]

    else: Label(self.id_frame, text = "Error: Not enough data", background = "white").pack(side=TOP, anchor = N)

    def plus(matrix, i):
        return [row[i] for row in matrix]

    def minus(matrix, i):
        return [1.00-row[i] for row in matrix]

    def average(lst):
        return sum(lst) / len(lst)

    bact=zip(*bac)
    bact2=bact[0:1]
    bact3=bact[0:1]

    if self.cat_option.get()=="+":
        bact2.append(plus(bac,1))
        bact3.append(plus(bac,1))
    if self.cat_option.get()=="--":
        bact2.append(minus(bac,1))
        bact3.append(plus(bac,1))

    if self.oxi_option.get()=="+":
        bact2.append(plus(bac,2))
        bact3.append(plus(bac,2))

    if self.oxi_option.get()=="--":
        bact2.append(minus(bac,2))
        bact3.append(plus(bac,2))

    bac2=zip(*bact2)
    bac3=zip(*bact3)

    #experimental additive probability
    #bac4 = [(bac2[0],reduce(mul,bac2[1:])) for bac2 in bac2]

    #experimental mean probability
    bac4 = [(bac2[0], average(bac2[1:])) for bac2 in bac2]

    #experimental additive probability / expected outcome additive probability
    #bac4 = [(bac2[0],reduce(mul,bac2[1:])/reduce(mul,bac3[1:])) for (bac2,bac3) in zip(bac2,bac3)]

    bac5 = tuple(sorted(bac4, key=lambda item: item[1], reverse=True))

    Label(self.id_frame, text = bac5[0], background = "white").pack(side=TOP, anchor = W)
    Label(self.id_frame, text = bac5[1], background = "white").pack(side=TOP, anchor = W)
    Label(self.id_frame, text = bac5[2], background = "white").pack(side=TOP, anchor = W)
    Label(self.id_frame, text = bac5[3], background = "white").pack(side=TOP, anchor = W)
    Label(self.id_frame, text = bac5[4], background = "white").pack(side=TOP, anchor = W)
    Label(self.id_frame, text = bac5[5], background = "white").pack(side=TOP, anchor = W)
    Label(self.id_frame, text = bac5[6], background = "white").pack(side=TOP, anchor = W)
    Label(self.id_frame, text = bac5[7], background = "white").pack(side=TOP, anchor = W)
    Label(self.id_frame, text = bac5[8], background = "white").pack(side=TOP, anchor = W)
    Label(self.id_frame, text = bac5[9], background = "white").pack(side=TOP, anchor = W)
    Label(self.id_frame, text = bac5[10], background = "white").pack(side=TOP, anchor = W)

rawDescription: How to tie radiobutton selections with array data

description: Tie radiobutton selections with array data


code:
import numpy as np
A = np.array([1, 1, 1])
B = np.array([2, 2, 2])
C = np.array([3, 3, 3])
D = np.vstack((A, B, C))

rawDescription: 2d matrix composed from 1d matrices in python


code:
data = np.random.rand(1000, 3)
import scipy.spatial
kdt = scipy.spatial.cKDTree(data)
k = 5 # number of nearest neighbors
dists, neighs = kdt.query(data, k+1)
avg_dists = np.mean(dists[:, 1:], axis=1)

rawDescription: Vectorised average K-Nearest Neighbour distance in Python


code:
for n in range(0, len(keys) - 1,2):
    plt.subplot(len(keys)//2, 1, i)
    gn, = plt.plot(horas, diccionario[keys[n]], 'ro-')
    gn1, = plt.plot(horas, diccionario[keys[n+1]], 'g*-')
    plt.legend([gn, gn1], [keys[n], keys[n+1]])
    i+=1

rawDescription: matplotlib subplot not working as expected

description: Matplotlib subplot not working as expected


code:
def post(self, request, *args, **kwargs):
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    if form.is_valid():
        return self.form_valid(form)

rawDescription: Is the form in create view already bound?


code:
def encrypt(encryptString, shift):
    shift = shift % 26 + 26
    stringList = list(encryptString)
    for eachCharacter in stringList:
        if eachCharacter.isalpha() == True:
            if eachCharacter.isupper() == True:
                eachCharacter = chr( ( ord('A') + ord(eachCharacter) - ord('A') + shift) % 26)
            else:
                eachCharacter = chr( ( ord('a') + ord(eachCharacter) - ord('a') + shift) % 26)

    encryptString = ''.join(stringList)
    return encryptString

rawDescription: Python string concatation for Caesar cipher, comparable with Java code


code:
from bs4 import BeautifulSoup
from collections import namedtuple
import csv
from itertools import tee, izip
import os, os.path
import re

DIR       = r'C:\Users\Documents\Congressional Hearings\NHTF Project\Test Set'
HARD_WRAP = re.compile(r'\n(?!    )')
SPEAKERS  = re.compile(r'^    (Mr.|Mrs.|Congressman|Congresswoman|Chairman|Chairwoman) ([a-zA-Z \-]{2,40})\.', re.MULTILINE)
NAME      = lambda m: '{0} {1}'.format(*m.groups())
Speaker   = namedtuple('Speaker', ['name', 'name_start', 'name_end'])

def load_hearing_response(fname, split_on='    Present:'):
    with open(fname, 'rU') as inf:
        html = inf.read()
    txt  = BeautifulSoup(html).get_text()
    return txt.rsplit(split_on, 1)[-1]     # return everything after last occurrence of split_on

def un_hard_wrap(txt, reg=HARD_WRAP):
    return reg.sub('', txt)

def pairwise(iterable):
    a,b = tee(iterable)
    next(b, None)
    return izip(a, b)

def get_speeches(txt):
    speakers = [Speaker(NAME(sp), sp.start(), sp.end()) for sp in SPEAKERS.finditer(txt)]
    speakers.append(Speaker('', len(txt), None))    # tail sentinel for pairwise processing
    return [(this.name, txt[this.name_end:nxt.name_start]) for this,nxt in pairwise(speakers)]

def write_csv(fname, data, header=None):
    with open(fname, 'wb') as outf:
        out_csv = csv.writer(outf)
        if header is not None:
            out_csv.writerow(header)
        out_csv.writerows(data)

def main():
    # get text of Congressional hearing responses
    txt = load_hearing_response(os.path.join(DIR, 'CHRG-107hhrg70750.htm'))
    txt = un_hard_wrap(txt)
    # break into speeches
    speeches = get_speeches(txt)
    # write (speaker, speech) pairs to a .csv file
    write_csv(os.path.join(DIR, 'CHRG-107hhrg70750.csv'), speeches, ['Speaker', 'Speech'])
    # write paragraphs of speeches to a .csv file
    paragraphs = ([para.strip()] for speaker,speech in speeches for para in speech.split('\n') if para.strip())
    write_csv(os.path.join(DIR, 'Paragraphs.csv'), paragraphs, ['Paragraphs'])

if __name__=="__main__":
    main()

rawDescription: Type Error when running a large function in Python


rawDescription: Numpy multiply multiple columns by scalar


code:
import time
import subprocess
def time_time():
    t1 = time.time()
    subprocess.call(['python', 'a.py'])
    return time.time() - t1

def time_clock():
    t1 = time.clock()
    subprocess.call(['python', 'a.py'])
    return time.clock() - t1

time_time()
time_clock()

rawDescription: Use python to test the load time of windows applications


code:
@app.context_processor
def inject_user():
    return {
        'my_stuff': do_stuff(request.url)
    }

rawDescription: Run jinja2 template_filter on every request using Flask


code:
#!/usr/bin/env python
"""
matplotlib gives you 4 ways to specify colors,

    1) as a single letter string, ala MATLAB

    2) as an html style hex string or html color name

    3) as an R,G,B tuple, where R,G,B, range from 0-1

    4) as a string representing a floating point number
       from 0 to 1, corresponding to shades of gray.

See help(colors) for more info.
"""
from pylab import *

subplot(111, axisbg='darkslategray')
#subplot(111, axisbg='#ababab')
t = arange(0.0, 2.0, 0.01)
s = sin(2*pi*t)
plot(t, s, 'y')
xlabel('time (s)', color='r')
ylabel('voltage (mV)', color='0.5') # grayscale color
title('About as silly as it gets, folks', color='#afeeee')
show()

rawDescription: How to change the face color of a plot using Matplotlib

description: Change the face color of a plot using Matplotlib


rawDescription: Reshuffle numpy array based on indices in a second array


code:
from itertools import product
list(product(['+','-','*'],repeat=4))

rawDescription: Python: itertools for generating this combination?


code: r = r.decode('cp1252').encode('utf8')

rawDescription: Why is my urllib.quote in python encoding from Win-1252 instead of UTF-8 for CSV file?


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

def func(x):
    return (x-0.5)**2

start = 0
end = 1
npoints = 100

x = np.linspace(start,end,npoints)
fx = func(x)

# take density (or intervals) as inverse of fx
# g in [0,1] controls how much warping you want.
# g = 0: fully warped
# g = 1: linearly spaced
g = 0
density = (1+g*(fx-1))/fx

# sum the intervals to get new grid
x_density = np.cumsum(density)
# rescale to match old range
x_density -= x_density.min()
x_density/= x_density.max()
x_density *= (end-start)
x_density += start

fx_density = func(x_density)

plt.plot(x,fx,'ok',ms = 10,label = 'linear')
plt.plot(x_density,fx_density,'or',ms = 10,label = 'warped')
plt.legend(loc = 'upper center')

plt.show()

rawDescription: Numpy: Generate grid according to density function


code:
class Part(db.Model):
  # ...
  date_checked = db.column_property(
        db.select([db.func.min(PartHistory.date_checked)]).\
            where(PartHistory.part_id==id).\
            correlate_except(PartHistory)
    )

rawDescription: Display first element of a one-to-many relationship in Flask-Admin


code:
from progressbar import *
import time

widgets = [FormatLabel(''), ' ', Percentage(), ' ', Bar('/'), ' ', RotatingMarker()]
progressbar = ProgressBar(widgets=widgets, maxval=10)
progressbar.start()
for i in range(0, 11):
    widgets[0] = FormatLabel('<filename-{0}>'.format(i))
    progressbar.update(i)
    time.sleep(.5)
progressbar.finish()

rawDescription: Python Progressbar (PyPi) - display custom text that changes with update()


code:
import numpy.distutils.system_info as sysinfo
sysinfo.show_all()

rawDescription: How can I check if my installed numpy is compiled with SSE/SSE2 instruction set?

description: Check if my installed numpy is compiled with SSE/SSE2 instruction set


code:
from tkinter import messagebox, Tk, Menu, ttk

news = ['Mid Day News', 'Evening News']
features = ['Calling Farmers', 'Round About Ja', 'You and the Law', 'Get the Facts',
            'Career Talk', 'Economy and you', 'Arts Page', 'Tourism Roundup',
            'Jeep','Jamaica Promise', 'House Matters', 'Jamaica House Weekly']
features.sort()

class CustomMenu(object):
    def __init__(self, root, values=[], combo_placement=(0, 0), button_placement=(0, 0), label_placement=(0, 0)):
        self.frame = root
        self.combobox = ttk.Combobox(self.frame, values=values)
        self.combobox.bind("<<>ComboboxSelected>")
        self.combobox.grid(row=combo_placement[0], column=combo_placement[1])
        self.label = ttk.Label(self.frame, textvariable=self.combobox.get())
        self.label.grid(row=label_placement[0], column=label_placement[1])
        self.button = ttk.Button(self.frame, text="Add", command=self.update_popup)
        self.button.grid(row=button_placement[0], column=button_placement[1])

    def update_popup(self):
        messagebox.showinfo(
            title="File update",
            message="{} has been added".format(self.combobox.get())
        )

root = Tk()
root.title('Feature Tracking')
root.geometry('255x425')

update_frame = ttk.Frame(root, padding=(5,10))
def show_update_frame():
    update_frame.grid(row=0, column=0)

#Update Menu Frame
features_frame = CustomMenu(update_frame, features, (1, 0), (3, 0), (0, 0))
news_frame = CustomMenu(update_frame, news, (4, 0), (5, 0), (6, 0))

#Menu bar with menu options
menubar = Menu(root)

#Update Menu
filemenu = Menu(menubar, tearoff = 0)
filemenu.add_command(label='New', command=show_update_frame)
menubar.add_cascade(label='Update', menu=filemenu)

root.config(menu = menubar)

root.mainloop()

rawDescription: How to get the Combo Box Value

description: Get the Combo Box Value


code: [dict(foo) for foo in Bar.objects.all()]

rawDescription: Cqlengine queries: how to return dictionary?


rawDescription: Python: Combining regular expression groups into one inside a non-grouping version of regular parentheses


code:
from smtplib import SMTP_SSL as SMTP
import logging, logging.handlers, sys
from email.mime.text import MIMEText

def send_message():
    text = '''
            Hello,

            This is an example of how to use email in Python 3.

            Sincerely,

            My name
            '''
    message = MIMEText(text, 'plain')
    message['Subject'] = "Email Subject"
    my_email = 'your_address@email.com'

    # Email that you want to send a message
    message['To'] = my_email

    try:
        # You need to change here, depending on the email that you use.
        # For example, Gmail and Yahoo have different smtp. You need to know what it is.
        connection = SMTP('smtp.email.com')
        connection.set_debuglevel(True)

        # Attention: You can't put for example: 'your_address@email.com'.
        #            You need to put only the address. In this case, 'your_address'.
        connection.login('your_address', 'your_password')

        try:
            #sendemail(<from address>, <to address>, <message>)
            connection.sendmail(my_email, my_email, message.as_string())
        finally:
            connection.close()
    except Exception as exc:
        logger.error("Error sending the message.")
        logger.critical(exc)
        sys.exit("Failure: {}".format(exc))

if __name__ == "__main__":
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    send_message()

rawDescription: Python 3: sending emails through any online webmail service


code: cursor.execute("call procedure('%s');" % variable )

rawDescription: how can i pass a value of variable defined in python to a procedure in mysql as an input?

description: Pass a value of variable defined in python to a procedure in mysql as an input


code:
class Vector2D():
    # Magic methods here...

    @staticmethod
    def dot_product(a, b):
        return a[0]*b[1] + a[1]*b[0]

rawDescription: Python decorator that makes OOP code FP; good or bad idea?


code:
v1 = df1.reindex(columns=['a', 'b', 'c']).values
v2 = df2.reindex(columns=['e', 'd', 'f']).values
rs = DataFrame(v1 / v2, index=v1.index, columns=['a', 'b', 'c'])

rawDescription: How can I multiply two dataframes with different column labels in pandas?

description: Multiply two dataframes with different column labels in pandas


rawDescription: How can I impose the total number of digits in python (new formatting)

description: Impose the total number of digits in python (new formatting)


code:
# Return the longest prefix of all list elements.
def commonprefix(m):
    "Given a list of pathnames, returns the longest common leading component"
    if not m: return ''
    s1 = min(m)
    s2 = max(m)
    for i, c in enumerate(s1):
        if c != s2[i]:
            return s1[:i]
    return s1

rawDescription: Python: Determine prefix from a set of (similar) strings


code:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[],
                 title="Vereinfachtes Kraftwerksmodell")
sankey = Sankey(ax=ax, unit=None)
sankey.add(flows=[1.0, -0.3, -0.1, -0.1, -0.5],
       pathlengths = [0.5,0.06,0.5,0.5,0.375],
       labels=['P$el$', 'Q$ab,vd$', 'P$vl,vd$', 'P$vl,mot$', ''],
       label='Laden',
       orientations=[0, -1, 1, 1, 0])
sankey.add(flows=[0.5, 0.1, 0.1, -0.1, -0.1, -0.1, -0.1, -0.3], fc='#37c959',
       label='Entladen',
       labels=['P$mech$', 'Q$zu,ex$', 'Q$zu,rekup$', 'P$vl,tb$', 'P$vl,gen$',                'Q$ab,tb$', 'Q$ab,rekup$', 'P$nutz$'],
       orientations=[0, -1, -1, 1, 1, -1, -1, 0], prior=0, connect=(4, 0))
sankey.add(flows=[-0.1, 0.1],
       label='Rekuperator',
       #labels=['bla'],
       orientations=[1,1], prior=1, connect=(2, 0))
diagrams = sankey.finish()
diagrams[-1].patch.set_hatch('/')
plt.legend(loc='lower right')
plt.show()

rawDescription: Connecting flows in matplotlib sankey diagram


code:
import re
string = "(src://path/to/foldernames canhave spaces/file.xzy)"
string2 = \
'(src://path/to/foldernames canhave spaces/file.xzy "optional string")'
re.findall(r'\((.*?)( ".*")?\)', string2)
re.findall(r'\((.*?)( ".*")?\)', string)

rawDescription: python re, find expression containing an optional group

description: Python re, find expression containing an optional group


rawDescription: What's a convenient way of resolving a path /bar/foo/baz/../.. into /bar?


code:
import threading

# ... your code here...

def run_while_true(server_class=BaseHTTPServer.HTTPServer,
               handler_class=BaseHTTPServer.BaseHTTPRequestHandler):

    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    while keep_running():
        httpd.handle_request()

if __name__ == '__main__':
    background_thread = threading.Thread(target=do_something_else)
    background_thread.start()
    # ... web server start code here...
    background_thread.join()

rawDescription: Python Web Server - Getting it to do other tasks


code:
mymenu = QtGui.QMenu("Menu")

mymenu.clear()

rawDescription: PyQt Clear the menubar

description: PyQt Clear the menubar


code:
from psychopy import visual
win = visual.Window(screen=1)

rawDescription: Pyschopy Script That Uses Primary Display Monitor


code:
def magic(curwords=None):
  if curwords is None: curwords = []
  # ...

rawDescription: Python old values reappearing

description: Python old values reappearing


code:
def load():
    return some_huge_data_structure

def process(ds):
    do_whatever_to(ds)

process(load())  # after this, the huge DS will be gone

rawDescription: Should I interfere the normal Python garbage collection process


code:
import numpy, scipy.sparse
A = numpy.array([[0,1,0],[0,0,0],[1,0,0]])
Asp = scipy.sparse.csr_matrix(A)
Asp

rawDescription: numpy array to scipy.sparse matrix

description: Numpy array to scipy.sparse matrix


code: sum(val for row in matrix for val in row)

rawDescription: Find summary of values contained in a matrix in python3


code:
sys.path[0:0] = ['/usr/lib64/python2.6/site-packages/mpich2']
import mpi4py

rawDescription: how to import the correct module where the name exists multiple times in site-packages

description: Import the correct module where the name exists multiple times in site-packages


code:
offscreen_window = Gtk.OffscreenWindow()
offscreen_window.add(widget_that_needs_screenshotting)
pixbuf = offscreen_window.get_pixbuf()

rawDescription: How do I take a screenshot using GdkPixbuf?

description: Take a screenshot using GdkPixbuf


code:
import matplotlib.pyplot as pyplot
from matplotlib.font_manager import FontProperties

if __name__ == "__main__":
    pyplot.figure()
    prop = FontProperties()
    prop.set_file('STIXGeneral.ttf')
    pyplot.xlabel(u"\u2736", fontproperties=prop)
    pyplot.show()

rawDescription: How to use unicode symbols in matplotlib?

description: Use unicode symbols in matplotlib


code:
class MyChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return my_fun(obj)

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "my_field":
            kwargs["form_class"] = MyChoiceField
            return db_field.formfield(**kwargs)
        return super(MyModelAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs)

rawDescription: How to override ModelChoiceField template?

description: Override ModelChoiceField template


rawDescription: 3 dimensional matrix addition

description: 3 dimensional matrix addition


code: sum(A[index] for index in patternDict[5])

rawDescription: Finding values of patterns in an array

description: Finding values of patterns in an array


code:
import wx

########################################################################
class NoSystemMenuFrame(wx.Frame):
    """
    There is no system menu, which means the title bar is there, but
    no buttons and no menu when clicking the top left hand corner
    of the frame
    """

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        no_sys_menu = wx.CAPTION
        wx.Frame.__init__(self, None, title="No System Menu", style=no_sys_menu)
        panel = wx.Panel(self)
        self.Show()

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

rawDescription: WxPython - How to hide the X and expand button on window


rawDescription: How to combine Pandas Series

description: Combine Pandas Series


code:
def time_to_int(time):
    mins,secs = time.split(':')
    return int(mins)*60 + int(secs)

def line_to_tuple(line):
    return tuple(time_to_int(t) for t in line.split())

natimes = [line_to_tuple(line) for line in sys.stdin]

rawDescription: Modifying tuples within list

description: Modifying tuples within list


code:
import os
os.environ['GDAL_LIBRARY_PATH'] = '/home/user123/lib/libgdal.so'
from osgeo import gdal
print(gdal.VersionInfo())

rawDescription: Can I set the library path inside a Python script?

description: Set the library path inside a Python script


code:
h4s = soup.find_all("h4", class_="actorboxLink")
for h4 in h4s:
    for text in h4.find_next_siblings(text=True):
        print(text.strip())

rawDescription: BeautifulSoup - how to extract text without opening tag and before <br> tag?


rawDescription: Python Plot Regression

description: Python Plot Regression


code:
import urlparse
access_token = urlparse.parse_qs(urlparse.urlsplit(url).fragment).get('access_token')

rawDescription: How to parse the hashed arguments (with # instead of ?) in url in GAE with python?

description: Parse the hashed arguments (with # instead of ?) in url in GAE with python


code:
import os
import re

# Fetch all hashes and counts
file_c = open('num.txt')
file_c = file_c.read()
lines = re.findall(r'\w+\.txt \d+', file_c)
numbers = {}

for line in lines:
    line_split = line.split('.txt ')
    hash_name = line_split[0]
    count = line_split[1]

    numbers[hash_name] = count

#print(numbers)

# The input file
file_i = open('input.txt')
file_i = file_i.read()

for hash_name, count in numbers.iteritems():
    regex = '(' + hash_name.strip() + ')'
    result = re.findall(r'>.*\|(' + regex + ')(.*?)>', file_i, re.S)

    if len(result) > 0:
        data_original = result[0][2]
        stripped_data = result[0][2][int(count):]

        file_i = file_i.replace(data_original, '\n' + stripped_data)

        #print(data_original)
        #print(stripped_data)

#print(file_i)

# Write the input file to new input_new.txt
f = open('input_new.txt', 'wt')
f.write(file_i)

rawDescription: Cutting character values according to value from file


code:
import pyglet

window = pyglet.window.Window( resizable=True )

@window.event
def on_resize( width, height ):
    ratio = 9/16
    window.set_size( width, width*ratio )

@window.event
def on_draw():
    window.clear()

pyglet.app.run()

rawDescription: Locking the size of a resizable window to the original aspect ratio of the window in Pyglet


code:
# imagine you have a function that takes a day to complete.
cache.set('very_expensive_homepage_logic', takes_a_day_to_calculate())

# now if you call get() with your key, it will be returned and you won't have to wait a day to calculate.
cache.get('very_expensive_homepage_logic')

rawDescription: what's differece between the django's cache ?the The per-site cache,The per-view cache,Specifying per-view cache and Template fragment caching

description: What's differece between the django's cache ?the The per-site cache,The per-view cache,Specifying per-view cache and Template fragment caching


code:
dataset = [0,1,2,3]
var = ['a', 'b', 'c']

data = {}
for set in datasets:
    data[set] = {}
    for type in var:
        data[set][type] = read_hdf5(set, type)

rawDescription: How to read data and create a dictionary of dictionaries in Python?

description: Read data and create a dictionary of dictionaries in Python


code:
widget.connect("button_press_event", on_button_press)

def on_button_press(widget, event):
    popup = get_popup_menu() # acquire your popup menu somehow
    popup.popup(None, None, None, event.button, event.time)

rawDescription: Popup menu for gtk+ application on GtkViewTree


code:
df.iloc[0]
df.iloc[:1]

rawDescription: Cleanest iteration/functional application on Pandas Dataframe regardless of length


code:
import re

s = 'XYZQUACKESTARNFSDMADESBHSCHILDABCD'
matches = re.findall('QUACK|TAR|MAD|CHILD',s)
non_matches = re.split('QUACK|TAR|MAD|CHILD',s)
'-'.join(["{}-({})".format(matches[i], len(non_matches[i+1])) for i in range(len(matches))])
#'QUACK-(2)-TAR-(4)-MAD-(5)-CHILD-(4)'

rawDescription: How can you get the indices from a regular expression match?

description: Get the indices from a regular expression match


rawDescription: pandas dataframe computation between columns

description: Pandas dataframe computation between columns


code:
import numpy as np
from scipy.optimize import leastsq
import pylab as plt

N = 1000 # number of data points
t = np.linspace(0, 4*np.pi, N)
data = 3.0*np.sin(t+0.001) + 0.5 + np.random.randn(N) # create artificial data with noise

guess_mean = np.mean(data)
guess_std = 3*np.std(data)/(2**0.5)
guess_phase = 0

# we'll use this to plot our first estimate. This might already be good enough for you
data_first_guess = guess_std*np.sin(t+guess_phase) + guess_mean

# Define the function to optimize, in this case, we want to minimize the difference
# between the actual data and our "guessed" parameters
optimize_func = lambda x: x[0]*np.sin(t+x[1]) + x[2] - data
est_std, est_phase, est_mean = leastsq(optimize_func, [guess_std, guess_phase, guess_mean])[0]

# recreate the fitted curve using the optimized parameters
data_fit = est_std*np.sin(t+est_phase) + est_mean

plt.plot(data, '.')
plt.plot(data_fit, label='after fitting')
plt.plot(data_first_guess, label='first guess')
plt.legend()
plt.show()

rawDescription: How do I fit a sine curve to my data with pylab and numpy?

description: Fit a sine curve to my data with pylab and numpy


code:
import mechanize

br = mechanize.Browser()
br.open('http://somesite.com/account/signin/')

br.select_form('loginForm')
br['username'] = 'jekyll'
br['password'] = 'bananas'
br.submit()
# At this point, you're logged in, redirected, and the
#  br object has the cookies and all that.

br.geturl() # e.g. http://somesite.com/loggedin/

rawDescription: Using urllib2 for posting data, following redirects and maintaining cookies


code:
m1 = m2 = m3 = m4 = m5 = -1

for i in range(len(df.index)):
    if df.ix[i, 'ema4'] >= df.ix[i, 'ema9']:
        m1 = 1
    ...

rawDescription: IF conditions by pair of conditions

description: IF conditions by pair of conditions


rawDescription: Python parse comma-separated number into int


rawDescription: How to bind a Scrollbar to Canvas when using python TKinter to create GUI?

description: Bind a Scrollbar to Canvas when using python TKinter to create GUI


code:
class SessionLock(object):
    """
    Prevents users from making simultaneous requests.
    """

    def __init__(self):
        if not getattr(settings, 'SESSION_LOCK', True):
            raise MiddlewareNotUsed

        from django.db import connections, DEFAULT_DB_ALIAS
        from django.contrib.sessions.middleware import SessionMiddleware
        self.connections = connections
        self.db_alias = getattr(settings, 'SESSION_LOCK_DB', DEFAULT_DB_ALIAS)

        # Get session initialisation function from session middleware.
        self.load_session = SessionMiddleware.process_request.__func__

    def process_request(self, request):
        # Load the session to retrieve user id from it.
        self.load_session(None, request)

        # Generate a lock id.
        user_id = request.session.get(USER_ID_SESSION_KEY)
        if user_id is not None:
            request.session_lock_id = ('user_lock_%d' % user_id).__hash__()
        else:
            # If user is anonymous then use meta info for identification.
            request.session_lock_id = (
                request.META.get('HTTP_HOST', '') + ':' +
                request.META.get('HTTP_USER_AGENT', '')
            ).__hash__()

        # Acquire the lock.
        cursor = self.connections[self.db_alias].cursor()
        cursor.execute('SELECT pg_advisory_lock(%d)' % request.session_lock_id)

    def process_response(self, request, response):
        self._release_lock(request)
        return response

    def process_exception(self, request, exception):
        self._release_lock(request)

    def _release_lock(self, request):
        if hasattr(request, 'session_lock_id'):
            cursor = self.connections[self.db_alias].cursor()
            cursor.execute('SELECT pg_advisory_unlock(%d)' %
                           request.session_lock_id)

rawDescription: Prevent simultaneous requests from single user in Django on a multi-server setup


code:
import multiprocessing

def process(file):
    pass # do stuff to a file

p = multiprocessing.Pool()
for f in glob.glob(folder+"*.csv"):
    # launch a process for each file (ish).
    # The result will be approximately one process per CPU core available.
    p.apply_async(process, [f])

p.close()
p.join() # Wait for all child processes to close.

rawDescription: Multiprocess multiple files in a list

description: Multiprocess multiple files in a list


code:
for line in file:
    result = re.finditer(regex, line)
    # do something...

rawDescription: findall/finditer on a stream?

description: Findall/finditer on a stream


code:
res = pd.merge(aa, bb, left_on='a', right_on='c', how='inner', left_index=True)
bb['newcolumn']= res.reindex(range(len(aa))).fillna(0)['b']
print(bb)

rawDescription: Iterate over a column in a dataframe matching each value with a value in another column in another dataframe


code:
def percent(alpha, string):
    results = []
    for c in alpha:
        y = [e for e in string if e == c]
        x = len(y)
        results.append((c, round((float(x) / len(string)*100))))
    return results

rawDescription: Finding percentage of nonempty string

description: Finding percentage of nonempty string


code: out = [v for v in inputlist if int(v[3:7]) >= 1990]

rawDescription: Remove element of a list meeting a logical condition in Python


code:
import re
inp = '{responseHeader:{status:0,QTime:94}}'
re.sub(r'([a-zA-Z]+)',r'"\1"',inp)

rawDescription: Replace string with double quotes + string using regex


code:
class YourAdminForm(forms.ModelForm):

    class Meta:
        model = YourModel

    def __init__(self, *args, **kwargs):
        super(YourAdminForm, self).__init__(*args, **kwargs)
        qs = self.fields['your_fk_field'].queryset
        self.fields['your_fk_field'].queryset = qs.filter(is_active=1)

rawDescription: django admin: show list of items filtered

description: Django admin: show list of items filtered


code:
import wx
from wx.lib.delayedresult import startWorker
import array

#=============================================================================
class DrawPanel(wx.Panel):
    """
    Basic panel with graphics drawn in Pain Event
    """
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

    #-------------------------------------------------------------------------
    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        dc.SetBackground(wx.Brush(wx.BLACK))
        dc.Clear()
        w, h = self.GetClientSizeTuple()
        dc.DrawCirclePoint((w / 2, h / 2), 50)

    #-------------------------------------------------------------------------
    def OnSize(self, event):
        self.Refresh()
        self.Update()

    #-------------------------------------------------------------------------
    def OnEraseBackground(self, event):
        pass # Or None

#=============================================================================
class DrawPanelDB(wx.Panel):
    """
    Basic panel with graphics drawn in Pain Event using Double Buffering
    """
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

    #-------------------------------------------------------------------------
    def OnPaint(self, event):
        # Switches the buffers when 'dc' goes out of scope
        dc = wx.BufferedPaintDC(self)
        dc.SetBackground(wx.Brush(wx.BLACK))
        dc.Clear()
        w, h = self.GetClientSizeTuple()
        dc.DrawCirclePoint((w / 2, h / 2), 50)

    #-------------------------------------------------------------------------
    def OnSize(self, event):
        self.Refresh()
        self.Update()

    #-------------------------------------------------------------------------
    def OnEraseBackground(self, event):
        pass # Or None

#=============================================================================
class DrawPanelDBT(wx.Panel):
    """
    Complex panel with its content drawn in another thread
    """
    def __init__(self, *args, **kwargs):
        wx.Panel.__init__(self, *args, **kwargs)

        self.t = None
        self.w, self.h = self.GetClientSizeTuple()
        self.buffer = wx.EmptyBitmap(self.w, self.h)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)

        self.SizeUpdate()

    #-------------------------------------------------------------------------
    def OnPaint(self, event):
        # Just draw prepared bitmap
        wx.BufferedPaintDC(self, self.buffer)

    #-------------------------------------------------------------------------
    def OnSize(self, event):
        self.w, self.h = self.GetClientSizeTuple()
        self.buffer = wx.EmptyBitmap(self.w, self.h)
        self.Refresh()
        self.Update()
        # After drawing empty bitmap start update
        self.SizeUpdate()

    #-------------------------------------------------------------------------
    def OnEraseBackground(self, event):
        pass # Or None

    #-------------------------------------------------------------------------
    def OnTimer(self, event):
        # Start another thread which will update the bitmap
        # But only if another is not still running!
        if self.t is None:
            self.timer.Stop()
            self.t = startWorker(self.ComputationDone, self.Compute)

    #-------------------------------------------------------------------------
    def SizeUpdate(self):
        # The timer is used to wait for last thread to finish
        self.timer.Stop()
        self.timer.Start(100)

    #-------------------------------------------------------------------------
    def Compute(self):
        # Compute Fractal
        MI = 20

        def mapme(x, minimal, maximal, newmin, newmax):
            return(((float(x) - minimal) / (maximal - minimal))
                   * (newmax - newmin) + newmin)

        def compute(x, y):
            z = complex(0, 0)
            c = complex(x, y)
            for i in range(MI):
                z = z**2 + c
                if abs(z) > 2:
                    return i+1
            return 0

        def color(i):
            a = int(mapme(i, 1, MI, 0, 255))
            return(a, a, a)

        def compute_buff(x1, x2, y1, y2, w, h):
            buffer = array.array('B')
            for y in range(h):
                for x in range(w):
                    i = compute(mapme(x, 0, w, x1, x2),
                                mapme(y, 0, h, y2, y1))
                    if i == 0:
                        buffer.extend((255, 255, 255))
                    else:
                        buffer.extend(color(i))
            return buffer

        width, height = self.w, self.h
        x = -0.5
        y =  0.0
        w =  2.4
        h = w * height / width
        data = compute_buff(x - w/2, x + w/2, y - h/2, y + h/2, width, height)
        temp_buffer = wx.BitmapFromBuffer(width, height, data)
        return temp_buffer

    #-------------------------------------------------------------------------
    def ComputationDone(self, r):
        # When done, take bitmap and place it to the drawing buffer
        # Invalidate panel, so it is redrawn
        # But not if the later thread is waiting!
        temp = r.get()
        if not self.timer.IsRunning():
            self.buffer = temp
            self.Refresh()
            self.Update()
        self.t = None

#=============================================================================
class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel = wx.Panel(self)
        self.drawing = DrawPanel(self.panel, size=(300, 300))
        self.drawingDB = DrawPanelDB(self.panel, size=(300, 300))
        self.drawingDBT = DrawPanelDBT(self.panel, size=(300, 300))
        self.sizerPanel = wx.BoxSizer()
        self.sizerPanel.Add(self.panel, proportion=1, flag=wx.EXPAND)
        self.sizerMain = wx.BoxSizer()
        self.sizerMain.Add(self.drawing, 1, wx.ALL | wx.EXPAND, 5)
        self.sizerMain.Add(self.drawingDB, 1, wx.ALL | wx.EXPAND, 5)
        self.sizerMain.Add(self.drawingDBT, 1, wx.ALL | wx.EXPAND, 5)
        self.panel.SetSizerAndFit(self.sizerMain)
        self.SetSizerAndFit(self.sizerPanel)
        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: Draw on image buffer (MemoryDC) in separate thread


code:
d = defaultdict(list)
f = open(file,'r')
start = time()
for line in f:
    NS,domain_list = line.split('|')
    d[NS] = json.loads(domain_list.replace("'", '"'))

for NS, domains in d.items():
    for domain in domains:
        print (NS, domain)

rawDescription: Python: How to reform python list and print them line by line?


code:
import re

# Send request by setting 'stream=True'
r = ses.get(manifest_url, ..., stream=True)

# Fetch filename
d = r.headers['content-disposition']
fname = re.findall("filename=(.+)", d)

# Write content to file
with open(fname, 'wb') as f:
    for chunk in r.iter_content(chunk_size=1024):
        if chunk: # filter out keep-alive new chunks
            f.write(chunk)

rawDescription: Unable to download a file after login using python request


code:
while True:
    x = raw_input("Enter number here (or 'quit' to end): ")
    if x == 'quit':
        break

    # ...

rawDescription: How can I make if-statements recurring until the user types 'quit'?

description: Make if-statements recurring until the user types 'quit'


rawDescription: How to click and verify the existence of a pop up (alert)

description: Click and verify the existence of a pop up (alert)


code:
viewers = [(item['viewer'], item['timestamp']) for item in data]
viewers

rawDescription: Getting all "viewer" and "timestamp" using json


code: ((v, indx) for indx, v in enumerate(I))

rawDescription: 'backwards' enumerate

description: 'backwards' enumerate


code:
def del_env(name):
   key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS)
   DeleteValue(key, name)
   CloseKey(key)
   SendMessage(
        win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')

rawDescription: Deleting a Windows Registry Value with Python


code:
with open("test.txt", "r") as f:
    firstline = f.readline().rstrip("\n")
    secondline = f.readline().rstrip("\n")

firstline = "x=r_[" + firstline + "]\n"
secondline = "y=r_[" + secondline + "]\n"
data = firstline+secondline

with open("test2.txt", "w") as f:  # <-- changed name here, just in case
    f.write(data)

rawDescription: Reading data from file with Python-special format


code:
import sys

from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)

widget = QtGui.QWidget()
widget_layout = QtGui.QHBoxLayout()
widget.setLayout(widget_layout)

def add_group_box():
    group_box = widget.group_box = QtGui.QGroupBox()
    group_layout = QtGui.QVBoxLayout()
    group_box.setLayout(group_layout)

    for i in range(2):
        group_layout.addWidget(QtGui.QRadioButton(str(i)))

    widget_layout.insertWidget(0, group_box)
add_group_box()

show_button = QtGui.QPushButton("show")
hide_button = QtGui.QPushButton("hide")
def on_show():
    if not widget.group_box:
        add_group_box()
def on_hide():
    if widget.group_box:
        widget.group_box.deleteLater()
        widget.group_box = None
show_button.connect(show_button, QtCore.SIGNAL("clicked()"), on_show)
hide_button.connect(hide_button, QtCore.SIGNAL("clicked()"), on_hide)
widget_layout.addWidget(show_button)
widget_layout.addWidget(hide_button)

widget.show()

app.exec_()

rawDescription: PyQt: removeChild/addChild QGroupBox

description: PyQt: removeChild/addChild QGroupBox


code:
df['Date'] = pd.to_datetime(df['Date']) # in case `Date` column is string
i = df.groupby('Ticker')['Date'].idxmax().values
df.loc[i,:]

rawDescription: Python pandas - get index of rows

description: Python pandas - get index of rows


code:
# find the current time
try:
    pagina = urllib.urlopen('http://just-the-time.appspot.com/?f=%Y%m%d,%20seconds%20since%20the%20epoch:%20%t')
    tempo = pagina.read()
    real_time = tempo[35:48]
except IOError:
    exit()

if (time.time() > 1408492800) or (float(real_time) > 1408492800): # 20 August 2014 at 00:00
    disp("License expired!")
else:
    root = Tk()
    app = App(root)
    root.mainloop()

rawDescription: is it secure to use epoch time for expiring license in python?

description: Is it secure to use epoch time for expiring license in python


code:
import sys
sys.executable
import os
os.path.dirname(sys.executable)

rawDescription: Can I find the path of the executable running a python script from within the python script?

description: Find the path of the executable running a python script from within the python script


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

def add_arrow(line,position = None,direction = 'right',size=15,color = None):
   """ add an arrow to a line.

       line: Line2D object
       position: x-position of the arrow. If None, mean of xdata is taken
       direction:  'left' or 'right'
       size:  size of the arrow in fontsize points
       color: if None, line color is taken.
       """
   if color is None:
       color = line.get_color()

   xdata = line.get_xdata()
   ydata = line.get_ydata()

   if position is None:
       position = xdata.mean()
   # find closest index
   start_ind = np.argmin(np.absolute(xdata-position))
   if direction == 'right':
       end_ind = start_ind + 1
   else:
       end_ind = start_ind - 1

   line.axes.annotate('',xytext = (xdata[start_ind],ydata[start_ind]),xy = (xdata[end_ind],ydata[end_ind]),arrowprops=dict(arrowstyle="->",color = color),size = size)

t = np.linspace(-2, 2, 100)
y= np.sin(t)
# return the handle of the line
line = plt.plot(t, y)[0]

add_arrow(line)

plt.show()

rawDescription: Arrow on a line plot with matplotlib

description: Arrow on a line plot with matplotlib


code:
class StreamLogger(object):
    def __init__(self, input_stream, output_logger):
        self.input_stream = input_stream
        self.output_logger
    def run(self):
        while True:
            line = input_stream.readline()
            if not line:
                break
            output_logger.error(line)

rawDescription: How can one use the logging module in python with the unittest module?


rawDescription: Efficiently find row intersections of two 2-D numpy arrays


code:
import json

class Jsonable(object):
    @classmethod
    def from_json(cls, json_string):
        attributes = json.loads(json_string)
        if not isinstance(attributes, dict) or attributes.pop('__class') != cls.__name__:
            raise ValueError
        return cls(**attributes)

rawDescription: Create an object from a JSON file in python (using a classmethod)?


code:
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import FirefoxBinary
import pyvirtualdisplay

with pyvirtualdisplay.Display(visible=True):
    if True:  # Set to False to use Chrome...
        binary = FirefoxBinary()
        driver = webdriver.Firefox(None, binary)
    else:
        driver = webdriver.Chrome()

    driver.get("http://www.google.com")
    driver.quit()

rawDescription: Firefox started by Selenium ignores the display created by pyvirtualdisplay


code:
import urllib
dir(urllib)
import urllib.request
dir(urllib.request)

rawDescription: Missing methods on urllib

description: Missing methods on urllib


code:
def is_head_tag(soup):
    if soup.name == 'head':
        return True
    return False

rawDescription: How to know in what tag my object is currently on?

description: Know in what tag my object is currently on


rawDescription: Pandas - resample a DataFrame by half-hourly frequency


code:
import numpy as np

A = np.array([[0, 1, 0],
              [0, 2, 0],
              [0, 0, 3]])

# the input needs to be an array, since matrices can only be 2D.
B = np.repeat(A[np.newaxis,...], 4, 0)

# for arbitrary input arrays you could do something like:
# B = np.vstack(a[np.newaxis,...] for a in input_arrays)
# but for this to work it will be necessary for each element in
# 'input_arrays' to have the same shape

# eigvals will operate over the last two dimensions of the array and return
# a (4, 3) array of eigenvalues
C = np.linalg.eigvals(B)

# reshape this output so that it matches your original example
C.shape = (2, 2, 3)

rawDescription: Vectorize eigenvalue calculation in Numpy


code: line = line.replace(marker, replacement)

rawDescription: How to replace a current word on a string using python 2.7?

description: Replace a current word on a string using python 2.7


rawDescription: Beautifulsoup text inside tag

description: Beautifulsoup text inside tag


code:
for i, matching in enumerate(sample_json['matchings']):
    # i is your matching's index
    # matching is your current matching object
    my_new_value = 'something'
    sample_json["matchings"][i]["geometry"] = my_new_value

rawDescription: How to update a dict value with Python

description: Update a dict value with Python


code:
import logging
import sys
import traceback
def tracer(func):
    def new_func(*args, **kwargs):
        try:
            traceback.print_stack(sys.stderr)
        except:
            traceback.print_exc(sys.stderr)
        return func(*args, **kwargs)
    return new_func
old_addHandler = logging.root.addHandler
logging.root.addHandler = tracer(old_addHandler)

# run your code

rawDescription: Finding out which module is setting the root logger


code:
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy.linalg import norm

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
origin = np.array([0, 0, 0])
#axis and radius
p0 = np.array([1, 3, 2])
p1 = np.array([8, 5, 9])
R = 5
#vector in direction of axis
v = p1 - p0
#find magnitude of vector
mag = norm(v)
#unit vector in direction of axis
v = v / mag
#make some vector not in the same direction as v
not_v = np.array([1, 0, 0])
if (v == not_v).all():
    not_v = np.array([0, 1, 0])
#make vector perpendicular to v
n1 = np.cross(v, not_v)
#normalize n1
n1 /= norm(n1)
#make unit vector perpendicular to v and n1
n2 = np.cross(v, n1)
#surface ranges over t from 0 to length of axis and 0 to 2*pi
t = np.linspace(0, mag, 100)
theta = np.linspace(0, 2 * np.pi, 100)
#use meshgrid to make 2d arrays
t, theta = np.meshgrid(t, theta)
#generate coordinates for surface
X, Y, Z = [p0[i] + v[i] * t + R * np.sin(theta) * n1[i] + R * np.cos(theta) * n2[i] for i in [0, 1, 2]]
ax.plot_surface(X, Y, Z)
#plot axis
ax.plot(*zip(p0, p1), color = 'red')
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
plt.show()

rawDescription: How to draw a cylinder using matplotlib along length of point (x1,y1) and (x2,y2) with specified radius?

description: Draw a cylinder using matplotlib along length of point (x1,y1) and (x2,y2) with specified radius


code:
def larger_axlim( axlim ):
    """ argument axlim expects 2-tuple
        returns slightly larger 2-tuple """
    axmin,axmax = axlim
    axrng = axmax - axmin
    new_min = axmin - 0.1 * axrng
    new_max = axmax + 0.1 * axrng
    return new_min,new_max
...
ax.set_ylim( larger_axlim( ax.get_ylim() ) )
...

rawDescription: Is there a way to tell matplotlib to loosen the zoom on the plotted data?


code:
(1 == 1) is True
(1 == 0) is False

rawDescription: Is there only one True and one False object in Python?


code:
import os
import subprocess
from xml.sax.saxutils import quoteattr as xml_quoteattr

def DirAsLessXML(path):

    result = '<dir type ={0} name={1} path={2}>\n'.format(xml_quoteattr('dir'),xml_quoteattr(os.path.basename(path)),xml_quoteattr(path))

    list = subprocess.Popen(['find', path,'-maxdepth', '1', '-type', 'd'],stdout=subprocess.PIPE, shell=False).communicate()[0]

    output_list = list.splitlines()
    if len(output_list) == 1:
        result = '<dir type ={0} name={1} path={2}>\n'.format(xml_quoteattr('leaf_dir'),xml_quoteattr(os.path.basename(path)),xml_quoteattr(path))

    for item in output_list[1:]:
        result += '\n'.join('  ' + line for line in DirAsLessXML(item).split('\n'))
    result += '</dir>\n'
    return result

rawDescription: Getting list of sub directories inside a given directory


rawDescription: How do I cause the first row to be selected when using wxPython DataViewCtrl?

description: Cause the first row to be selected when using wxPython DataViewCtrl


code:
def fields(cursor):
    results = {}
    column = 0
    for d in cursor.description:
        results[d[0]] = column
        column = column + 1

    return results

rawDescription: Django psycopg2 template return

description: Django psycopg2 template return


code:
import pylab as plt
import numpy as np

xs = np.linspace(0., 100., 1000.)
data = (xs*0.03 + np.sin(xs) * 0.1) % 1

plt.subplot(2,1,1)
plt.plot(xs, data, "r-")

#Make a masked array with jump points masked
abs_d_data = np.abs(np.diff(data))
mask = np.hstack([ abs_d_data > abs_d_data.mean()+3*abs_d_data.std(), [False]])
masked_data = np.ma.MaskedArray(data, mask)
plt.subplot(2,1,2)
plt.plot(xs, masked_data, "b-")

plt.show()

rawDescription: Plot periodic trajectories

description: Plot periodic trajectories


code:
def get_first_text_part(msg):
    maintype = msg.get_content_maintype()
    if maintype == 'multipart':
        for part in msg.get_payload():
            if part.get_content_maintype() == 'text':
                return part.get_payload()
    elif maintype == 'text':
        return msg.get_payload()

rawDescription: Email body is a string sometimes and a list sometimes. Why?


code:
def get_queryset(self, request):
    qs = super(PostAdmin, self).get_queryset(request)
    if request.user.is_superuser:
        return qs
    return qs.filter(user=request.user)

rawDescription: django admin view and edit only what the user has create

description: Django admin view and edit only what the user has create


code: p = Article.objects.order_by('title', 'pub_date').first()

rawDescription: Django: Get an object form the DB, or 'None' if nothing matches


code:
class Question(models.Model):
    question_package = models.ManyToManyField(QuestionPackage, blank=True)
    name = models.CharField(max_length=128)
    answer = models.TextField()

    class Meta:
        abstract = True

rawDescription: How to show subclass model in Django-admin inline form？

description: Show subclass model in Django-admin inline form？


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2)

df1.plot(ax=axes[0,0])
df2.plot(ax=axes[0,1])
...

rawDescription: How can I plot separate Pandas DataFrames as subplots?

description: Plot separate Pandas DataFrames as subplots


code:
df = pd.DataFrame([[1, 2], [3, np.nan]])
df.isnull().any().any()
np.any(df.isnull())

rawDescription: More idiomatic version of "df.isnull().any().any()" w/ a Pandas DataFrame?


code:
import sys
from PyQt4 import QtCore, QtGui, QtWebKit

class Browser(QtGui.QMainWindow):
    def __init__(self):
        """
            Initialize the browser GUI and connect the events
        """

        QtGui.QMainWindow.__init__(self)
        self.resize(800,600)
        self.centralwidget = QtGui.QWidget(self)

        self.mainLayout = QtGui.QHBoxLayout(self.centralwidget)
        self.mainLayout.setSpacing(0)
        self.mainLayout.setMargin(1)

        self.frame = QtGui.QFrame(self.centralwidget)

        self.gridLayout = QtGui.QVBoxLayout(self.frame)
        self.gridLayout.setMargin(0)
        self.gridLayout.setSpacing(0)

        self.horizontalLayout = QtGui.QHBoxLayout()
        self.tb_url = QtGui.QLineEdit(self.frame)
        self.bt_back = QtGui.QPushButton(self.frame)
        self.bt_ahead = QtGui.QPushButton(self.frame)

        self.bt_back.setIcon(QtGui.QIcon().fromTheme("go-previous"))
        self.bt_ahead.setIcon(QtGui.QIcon().fromTheme("go-next"))

        self.horizontalLayout.addWidget(self.bt_back)
        self.horizontalLayout.addWidget(self.bt_ahead)
        self.horizontalLayout.addWidget(self.tb_url)
        self.gridLayout.addLayout(self.horizontalLayout)

        self.html = QtWebKit.QWebView()
        self.gridLayout.addWidget(self.html)
        self.mainLayout.addWidget(self.frame)
        self.setCentralWidget(self.centralwidget)

        self.connect(self.tb_url, QtCore.SIGNAL("returnPressed()"), self.sparsh)

        self.connect(self.bt_back, QtCore.SIGNAL("clicked()"), self.html.back)
        self.connect(self.bt_ahead, QtCore.SIGNAL("clicked()"), self.html.forward)

        self.default_url = "http://codescience.wordpress.com/"
        self.tb_url.setText(self.default_url)
        self.browse()

    def browse(self):
        """
            Make a web browse on a specific url and show the page on the
            Webview widget.
        """

        url = self.tb_url.text() if self.tb_url.text() else self.default_url
        self.html.load(QtCore.QUrl(url))
        self.html.show()

    def sparsh_timer_callback (self):
        if self.sparsh_index >= len(self.sparsh_urls):
            return
        url = self.sparsh_urls[self.sparsh_index]
        self.html.load(QtCore.QUrl(url))
        self.sparsh_index += 1
        QtCore.QTimer.singleShot(self.sparsh_interval, self.sparsh_timer_callback)

    def sparsh(self):
        self.sparsh_urls=["http://thapar.edu","http://yahoo.com","http://google.com"]
        self.sparsh_index = 0
        self.sparsh_interval = 30000 # 30 seconds

        self.sparsh_timer_callback()
        self.html.show()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    main = Browser()
    main.show()
    sys.exit(app.exec_())

rawDescription: python pyqt4 module not opening just the last website

description: Python pyqt4 module not opening just the last website


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

fig, axes = plt.subplots(nrows=2)

for ax in axes:
    ax.plot(np.random.random(100))

axes[1].autoscale(False)
imdata = np.random.random((10,10))
axes[1].imshow(imdata, aspect='auto', extent=[5, 20, 0.3, 0.8])

plt.show()

rawDescription: pylab subplot bounds altered when overlaying image

description: Pylab subplot bounds altered when overlaying image


rawDescription: Python: Eliminating rows in Pandas DataFrame based on boolean condition


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

M = nr.random((20,20))
ax = plt.imshow(M).get_axes()

ax.annotate('anomaly', xy=(4., 1),  xycoords='data',
                xytext=(50, -120), textcoords='offset points',
                bbox=dict(boxstyle="round", fc="0.8"),
                arrowprops=dict(arrowstyle="->",
                                shrinkA=0, shrinkB=10,
                                connectionstyle="angle,angleA=0,angleB=90,rad=10"),
                )

plt.show()

rawDescription: matplotlib.pyplot.imshow, issue with plt.legend()

description: Matplotlib.pyplot.imshow, issue with plt.legend()


code:
new_dict = dict([(attr,self.__dict__[attr]) for attr in self.__dict__ if self.__dict__[attr]])
return json.dumps(new_dict, default=lambda obj: obj.__dict__, indent=4)

rawDescription: Python to JSON Serialization

description: Python to JSON Serialization


code:
import multiprocessing as mp
import logging
import Queue
import time

logger=mp.log_to_stderr(logging.DEBUG)  # or,
# logger=mp.log_to_stderr(logging.WARN) # uncomment this to silence debug and info messages

def worker(url_queue,seen):
    while True:
        url=url_queue.get()
        if url not in seen:
            logger.info('downloading {u}'.format(u=url))
            seen[url]=True
            # Replace this with code to dowload url
            # urllib2.open(...)
            time.sleep(0.5)
            content=url
            logger.debug('parsing {c}'.format(c=content))
            # replace this with code that finds interesting links and
            # puts them in url_queue
            for i in range(3):
                if content<5:
                    u=2*content+i-1
                    logger.debug('adding {u} to url_queue'.format(u=u))
                    time.sleep(0.5)
                    url_queue.put(u)
        else:
            logger.debug('skipping {u}; seen before'.format(u=url))
        url_queue.task_done()

if __name__=='__main__':
    num_workers=4
    url_queue=mp.JoinableQueue()
    manager=mp.Manager()
    seen=manager.dict()

    # prime the url queue with at least one url
    url_queue.put(1)
    downloaders=[mp.Process(target=worker,args=(url_queue,seen))
                 for i in range(num_workers)]
    for p in downloaders:
        p.daemon=True
        p.start()
    url_queue.join()

rawDescription: Which strategy to use with multiprocessing in python


code:
def voting_plurality(votes):
    party_list = [0, 0, 0, 0]

    for i in range(len(votes)):
        if votes[i] in NAME_TO_INDEX:
            party_list[NAME_TO_INDEX[votes[i]]] += 1

    return(INDEX_TO_NAME[index_to_max(party_list)], party_list)

rawDescription: How would I form this function using the indicies and dictionary


code:
import matplotlib.pyplot as plt
import numpy

STANDARD_DEVIATION_VALUE = 50
DISTRIBUTION_CENTER = 200

def single_num(n):
    # Repeats until a number within the scale is found.
    while 1:
        num = numpy.random.normal(loc=DISTRIBUTION_CENTER, scale=STANDARD_DEVIATION_VALUE)

        if abs(DISTRIBUTION_CENTER-num) <= (STANDARD_DEVIATION_VALUE * n):
            return num

# One standard deviation apart.
lst_of_nums = [single_num(n=1) for _ in xrange(1000000)]

plt.hist(lst_of_nums, bins=100)
plt.xlabel("value")
plt.ylabel("frequency")
plt.show()

rawDescription: Get random numbers within one standard deviation


code:
from datetime import datetime
d = datetime.fromtimestamp(1358294533)
d.isoformat()

rawDescription: converting JSON python time to regular time

description: Converting JSON python time to regular time


code:
lists = []
infile = open('yourfilename.pickle', 'r')
while 1:
    try:
        lists.append(pickle.load(infile))
    except (EOFError, UnpicklingError):
        break
infile.close()

rawDescription: Reading from a file using pickle and for loop in python


rawDescription: Fill NaN in pandas column in both direction


code:
import application
from flask.ext.testing import TestCase

class MyTest(TestCase):

    def create_app(self):
        application.app.config['TESTING'] = True
        application.app.config['WTF_CSRF_ENABLED'] = False
        return application.app

    def setUp(self):
        self.app = application.app.test_client()

    def test_home(self):
        mock_service = mock.MagicMock()
        application.views.some_service = mock_service
        self.app.get('/home')
        mock_service.do_thing.assert_called_with('bar')

rawDescription: How do I mock dependencies of the views module of my Flask application in flask-testing?

description: Mock dependencies of the views module of my Flask application in flask-testing


code:
#!/usr/bin/env python3
# coding: utf-8

import pygame
from pygame.locals import *

# Define some colors
BLACK = (0, 0, 0)

pygame.init()

# Set the width and height of the screen [width, height]
screen = pygame.display.set_mode((1920, 1080))

org_pic = pygame.image.load('test.jpg').convert()
pic_position_and_size = org_pic.get_rect()
pic = pygame.transform.scale(org_pic, pic_position_and_size.size)
# Loop until the user clicks the close button.
done = False

# Clear event queue
pygame.event.clear()

# -------- Main Program Loop -----------
while not done:
    for event in pygame.event.get():
        if event.type == QUIT:
            done = True
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                done = True

    # background in black
    screen.fill(BLACK)

    # Copy image to screen:
    screen.blit(pic, (0,0))

    # Update the screen with what we've drawn.
    pygame.display.flip()
    pygame.display.update()

    pygame.time.delay(10)    # stop the program for 1/100 second

    # decreases size by 1 pixel in x and y axis
    pic_position_and_size = pic_position_and_size.inflate(-1, -1)

    # scales the image
    pic = pygame.transform.smoothscale(org_pic, pic_position_and_size.size)

# Close the window and quit.
pygame.quit()

rawDescription: pyGame image scale does not work as expected

description: PyGame image scale does not work as expected


code:
from django.core.paginator import Paginator
objects = ['john', 'paul', 'george', 'ringo']
p = Paginator(objects, 2)
p.count
p.num_pages
p.page_range

rawDescription: Django: Iterating over multiple instances of a single model in a view


rawDescription: Python histogram bins

description: Python histogram bins


code:
child = pexpect.spawn('/bin/bash')
child.sendline('echo hello | cat')

rawDescription: pexpect and shell meta characters (>, |, or *)

description: Pexpect and shell meta characters (>, |, or *)


code:
def convert_type(cell, typ):
    try:
        return typ(cell)
    except TypeError:
        return "No_Data"

# These lines go below 'tl = my_reader.next()' in your code
col_types = [int, str, int, float, float, float, float, float, float, float, float, list]
new_row = tuple(convert_type(cell, typ) for cell, typ in zip(tl, col_types))
per_table[tl[1]] = new_row

rawDescription: How to handle missing data in a csv file without using numpy/pandas?

description: Handle missing data in a csv file without using numpy/pandas


code:
{'image_urls': ['http://i.stack.imgur.com/tKsDb.png',
                'http://i.stack.imgur.com/NAGkl.png'],
 'images': [{'checksum': 'b0974ea6c88740bed353206b279e0827',
             'path': 'full/762f5682798c5854833316fa171c71166e284630.jpg',
             'url': 'http://i.stack.imgur.com/tKsDb.png'},
            {'checksum': '9a42f7bd1dc45840312fd49cd08e6a5c',
             'path': 'full/615eabb7b61e79b96ea1ddb34a2ef55c8e0f7ec3.jpg',
             'url': 'http://i.stack.imgur.com/NAGkl.png'}]}

rawDescription: How to access name of image that scrapy uploaded to S3?

description: Access name of image that scrapy uploaded to S3


code:
def differ(df):
    delta = df.sample_date.diff().abs()  # only care about magnitude
    cond = delta.notnull() & (delta < np.timedelta64(8, 'W'))
    return df[cond].max()

delta = df.groupby(['dob', 'name']).apply(differ)

rawDescription: Apply function to a MultiIndex dataframe with pandas/python


code:
import argparse

parser = argparse.ArgumentParser()

#-db DATABASE -u USERNAME -p PASSWORD -size 20000
parser.add_argument("-host", "--hostname", dest = "hostname", default = "xyz.edu", help="Server name")
parser.add_argument("-db", "--database", dest = "db", default = "ding_dong", help="Database name")
parser.add_argument("-u", "--username",dest ="username", help="User name")
parser.add_argument("-p", "--password",dest = "password", help="Password")
parser.add_argument("-size", "--binsize",dest = "binsize", help="Size", type=int)

args = parser.parse_args()

print( "Hostname {} db {} User {} Password {} size {} ".format(
        args.hostname,
        args.db,
        args.username,
        args.password,
        args.binsize
        ))
def ConnectToDB():
    print ('Trying to connect to mySQL server')
    # Try to connect to the database
    try:
        con=sql.connect(host=args.hostname, user= args.username, passwd= args.password)
        print ('\nConnected to Database\n')

    # If we cannot connect to the database, send an error to the user and exit the program.
    except sql.Error:
        print ("Error %d: %s" % (sql.Error.args[0],sql.Error.args[1]))
        sys.exit(1)

    return con

rawDescription: Add command line arguments with flags in Python3


code:
def read_write_batch(inpath, outpath, n):
    with open(inpath) as infile, open(outpath, 'w') as outfile:
        batch = []
        for line in infile:
            batch.append(line.strip())
            if len(batch) == n:
                outfile.write(':'.join(batch))
                outfile.write('\n')
                batch = []

if __name__ == '__main__':
    read_write_batch('/tmp/test.txt', '/tmp/out.txt', 4)

rawDescription: Reading entire file and join nth line

description: Reading entire file and join nth line


code:
@register.filter
def mygetattr(obj, name):
    return getattr(obj, name)

rawDescription: Print all properties of an App Engine Model


code:
import matplotlib.colorbar as cbar
import pylab as pl
import numpy as np

N = 50
xs = np.random.randint(0, 100, N)
ys = np.random.randint(0, 100, N)
ws = np.random.randint(10, 20, N)
hs = np.random.randint(10, 20, N)
vs = np.random.randn(N)

normal = pl.normalize(vs.min(), vs.max())
colors = pl.cm.jet(normal(vs))

ax = pl.subplot(111)
for x,y,w,h,c in zip(xs,ys,ws,hs,colors):
    rect = pl.Rectangle((x,y),w,h,color=c)
    ax.add_patch(rect)

cax, _ = cbar.make_axes(ax)
cb2 = cbar.ColorbarBase(cax, cmap=pl.cm.jet,norm=normal)

ax.set_xlim(0,120)
ax.set_ylim(0,120)
pl.show()

rawDescription: Colors of Rectangles in python

description: Colors of Rectangles in python


code:
from PyQt4 import QtGui

class ProxyPerso(QtGui.QSortFilterProxyModel):

    def __init__(self, parent):
        super(ProxyPerso, self).__init__(parent)

        self.parent = parent

    def sort(self, column, order):
        super(ProxyPerso, self).sort(column, order)

        self.parent.proxy.setSourceModel(self.parent.modele)
        self.parent.tableau.setModel(self.parent.proxy)

rawDescription: QSortFilterProxyModel sorts when not necessary


code:
def a(x, stack=None):
    if stack is None:
        stack = [None]
    ...
    a(x + 1, stack)

rawDescription: Python: re-initialize a function's default value for subsequent calls to the function


code:
import re
p = re.compile(r'\{\{Infobox\s*(.*?)}}')
test_str = "{{blabla}}{{Infobox persoon Tweede Wereldoorlog| naam=Albert Speer| afbeelding=Albert Speer Neurenberg.JPG}}{{blabla}}"
match = p.search(test_str)
if match:
    print(match.group(1))

rawDescription: Using regex in python to find a string

description: Using regex in python to find a string


code:
from django.db.models import Max

Model.objects.filter(user_id=100).values('object_id').annotate(Max('id'))

rawDescription: How do I select from a subquery using the Django ORM?

description: Select from a subquery using the Django ORM


code: tags = soup.find_all(['hr', 'strong'])

rawDescription: Python BeautifulSoup give multiple tags to findAll


code:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge('center',1)
G.add_edge('center',2)
G.add_edge('center',3)
G.add_edge('center',4)

pos = {'center':(0,0),
       1:(1,0),
       2:(0,1),
       3:(-1,0),
       4:(0,-1)
       }

nx.draw(G, pos=pos, with_labels=True)
plt.show()

rawDescription: Drawing a custom diagram in python

description: Drawing a custom diagram in python


code:
print("How do you proceed?")

while True:
    print("Do you Shout? Look? Continue?")
    action1 = input()

    if action1 == "Continue": # Continue to next section
        print("You continue on throught the darkness untill you reach a cold stone wall")
        break # break out of the while loop

    elif action1 == "Shout":
        print("In the dark none can hear you scream.")

    elif action1 == 'Look':
        print("'I cannot see anything in the dark' you think to yourself in a broad Scottish accent.")

    print("Enter your next action.(Case sensitive!!)")

# You'll land here after the break statement

rawDescription: How to make my python code loop back

description: Make my python code loop back


code:
key = raw_input("which key you want to update? : ")
value = raw_input("Which value you want to update? : ")

rawDescription: Update dictionary in python, how do I get input from user?


code:
import sys
sys.path.append('c:\\myprojects\\MyProjDir\\')

from MyModule import MyClass

rawDescription: Python how to make a function visible for other python modules


code:
buf = '\xAE\x02\x59'
from struct import unpack
unpack('>BH', buf)

rawDescription: Python/PySerial bit operator on string

description: Python/PySerial bit operator on string


code: combined = list(zip(a, b))

rawDescription: Randomizing two lists and maintaining order in Python 3.4


code:
class LineGraphSerializer(serializers.ModelSerializer):
    pr_id__count = serializers.ReadOnlyField()
    month = serializers.ReadOnlyField()

    class Meta:
        model = Prescription
        fields = ['pr_id__count', 'month']

rawDescription: Serializing data in Django Rest Framework for custom fields


code: itertools.permutations(my_list, 3)

rawDescription: How do I generate permutations of length LEN given a list of N Items?

description: Generate permutations of length LEN given a list of N Items


code:
from collections import Counter

def selectUnique(x):
    count = Counter((i[1], i[2]) for i in x)
    out = [i for i in x if count[(i[1], i[2])] == 1]
    return out

rawDescription: Remove duplicates from list of tuples based on value at certain index


rawDescription: built in function for computing overlap in Python

description: Built in function for computing overlap in Python


code:
mock = MagicMock(return_value=sentinel.file_handle)
with patch('builtins.open', mock):
    import the_broken_module
    # do your testing here

rawDescription: python unittest faulty module

description: Python unittest faulty module


code:
@to_json
def getAllUsersFrom(db):
    return list(db.users.find())

rawDescription: How to turn these functions generic

description: Turn these functions generic


code:
import random

x = random.randint(0,10)
y = 7
while x != y:
    print(x)   #Print old (non-7) random number
    x = random.randint(0,10)  #pick a new number.  I hope it's 7 so we can end this madness

print("You found {0}.  Congrats.  Go have a beer.".format(y))

rawDescription: While loop that prints a random number between 1 and 10 and stops when the number is N


code:
from sets import Set
import csv

source = list(csv.reader(open("account_file.csv")))

accounts = Set(line[0] for line in source)

for account in accounts:
    out = open(account+".csv","w")
    out.write( "\n".join(",".join(x) for x in source if x[0] == account))
    out.close()

rawDescription: Create and write to files based on list with like items


code:
from tornado.web import RequestHandler

db = SqliteDatabase('my_db.db')

class PeeweeRequestHandler(RequestHandler):
    def prepare(self):
        db.connect()
        return super(PeeweeRequestHandler, self).prepare()

    def on_finish(self):
        if not db.is_closed():
            db.close()
        return super(PeeweeRequestHandler, self).on_finish()

rawDescription: How to use Peewee with Tornado perfectly

description: Use Peewee with Tornado perfectly


code:
page = urllib.urlopen('http://www.westforts.com/%s/battles/page/%s' % (server, pagenum))
page_content = page.read()
with open('battle_id_getter%s.txt' % (pagenum) , 'w') as textfile:
    textfile.write(page_content)
with open('battle_id_getter%s.txt' % (pagenum), 'rU') as fp:
    lines = fp.readlines()
line = lines[125]

rawDescription: Py2exe unable to use linecache

description: Py2exe unable to use linecache


code:
from BeautifulSoup import BeautifulSoup
doc = """

<img src="yay.jpg">

"""
soup = BeautifulSoup(doc)
soup.findAll('img')

rawDescription: Finding all *rendered* images in a HTML file


code:
mylst = []
for sentence in contents:   # for each line in contents
    sentence = sentence.split() # eliminate spaces and turn into a list
    sentence[0], sentence[1] = sentence[1], sentence[0] # reverse order
    mylst.append('{0} of {1}'.format(sentence[0],sentence[1]))

return mylst

rawDescription: How do i return each value in a loop?

description: Return each value in a loop


code:
import matplotlib.pyplot as plt

fig = plt.figure(0)
ax = fig.add_subplot(111)
#ax.set_aspect('equal')
plt.axis([-30, 35, -1, 1])

line1 = plt.plot([5, 10],[-0.5, 0], c='k', marker='o')
line2 = plt.plot([10, 20],[0, 0.75], c='k', marker='o')
line3 = plt.plot([20, 35],[0.75, 1], c='k', marker='o')

plt.show()

rawDescription: How to stretch plot vertically in Python

description: Stretch plot vertically in Python


rawDescription: Python find list lengths in a sublist

description: Python find list lengths in a sublist


rawDescription: In Google App Engines, how to display the HTML source of a page of a fetched URL in Python?


code:
import re
import itertools
import time

def use_finditer(data):
    regex = re.compile(r'((?:[^|\\]+|\\.)*)([|])?')
    result = []

    for m in regex.finditer(data):
        result.append(m.group(1))
        if (not m.group(2)):
            break
    return result

def use_split(data):
    regex = re.compile(r'(?:\|)?((?:[^|\\]|\\.)*)')
    result = regex.split(data)
    start_delete = data.startswith('|') * 2 if data else 1
    del result[start_delete::2]
    return result

def check_split(split_func):
    values = '', '', '', ' ', ' ', '|', '|', '\\', '\\\\', 'abc', 'd|ef', 'ghi\\'
    values = [x.replace('\\', '\\\\').replace('|', '\\|') for x in values]
    stuff = [], []
    for i in range(1, 6):
        srclist = list(itertools.permutations(values, i))
        for src in srclist:
            src = tuple(src)
            dst = tuple(split_func('|'.join(src)))
            stuff[dst != src].append((src, dst))

    if not stuff[1]:
        print("Successfully executed %d splits" % len(stuff[0]))
        return

    print(len(stuff[0]), len(stuff[1]))

    stuff[1].sort(key=lambda x: (len(x), x))
    for x, y in stuff[1][:20]:
        z = '|'.join(x)
        print(x, repr(z), y)

def check_loop(func, count=20):
    start = time.time()
    for i in range(count):
        check_split(func)
    print('Execution time: %0.2f' % (time.time() - start))

print('\nUsing finditer')
check_loop(use_finditer)
print('\nUsing split')
check_loop(use_split)

rawDescription: splitting escaped delimiters

description: Splitting escaped delimiters


code:
import xml.etree.ElementTree as ET

def find_child(node, with_name):
    """Recursively find node with given name"""
    for element in list(node):
        if element.tag == with_name:
            return element
        elif list(element):
            sub_result = find_child(element, with_name)
            if sub_result is not None:
                return sub_result
    return None

def replace_node(from_tree, to_tree, node_name):
    """
    Replace node with given node_name in to_tree with
    the same-named node from the from_tree
    """
    # Find nodes of given name ('car' in the example) in each tree
    from_node = find_child(from_tree.getroot(), node_name)
    to_node = find_child(to_tree.getroot(), node_name)

    # Find where to substitute the from_node into the to_tree
    to_parent, to_index = get_node_parent_info(to_tree, to_node)

    # Replace to_node with from_node
    to_parent.remove(to_node)
    to_parent.insert(to_index, from_node)

def get_node_parent_info(tree, node):
    """
    Return tuple of (parent, index) where:
        parent = node's parent within tree
        index = index of node under parent
    """
    parent_map = {c:p for p in tree.iter() for c in p}
    parent = parent_map[node]
    return parent, list(parent).index(node)

from_tree = ET.ElementTree(file='sample1.xml')
to_tree = ET.ElementTree(file='sample2.xml')

replace_node(from_tree, to_tree, 'car')

# ET.dump(to_tree)
to_tree.write('output.xml')

rawDescription: How to copy multiple XML nodes to another file in Python

description: Copy multiple XML nodes to another file in Python


code:
i = 0
while i < x:
    finalprice = list_number_1[i] * list_number_2[i]
    i += 1

rawDescription: Make mathematical equation from 3 lists python


code:
import operator
import struct

from PIL import BmpImagePlugin, PngImagePlugin, Image

def load_icon(file, index=None):
    '''
    Load Windows ICO image.

    See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format
    description.
    '''
    if isinstance(file, basestring):
        file = open(file, 'rb')

    try:
        header = struct.unpack('<3H', file.read(6))
    except:
        raise IOError('Not an ICO file')

    # Check magic
    if header[:2] != (0, 1):
        raise IOError('Not an ICO file')

    # Collect icon directories
    directories = []
    for i in xrange(header[2]):
        directory = list(struct.unpack('<4B2H2I', file.read(16)))
        for j in xrange(3):
            if not directory[j]:
                directory[j] = 256

        directories.append(directory)

    if index is None:
        # Select best icon
        directory = max(directories, key=operator.itemgetter(slice(0, 3)))
    else:
        directory = directories[index]

    # Seek to the bitmap data
    file.seek(directory[7])

    prefix = file.read(16)
    file.seek(-16, 1)

    if PngImagePlugin._accept(prefix):
        # Windows Vista icon with PNG inside
        image = PngImagePlugin.PngImageFile(file)
    else:
        # Load XOR bitmap
        image = BmpImagePlugin.DibImageFile(file)
        if image.mode == 'RGBA':
            # Windows XP 32-bit color depth icon without AND bitmap
            pass
        else:
            # Patch up the bitmap height
            image.size = image.size[0], image.size[1] >> 1
            d, e, o, a = image.tile[0]
            image.tile[0] = d, (0, 0) + image.size, o, a

            # Calculate AND bitmap dimensions. See
            # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage
            # for description
            offset = o + a[1] * image.size[1]
            stride = ((image.size[0] + 31) >> 5) << 2
            size = stride * image.size[1]

            # Load AND bitmap
            file.seek(offset)
            string = file.read(size)
            mask = Image.fromstring('1', image.size, string, 'raw',
                                    ('1;I', stride, -1))

            image = image.convert('RGBA')
            image.putalpha(mask)

    return image

rawDescription: how to determine the transparent color index of ICO image with PIL?

description: Determine the transparent color index of ICO image with PIL


code:
from ast import literal_eval
obj = '{"alert", "Sorry, you are not allowed to do that now, try later", "success", "Welcome, user"}'
literal_eval(obj[1:-1])

rawDescription: Regex for splitting a string which contains commas


rawDescription: TFS API: Retrieve changesets from main branch using VersionControlServer.QueryHistory


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

def concat(type):
    def concat_(*args):
        return list(chain(*args))
    return udf(concat_, ArrayType(type))

concat_string_arrays = concat(StringType())

df.select(concat_string_arrays(col("tokens"), col("bigrams")))

rawDescription: Combine PySpark DataFrame ArrayType fields into single ArrayType field


code:
def __del__(self):
    return self.close()

rawDescription: Closing shared database connection in WSGI app


code:
class Person(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        return self.name

    def get_name(self):
        return self.name if self.name else "John"

rawDescription: Django return property if not null else return method result


code:
regex = re.compile('(?P<key>[^=]+)(?:=(?P<val>.+))?')
regex.match('x=y').groupdict()
regex.match('x').groupdict()

rawDescription: Key=Val matching using regex

description: Key=Val matching using regex


code:
rst_epilog = """
.. _CC-BY: https://creativecommons.org/licenses/by/3.0/
.. _MIT: http://opensource.org/licenses/MIT
"""

rawDescription: Common link targets in Sphinx

description: Common link targets in Sphinx


code:
values = []  # initialize empty list

while len(values < 4):
    value = int(input("enter a number between 1 and 8:"))
    if value in values:  # Check if unique
        print("You already entered this")
    elif value < 1 or value > 8:  # Check bounds
        print("Value must be between 1 and 8")
    else:
        values.append(value)  # Valid number, add to your list

print(values)  # print out the final list

rawDescription: Compare elements of a unique list with Python using only "basic" code


code:
import numpy as np
a = np.random.rand(100,100)
b = np.random.rand(100,100)
c = np.random.rand(100,100)
d = np.dstack((a,b,c))
result = np.median(d,axis=2)

rawDescription: Efficient two dimensional numpy array statistics


code:
from django.contrib.auth.models import User, Group
group = Group(name="Editor")
group.save()                  # save this new group for this example
user = User.objects.get(pk=1) # assuming, there is one initial user
user.groups.add(group)        # user is now in the "Editor" group
user.groups.all()

rawDescription: In Django, how do I check if a user is in a certain group?


rawDescription: How to generate a new rainbow colormap using matplotlib?

description: Generate a new rainbow colormap using matplotlib


code:
import subprocess
proc = subprocess.Popen('hello.exe',shell=True)
proc.wait()

rawDescription: in python How to add to the windows path variable to find executables

description: In python How to add to the windows path variable to find executables


code:
from operator import add

b = []

with open("B.txt") as b_file:
    aux = b_file.readline()
    b   = [float(i) for i in aux.split()]

with open("A.txt") as a_file:
    output = open("output.txt", "a")
    for line in a_file:
        aux = [float(i) for i in line.split()]
        res = map(add, aux, b)
        output.write(str(res) + "\n")

rawDescription: Python: How can I perform addition operator for two different text files?


code: pd.concat([noclickDF, clickDF])

rawDescription: Appending two dataframes with same columns, different order


code: bananas = []+apples

rawDescription: Python assignment operator: Right operand is also modified when Left operand is modified


code:
with open("file.txt", "w") as att_file:
    for item in list:
        att_file.write(attribute + "\n")

rawDescription: Writing variables to new line of txt file in python


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import EllipseCollection

x = np.arange(10)
y = np.arange(15)
X, Y = np.meshgrid(x, y)

XY = np.hstack((X.ravel()[:,np.newaxis], Y.ravel()[:,np.newaxis]))

ww = X/10.0
hh = Y/15.0
aa = X*9

ax = plt.subplot(1,1,1)

ec = EllipseCollection(
                        ww,
                        hh,
                        aa,
                        units='x',
                        offsets=XY,
                        transOffset=ax.transData)
ec.set_array((X+Y).ravel())
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()

rawDescription: repeat y axis scale along grid line of graph ( matplotlib)

description: Repeat y axis scale along grid line of graph ( matplotlib)


code:
hourly_series['hour'] = hourly_series.index
hourly_series['hour'] = hourly_series['hour'].apply(lambda x: x.hour)
hourly_series.groupby(['hour']).var() # Or any other stats function

rawDescription: pandas grouping based on hour to get intra day variability

description: Pandas grouping based on hour to get intra day variability


code:
a = numpy.array([1, 2, 3])
a = numpy.vstack([numpy.roll(a, -i) for i in xrange(3)])

rawDescription: List comprehension or map() or for loop for accessing previous row to manipulate array


code:
nan = float('NaN')
left = (nan, nan)
right = (nan, nan)
left==right
left[0]==right[0]

rawDescription: python comparison for trees represented as tuples

description: Python comparison for trees represented as tuples


code:
import glob
import os.path

for path in glob.glob('third-party/jdk-*'):
    parent, name = os.path.split(path) # "third-party", "jdk-6u29-linux-i586.bin"
    version, update = name.split('-')[1].split('u') # ("6", "29")
    unpack_binaryfunction(path, ('/home/user/%s/third-party' % installdir), 'jdk1.{}.0_{}'.format(version, update))

rawDescription: Making Python guess a file Name

description: Making Python guess a file Name


rawDescription: File input to gnuplot through python

description: File input to gnuplot through python


code:
from itertools import groupby, count
with open(filename, 'r') as datafile:
    groups = groupby(datafile, key=lambda k, line=count(): next(line)//1000000)
    for k, group in groups:
        for line in group:
            ...

rawDescription: using islice to read a text file chunk-by-chunk

description: Using islice to read a text file chunk-by-chunk


code:
from flask import Flask,jsonify
import requests
import simplejson
import json

app = Flask(__name__)

@app.route("/")
def home():
    uri = "https://api.stackexchange.com/2.0/users?   order=desc&sort=reputation&inname=fuchida&site=stackoverflow"
    try:
        uResponse = requests.get(uri)
    except requests.ConnectionError:
       return "Connection Error"
    Jresponse = uResponse.text
    data = json.loads(Jresponse)

    displayName = data['items'][0]['display_name']# <-- The display name
    reputation = data['items'][0]['reputation']# <-- The reputation

    return Jresponse

if __name__ == "__main__":
    app.run(debug = True)

rawDescription: Displaying stackOverflow API JSON data using Flask


code:
partname = partsize = None

for line in searchfile:

    if partname and partsize:
        break

    if "PART FILE NAME" in line and partname is None:
        x = line
        partname = x[18:-1]

    if "PART SIZE" in line and partsize is None:
        y = line
        partsize = y[18:-1]

rawDescription: How do I find the first instance of a string in a text file using Python?

description: Find the first instance of a string in a text file using Python


code:
from collections import Counter

counts = Counter(list_of_words)

rawDescription: Add list of words to dictionary

description: Add list of words to dictionary


code:
import pandas as pd

df = pd.DataFrame({'dates': pd.date_range('2015-01-01', '2015-01-10', freq='12H')})
df.dates.dt.strftime('%H:%S')

rawDescription: How to convert timedelta column in pandas to string

description: Convert timedelta column in pandas to string


code:
class ExcludedModelForm(ModelForm):
    class Meta:
        exclude = ['creator', 'created', 'deleted', 'modified']

class ExampleModelForm(ExcludedModelForm):
    class Meta(ExcludedModelForm.Meta):
        model = ExampleModel

rawDescription: How can I create Django ModelForm for an abstract Model?

description: Create Django ModelForm for an abstract Model


code:
import cherrypy

class Root(object):
    @cherrypy.expose
    def index(self):
        urlVar = 1
        urlVar2 = 2
        raise cherrypy.HTTPRedirect("localhost:8080?foo=" + str(urlVar) + "&fooo=" + str(urlVar2))

cherrypy.config.update({
    'global': {
        'server.socketPort': 8080
    }
})
cherrypy.quickstart(Root())

rawDescription: Server in Python: write or add parameters on URL possible without redirect


rawDescription: Stopping list selection in Python 2.7

description: Stopping list selection in Python 2.7


code:
dependency_links = ['git+https://github.com/liamzebedee/scandir.git#egg=scandir-0.1'],
install_requires = ['scandir'],

rawDescription: Why isn't setup.py dependency_links doing anything?