code:
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
l = ldap.initialize("ldaps://ldap:636")
l.set_option(ldap.OPT_REFERRALS, 0)
l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
l.set_option(ldap.OPT_X_TLS,ldap.OPT_X_TLS_DEMAND)
l.set_option( ldap.OPT_X_TLS_DEMAND, True )
l.set_option( ldap.OPT_DEBUG_LEVEL, 255 )
l.simple_bind_s("admin@tester.com","password")

rawDescription: Python+LDAP+SSL

description: Python+LDAP+SSL


code:
from __future__ import print_function
import Tkinter as tk

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        """A text widget that report on internal widget commands"""
        tk.Text.__init__(self, *args, **kwargs)

        self._orig = self._w + "_orig"
        self.tk.call("rename", self._w, self._orig)
        self.tk.createcommand(self._w, self.proxy)

    def proxy(self, command, *args):
        # this lets' tkinter handle the command as usual
        cmd = (self._orig, command) + args
        result = self.tk.call(cmd)

        # here we just echo the command and result
        print(command, args, "=>", result)

        # Note: returning the result of the original command
        # is critically important!
        return result

if __name__ == "__main__":
    root = tk.Tk()
    CustomText(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: TkInter: how to get actual text modification?


code:
import mechanize
br = mechanize.Browser()
response=br.open("http://www.example.com/")
target_url='http://www.rfc-editor.org/rfc/rfc2606.txt'
for link in br.links():
    print(link)
    # Link(base_url='http://www.example.com/', url='http://www.rfc-editor.org/rfc/rfc2606.txt', text='RFC 2606', tag='a', attrs=[('href', 'http://www.rfc-editor.org/rfc/rfc2606.txt')])
    print(link.url)
    # http://www.rfc-editor.org/rfc/rfc2606.txt
    if link.url == target_url:
        print('match found')
        # match found
        break

br.follow_link(link)   # link still holds the last value it had in the loop
print(br.geturl())
# http://www.rfc-editor.org/rfc/rfc2606.txt

rawDescription: Python mechanize, following link by url and what is the nr parameter?


code: lambda x: operator.itemgetter(0, 2, 4)(x.split())

rawDescription: Python lambda optimization

description: Python lambda optimization


code:
mtx = sp.matrix([1,2,3])
mtx.A

rawDescription: numpy array.A------what is the built-in function A

description: Numpy array.A------what is the built-in function A


code:
for line in f:
 inp = line.split()
 x = float(inp[1])
 y = float(inp[2])

 if(inp[0] == 'r'):
  DrawRectangle(x,y,float(inp[3]),float(inp[4]),inp[5])

rawDescription: Reading in from a file and drawing

description: Reading in from a file and drawing


code:
from win32process import SetProcessWorkingSetSize
from win32api import GetCurrentProcessId, OpenProcess
from win32con import PROCESS_ALL_ACCESS

import win32com.client
import threading
import pythoncom

def CreateTom():
    pythoncom.CoInitialize()
    tom = win32com.client.Dispatch("TOM.Document")
    tom.Dataset.Load("FileName")
    tom.Clear()
    pythoncom.CoUninitialize()
    SetProcessWorkingSetSize(handle,-1,-1) #Releases memory after every use

pid = GetCurrentProcessId()
handle = OpenProcess(PROCESS_ALL_ACCESS, True, pid)

for i in range(50):
    t = threading.Thread(target = CreateTom)
    t.daemon = False
    t.start()

rawDescription: Memory Leak in Threaded COM Object with Python


rawDescription: Is there a way to use bincount with bin width = 0.1 in python?


code:
import numpy
import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1,2)

x1, x2 = 1, 5
y1, y2 = 3, 7

# first axis: ticks spaced at 0.5
ax1.plot([x1, x2], [y1, y2])
ax1.set_xticks(numpy.arange(x1-1, x2+1, 0.5))
ax1.set_yticks(numpy.arange(y1-1, y2+1, 0.5))

# second axis: tick labels will be replaced
ax2.plot([x1, x2], [y1, y2])
ax2.set_xticks(numpy.arange(x1-1, x2+1, 0.5))
ax2.set_yticks(numpy.arange(y1-1, y2+1, 0.5))

# We need to draw the canvas, otherwise the labels won't be positioned and
# won't have values yet.
fig.canvas.draw()

# new x ticks  '1'->'', '1.5'->'1', '2'->'', '2.5'->'2' etc.
labels = [item.get_text() for item in ax2.get_xticklabels()]
new_labels = [ "%d" % int(float(l)) if '.5' in l else '' for l in labels]
ax2.set_xticklabels(new_labels)

# new y ticks
labels = [item.get_text() for item in ax2.get_yticklabels()]
new_labels = [ "%d" % int(float(l)) if '.5' in l else '' for l in labels]
ax2.set_yticklabels(new_labels)

fig.canvas.draw()
plt.show()

rawDescription: Matplotlib: How to force integer tick labels?


code:
s = 'attachment;filename="ã\x80\x90å\x8a¨æ¼«ä¹\x8bå®¶æ±\x89å\x8c\x96ç»\x84ã\x80\x91[æ\x9c\x80å¼ºä¼\x9aé\x95¿é»\x91ç¥\x9e][ç¬¬192è¯\x9d][é»\x91ç¥\x9eç\x9b®æ³·ä¾\x9dç\x84¶å\x81¥å\x9c¨][END].zip"'
s = s.encode('latin-1').decode('utf-8')
s

rawDescription: How to decode the filename parameter of Content-Disposition header in HTTP?

description: Decode the filename parameter of Content-Disposition header in HTTP


rawDescription: Split on regex Python

description: Split on regex Python


rawDescription: Remove leading and trailing slash /

description: Remove leading and trailing slash /


code:
from multiprocessing import Pool
import random
import socket
import sys

remoteServer = sys.argv[1]
remoteServerIP  = socket.gethostbyname(remoteServer)

ports = random.sample(range(1,1000), 999)

def testport(num):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(.01)
    result = sock.connect_ex((remoteServerIP, port))
    sock.close()
    if result == 0:
        return num
    return None

p = Pool()
openports = p.map(testport, ports)
openports = [prt for prt in openports if prt is not None]

rawDescription: Cannot call python global variable outside of function


code:
import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
for fig in xrange(1, figure().number): ## will open an empty extra figure :(
    pdf.savefig( fig )
pdf.close()

rawDescription: Python saving multiple figures into one PDF file


code:
from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('--var1', action='store', type=float)
parser.add_argument('--var2', action='store', type=float)
parser.add_argument('--var3', action='store', type=float)
parser.add_argument('--var4', action='store', type=float)
args = parser.parse_args()

var1 = args.var1
var2 = args.var2
var3 = args.var3
var4 = args.var4

x = var1 + var2
y = var3 + var4
z = (x+y) / var4
print (str(x)) #result should always be 9.4
print (str(y)) #result should always be 10.2
print (str(z)) #result should always be 6.125

rawDescription: passing python arguments in different order along with its variable name

description: Passing python arguments in different order along with its variable name


code:
# Assume text is decoded HTML, so the <div> looks like a normal tag.
start = len('<description>')
end = text.find('<div>')
text = text[start: end]

rawDescription: Python RSS reader text filtering

description: Python RSS reader text filtering


code:
amount = 250000

thousands = amount % 100000
lakhs = amount - thousands

rawDescription: Python : Split Amount into Thousands and Lakhs


code:
Left= Word(alphanums)
Op = oneOf('= := -> ::=')
Right = QuotedString('"') | QuotedString("'")
Rule = Left+ Op+ Right
Rule.parseString("A -> '_\x5555 a'")
Rule.parseString(r"A -> '_\x5555 a'")  # use a raw string literal, with r""

rawDescription: How to make PyParsing recognize \x escapes?

description: Make PyParsing recognize \x escapes


code:
import ast
lst=[['ROOT', 'S'], ['S', 'NP', ')', 'VP', ')'], ['NP', 'DT', 'NN']]
lst=str(lst)
lst=lst.replace('\')\'','\' \'], [\' \'')
lst=ast.literal_eval(lst)
lst

rawDescription: How to split a list on the basis of an element in the list in python?

description: Split a list on the basis of an element in the list in python


code: [x**2 for x in range(20)]

rawDescription: Python List of Squares in Python3

description: Python List of Squares in Python3


code:
from django.contrib.auth.views import redirect_to_login

class ProfileUpdate(UpdateView):
    [...]

    def user_passes_test(self, request):
        if request.user.is_authenticated():
            self.object = self.get_object()
            return self.object.user == request.user
        return False

    def dispatch(self, request, *args, **kwargs):
        if not self.user_passes_test(request):
            return redirect_to_login(request.get_full_path())
        return super(ProfileUpdate, self).dispatch(
            request, *args, **kwargs)

rawDescription: Django restrict UpdateView for specific user


code: l.extend((i for i in (2,3,4) if i not in l))

rawDescription: Is list comprehension appropriate here?

description: Is list comprehension appropriate here


code:
from moduleA import (ClassA, ClassB, ClassC,
                     DataA, DataB)

rawDescription: Is there any difference between `from abc import a,b` and `from abc import (a,b)`?


code:
for name, url in zip(names, urls):
    urllib.request.urlretrieve(url, name)

rawDescription: Funny behavior using urlretrieve on a dict in Python


code:
master = Tk()

namR = []
for ii in range(0,20):
    namR.append(Entry(master))
    namR[ii].grid(row=2+ii, column=3)

rawDescription: Tkinter - getting an array of entry values


code:
def onMotion(self,event):

    if not event.inaxes:
        return

    xint = int(event.xdata)
    yint = int(event.ydata)

    self.rect = mpatches.Rectangle((xint, yint),1,1,fill=False,linestyle='dashed', edgecolor='red',linewidth=2.0)

    self.axh.add_patch(self.rect)

    self.canvash.draw()

    self.rect.remove()

rawDescription: Highlight cell in seaborn heatmap through mouse hover


code:
def _fetchInfo(self, data):
    try:
        data=int(data)
        sql='SELECT ... WHERE id = %s'
        args=[data]
    except ValueError:
        sql='SELECT ... WHERE email = %s'
        args=[data]
        # This might fail, in which case, data was neither a valid integer or email address

rawDescription: In python, what is the fastest way to determine if a string is an email or an integer?


code:
def temperatureTable(elevation):
    tempTable = list()
    for temperature in range(225, 350, 5):
        candyTemp = candyTemperature(temperature, elevation)
        tempTable.append((candyTemp, temperature))
    return tempTable

rawDescription: Python Help (Printing conversion table)

description: Python Help (Printing conversion table)


rawDescription: Python adding to the list

description: Python adding to the list


code:
import csv
with open('source.csv','rb') as source:
    rdr= csv.reader( source )
    with open('revised.csv','wb') as target:
        wtr= csv.writer( target )
        for r in rdr:
            wtr.writerow( (r[0], r[1], r[2], '{0};{1}'.format(r[3],r[4]), r[5], r[6]) )

rawDescription: How to replace a particular comma in a CSV file using Python?

description: Replace a particular comma in a CSV file using Python


code:
from sqlalchemy import create_engine, Column, String, Integer, ForeignKey
from sqlalchemy.orm import Session, relationship, backref, immediateload
from sqlalchemy.ext.declarative import declarative_base
import os

Base = declarative_base()

class Person(Base):
    __tablename__ = "people"
    id = Column(Integer, primary_key=True)
    name = Column(String)

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

class Edge(Base):
    __tablename__ = "edges"
    id = Column(Integer, primary_key=True)
    kid_id = Column(Integer, ForeignKey("people.id"))
    parent_id = Column(Integer, ForeignKey("people.id"))
    kid = relationship("Person", primaryjoin="Edge.kid_id==Person.id",
                       backref=backref("parent_edges",
                                       collection_class=set))
    parent = relationship("Person", primaryjoin="Edge.parent_id==Person.id",
                          backref=backref("kid_edges",
                                          collection_class=set))

    def __init__(self, kid, parent):
        self.kid = kid
        self.parent = parent

def teardown():
    for path in ("in.db", "out.db"):
        if os.path.exists(path):
            os.remove(path)

def fixture():
    engine = create_engine("sqlite:///in.db", echo=True)
    Base.metadata.create_all(engine)

    s = Session(engine)
    p1, p2, p3, p4, p5 = [Person('p%d' % i) for i in xrange(1, 6)]
    Edge(p1, p2)
    Edge(p1, p3)
    Edge(p4, p3)
    Edge(p5, p2)
    s.add_all([
        p1, p2, p3, p4, p5
    ])
    s.commit()
    return s

def copy(source_session):
    engine = create_engine("sqlite:///out.db", echo=True)
    Base.metadata.create_all(engine)

    s = Session(engine)
    for person in source_session.query(Person).\
            options(immediateload(Person.parent_edges),
                        immediateload(Person.kid_edges)):
        s.merge(person)

    s.commit()

    assert s.query(Person).count() == 5
    assert s.query(Edge).count() == 4

teardown()
source_session = fixture()
copy(source_session)

rawDescription: How to merge many to many relations from one db session to another with SQLAlchemy?

description: Merge many to many relations from one db session to another with SQLAlchemy


code:
def getIndexOfNeighoringTiles(i):
    neighbors = []
    if (i % M != 0):
        neighbors.append(i-1)
    if (i % M != (M-1)):
        neighbors.append(i+1)
    if (i / M != 0):
        neighbors.append(i-M)
    if (i / M != (M-1)):
        neighbors.append(i+M)
    return neighbors

rawDescription: Lights Out in Python- How to Get Adjacent Tiles in a one-dimensional array?


code:
# Python
n, p = p, n
x, y, z = z, x, y

rawDescription: Tuple Unpacking Similar to Python, but in Common Lisp


code:
import datetime
import dateutil.parser

five_minutes = datetime.timedelta(minutes=5)

def group_by_time(objects):
    objects = iter(objects)
    obj = next(objects)
    last = dateutil.parser.parse(obj.time)
    group = [obj]
    for obj in objects:
        time = dateutil.parser.parse(obj.time)
        if time > last + five_minutes:
            yield group
            group = []
        group.append(obj)
        last = time
    else:
        yield group

rawDescription: Group list of objects based on close datetime attribute


code:
import cv2
import numpy as np

#== Parameters =======================================================================
BLUR = 21
CANNY_THRESH_1 = 10
CANNY_THRESH_2 = 200
MASK_DILATE_ITER = 10
MASK_ERODE_ITER = 10
MASK_COLOR = (0.0,0.0,1.0) # In BGR format

#== Processing =======================================================================

#-- Read image -----------------------------------------------------------------------
img = cv2.imread('C:/Temp/person.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#-- Edge detection -------------------------------------------------------------------
edges = cv2.Canny(gray, CANNY_THRESH_1, CANNY_THRESH_2)
edges = cv2.dilate(edges, None)
edges = cv2.erode(edges, None)

#-- Find contours in edges, sort by area ---------------------------------------------
contour_info = []
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
for c in contours:
    contour_info.append((
        c,
        cv2.isContourConvex(c),
        cv2.contourArea(c),
    ))
contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)
max_contour = contour_info[0]

#-- Create empty mask, draw filled polygon on it corresponding to largest contour ----
# Mask is black, polygon is white
mask = np.zeros(edges.shape)
cv2.fillConvexPoly(mask, max_contour[0], (255))

#-- Smooth mask, then blur it --------------------------------------------------------
mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)
mask = cv2.erode(mask, None, iterations=MASK_ERODE_ITER)
mask = cv2.GaussianBlur(mask, (BLUR, BLUR), 0)
mask_stack = np.dstack([mask]*3)    # Create 3-channel alpha mask

#-- Blend masked img into MASK_COLOR background --------------------------------------
mask_stack  = mask_stack.astype('float32') / 255.0          # Use float matrices,
img         = img.astype('float32') / 255.0                 #  for easy blending

masked = (mask_stack * img) + ((1-mask_stack) * MASK_COLOR) # Blend
masked = (masked * 255).astype('uint8')                     # Convert back to 8-bit

cv2.imshow('img', masked)                                   # Display
cv2.waitKey()

#cv2.imwrite('C:/Temp/person-masked.jpg', masked)           # Save

rawDescription: How do I remove the background from this kind of image?

description: Remove the background from this kind of image


rawDescription: What range function does to a python list?


code:
img1 = Image.new('RGBA', (255, 255)) # Use RGBA
img2 = Image.new('RGBA', (255, 255)) # Use RGBA
draw1 = ImageDraw.Draw(img1)
draw2 = ImageDraw.Draw(img2)

draw1.polygon([(0, 0), (0, 255), (255, 255), (255, 0)], fill = (255,255,255,255))

transparence = 100 # Define transparency for the triangle.
draw2.polygon([(1,1), (20, 100), (100,20)], fill = (200, 0, 0, transparence))

img = Image.alpha_composite(img1, img2)
img.save("my_pic.png", 'PNG')

rawDescription: how to create a triangle filled in a translucent color by python pillow(fork PIL)

description: Create a triangle filled in a translucent color by python pillow(fork PIL)


code:
string_to_check = "name 2"
string_to_add = "name 1,"
with open("test.txt", 'r+') as file_to_write:
    lines = file_to_write.readlines()
    file_to_write.seek(0)
    file_to_write.truncate()
    for line in lines:
        if line.startswith(string_to_check):
           line = line.rstrip("\n") + string_to_add + "\n"
        file_to_write.write(line)

rawDescription: python - writing to a specific line in text file

description: Python - writing to a specific line in text file


code:
replacements = {
    'Name': ['FirstName','First Name','Nombre','NameFirst', 'Name', 'Given name', 'given name', 'Name'],
    'Address': ['Residence','Primary Address', 'primary address' ],
    #...
}

df.rename(columns={el:k for k,v in replacements.iteritems() for el in v}, inplace=True)

rawDescription: Pandas efficiently normalize column titles in a dataframe


code:
import smtplib
from email.mime.text import MIMEText

# define content
recipients = ["recipient_id@yahoo.com"]
sender = "sender_id@gmail.com"
subject = "report reminder"
body = """
Dear Student,
Please send your report
Thank you for your attention
"""

# make up message
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ", ".join(recipients)

# sending
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(sender, 'my password')
send_it = session.sendmail(sender, recipients, msg.as_string())
session.quit()

rawDescription: How to get line breaks in e-mail sent using Python's smtplib?

description: Get line breaks in e-mail sent using Python's smtplib


code:
for arry, name in zip(pglist, deptNames5):
    NewPdf = PdfFileWriter()
    for page in arry:
        pagenumber = pdfDoc.getPage(page)
        NewPdf.addPage(pagenumber)
    with open(name + b'.pdf', 'wb') as f:
        NewPdf.write(f)

rawDescription: python-pypdf split pdf based a list of page ranges

description: Python-pypdf split pdf based a list of page ranges


code:
N = mat.shape[1]
I, J = np.triu_indices(N, 1)
result = mat[:,I] - mat[:,J]

rawDescription: Calculate all possible columnwise differences in a matrix


code:
flags = [('name:', nameMethod), ('age:', ageMethod), ('test pass', tpMethod), ('test fail', tfMethod), ... ] #methods are functions without ()

for line in lines:
  for flag, func in flags:
    if line.find(flag) != -1:
      func(args) #your args
      break #same functionality as elif

rawDescription: Python: efficiently checking a file line by line


code:
import datetime, pytz
melbourne = pytz.timezone("Australia/Melbourne")
melbourne.utcoffset(datetime.datetime.now())
pacific = pytz.timezone("US/Pacific")
pacific.utcoffset(datetime.datetime.now())
-1*86400+61200
pacific.utcoffset(datetime.datetime.now()).total_seconds()

rawDescription: Python - get UTC offset by seconds

description: Python - get UTC offset by seconds


code:
class RirDataInline(admin.TabularInline):
    model = RirData
    fields = ['netname', 'inetnum', 'review_status', 'active']
    readonly_fields = fields
    can_delete = False
    show_change_link = True
    extra = 0

rawDescription: Django TabularInline: Discard empty rows


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

cap = cv2.VideoCapture(0)
ret, frame = cap.read()

bg = [[[0] * len(frame[0]) for _ in xrange(len(frame))] for _ in xrange(3)]

while(True):
    ret, frame = cap.read()
    # Resizing down the image to fit in the screen.
    frame = cv2.resize(frame, None, fx = 0.5, fy = 0.5, interpolation = cv2.INTER_CUBIC)

    # creating another frame.
    channels = cv2.split(frame)
    frame_merge = cv2.merge(channels)

    # horizintally concatenating the two frames.
    final_frame = cv2.hconcat((frame, frame_merge))

    # Show the concatenated frame using imshow.
    cv2.imshow('frame',final_frame)

    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

cap.release()
cv2.destroyAllWindows()

rawDescription: OpenCV (Python) video subplots

description: OpenCV (Python) video subplots


code:
content_toSend = urllib.urlencode({
    'guestbook_name' : guestbook_name,
    'content' : greeting.content
    })

rawDescription: Sending multi-var dictionary via get in google app engine; python


code:
fruit_wanted = ['fruit'] + ["'%s'" % f for f in fruit_wanted.split(',')]
outfile = csv.DictWriter(open(outputfile, 'wb'), fieldnames=fruit_wanted)
fruit_wanted = set(fruit_wanted)

for row in csv.DictReader(open(inputfile, 'rb')):
    row = {k: row[k] for k in row if k in fruit_wanted}
    outfile.writerow(row)

rawDescription: remove selected csv column in python

description: Remove selected csv column in python


code:
def trifactorgenerator(n):
  return (((i,j,n/(i*j))
           for i in range(1, int(n**.5)+1) if n%i==0
             for j in range(i, int( (n/i)**.5)+1) if n%(i*j) == 0))

rawDescription: Generating all unique ways of writing x = abc?


code:
list1=[{'a':'apples', 'b':'snack','count':2},{'a':'apples','b':'lunch','count':3},{'a':'apples','b':'snack','count':3}]

from collections import defaultdict
dd = defaultdict(int)
for d in list1:
    dd[d['a'], d['b']] += d['count']

list2 = [{'a': k[0], 'b': k[1], 'count': v} for k, v in dd.iteritems()]

[{'a': 'apples', 'count': 3, 'b': 'lunch'}, {'a': 'apples', 'count': 5, 'b': 'snack'}]

rawDescription: Python 2.7 - Sum value on duplicates in dictionary


code:
# create a series of just the data from the 'ShippmentSegmentDays' column
seg_days_df = trends['ShippmentSegmentDays']

# Create a new column, 'ShippmentSegment', in 'transdf' data frame by calling
# our utility function on the series created above.
transdf['ShippmentSegment'] = seg_days_df.apply(calc_ship_segment, axis=1)

# Utility function to define the rules set in the 'segmentdf' data frame
def calc_ship_segment(num):
     if not num:
         return 'On Time'
     elif num == 1:
         return '1 Day Late'
     elif num == 2:
         return '2 Days Late'
     elif num == 3:
         return '3 Days Late'
     else:
         return '>3 Days Late'

rawDescription: Pandas find value in interval

description: Pandas find value in interval


code:
pick_level = 1
lockpicking_level1_maxxp = 40
lockpicking_level2_maxxp = 70
lockpicking_level3_maxxp = 100
locals()["lockpicking_level%d_maxxp" % pick_level]

rawDescription: Is there a Python equivalent to the grave accent in bash scripting?


code:
def money():
    amount_ = float(input("Enter NZ conversion amount:$ "))
    for i in range(1, 11):
        amount = amount_ * i
        AUD = amount*0.96
        US = amount*0.75
        Euro = amount*0.67
        GBP = amount*0.496
        print('NZ$', amount,'AUD: {}, US:{}, Euro: {}, GBP: {}'.format(AUD, US, Euro, GBP))
    return

rawDescription: How can I loop my code so it will go up in increments?

description: Loop my code so it will go up in increments


code:
from collections import OrderedDict
from operator import itemgetter

print(list(OrderedDict.fromkeys(map(itemgetter("class"),lis))))
['math', 'english', 'history']

rawDescription: python filter distinct dictionary key value in list

description: Python filter distinct dictionary key value in list


code:
import numpy as np

list_of_my_bin_lists = [[2, 6, 9], [4, 6, 8], [3, 5, 9]]
my_array = np.array([1, 3, 7])
digitized = [np.digitize(np.array([item]), bin_list)[0]
             for item, bin_list
             in zip(my_array, list_of_my_bin_lists)]

rawDescription: digitize array to several lists of bins

description: Digitize array to several lists of bins


code:
numlines = 20

for i in np.linspace(0,1, numlines):
    plt.plot(np.arange(numlines),np.tile([i],numlines), linewidth=4, color=plt.cm.RdYlBu(i))

rawDescription: Having line color vary with data index for line graph in matplotlib?


code:
import ast
a = ast.literal_eval('(1, 2, 3)')
a
b = ast.literal_eval('__import__("evil")')

rawDescription: Any downside to overriding ConfigParser get() method to include an eval?


code:
# Any
contains = any(func(x) for x in enumerable)

# Count
count = sum(func(x) for x in enumerable)

# Distinct: since we are using a custom comparer here, we need a loop to keep
# track of what has been seen already
distinct = []
seen = set()
for x in enumerable:
    comp = comparer(x)
    if not comp in seen:
        seen.add(comp)
        distinct.append(x)

# First
element = next(iter(enumerable))

# Except
except_ = [x for x in enumerable if not comparer(x) in other]

rawDescription: Python equivalents to LINQ

description: Python equivalents to LINQ


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from functools import partial
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        numbers = [ '7', '8', '9',
            '4', '5', '6',
            '1', '2', '3',
                    '*', '0', '#',]
        self.vert_lay = QtGui.QVBoxLayout()
        self.dig_out = QtGui.QLineEdit()
        self.vert_lay.addWidget(self.dig_out)
        grid = QtGui.QGridLayout()
        j = 0
        pos = [(0, 0), (0, 1), (0, 2),
                (1, 0), (1, 1), (1, 2),
                (2, 0), (2, 1), (2, 2),
                (3, 0), (3, 1), (3, 2),
              ]
        for i in numbers:
            button = QtGui.QPushButton(i)
            grid.addWidget(button, pos[j][0], pos[j][1])
            j = j + 1
            button.clicked.connect(partial(self.addNumber,i))

        self.vert_lay.addLayout(grid)
        self.setLayout(self.vert_lay)

        self.move(300, 150)
        self.setWindowTitle('Calculator')
        self.show()

    def addNumber(self,num):
        current_txt = self.dig_out.text()
        self.dig_out.setText("%s%s" % (current_txt,num))

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

if __name__ == '__main__':
    main()

rawDescription: Reproduce functions in a video tutorial

description: Reproduce functions in a video tutorial


code:
view = QGraphicsView()
view.setScene(scene)
view.setSceneRect(QRectF(view.viewport().rect()))

rawDescription: Why are PNG images rendered from a QGraphicsScene being incorrectly offset?


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

data = np.random.normal(loc=1000,scale=20,size=2000)
n, bins, patches = plt.hist(np.log10(data),log=True)

# Extract the midpoints and widths of each bin.
bin_starts = bins[0:bins.size-1]
bin_widths = bins[1:bins.size] - bins[0:bins.size-1]

# Clear the histogram plot and replace it with a bar plot.
plt.clf()
plt.bar(bin_starts,np.log10(n),bin_widths)
plt.xlabel('Log(data)')
plt.ylabel('Log(Counts)')
plt.show()

rawDescription: Logging count value in histogram, not the axis itself


code:
words = ['halo', 'hallo', 'help']
[fdistance('hello', word) for word in words]

rawDescription: Edit distance string and list

description: Edit distance string and list


code:
fig, ax = plt.subplots()
ax2 = ax.twinx()
ax.bar(df_eg.index, df_eg["Release"], color=(190/255,190/255,190/255,0.7), label='Release')
ax2.plot(df_eg.index, df_eg["Hold"], color='green', label='Hold')
ax.set_xticklabels(df_eg.index)
ax.legend(loc='best')

rawDescription: pandas DataFrame how to mix bar and line plots with different scales

description: Pandas DataFrame how to mix bar and line plots with different scales


code:
f, (ax1, ax2) = plt.subplots(2)
sns.regplot(x, y, ax=ax1)
sns.kdeplot(x, ax=ax2)

rawDescription: Plotting with seaborn using the matplotlib object-oriented interface


rawDescription: 3D scatterplots in sage

description: 3D scatterplots in sage


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):

        wx.Frame.__init__(self, parent, id, title, size=(800, 700))
        self.tabbed = wx.Notebook(self, -1, style=(wx.NB_TOP))
        self.running = RunningPane(self.tabbed)
        self.queue = QueuePane(self.tabbed, self.running)
        self.submissions = SubmissionPane(self.tabbed, self.queue)

        self.tabbed.AddPage(self.submissions, "Submit Job")
        self.tabbed.AddPage(self.queue, "Queue")
        self.tabbed.AddPage(self.running, "Running Jobs")

        self.CreateStatusBar()
        menuBar = wx.MenuBar()
        menu = wx.Menu()
        self.SetMenuBar(menuBar)
        self.Centre()
        self.Show()

#---
#

class SubmissionPane(wx.Panel):
    def __init__(self, parent, queue_control):
        wx.Panel.__init__(self, parent, -1)
        self.parent = parent
        self.queue_control = queue_control
        self.selected_folder = None

        self.drop_target = MyFileDropTarget(self)
        self.tc_files = wx.TextCtrl(self, wx.ID_ANY, pos=(42, 120), size=(500, 25))
        self.tc_files.SetDropTarget(self.drop_target)
        self.buttonGo = wx.Button(self, -1, "Submit", pos=(90,530))
        self.buttonGo.Bind(wx.EVT_BUTTON, self.OnSubmit)

        self.buttonClose = wx.Button(self, -1, "Quit", pos=(195,530))
        self.buttonClose.Bind(wx.EVT_BUTTON, self.OnClose)

        outputtxt3 = '''Drag & Drop Folder of Packages to Verify'''
        wx.StaticText(self, -1, outputtxt3, (33, 64), style=wx.ALIGN_CENTRE)
        self.Show()

    def SetSubmissionFolders(self, folder_list):
        """Called by the FileDropTarget when files are dropped"""

        self.tc_files.SetValue(','.join(folder_list))
        self.selected_folders = folder_list

    def OnSubmit(self, event):
        self.queue_control.QueueFolders(self.selected_folders)
        wx.MessageBox('Job Submitted')

    def OnClose(self, e):
        self.Close(True)

class MyFileDropTarget(wx.FileDropTarget):
    """"""
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window

    def OnDropFiles(self, x, y, filenames):
        self.window.SetSubmissionFolders(filenames)

#---
#

class QueuePane(wx.Panel):
    def __init__(self, parent, run_control):
        wx.Panel.__init__(self, parent, -1)

        self.parent = parent
        self.run_control = run_control

        self.queue = []

        self.buttonClose2 = wx.Button(self, -1, "Quit", pos=(195,170))
        self.buttonClose2.Bind(wx.EVT_BUTTON, self.OnClose)

        self.log_text = wx.TextCtrl(self, -1, pos=(35, 210), size=(720,400),
                                    style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
        self.Show()

    def QueueFolders(self, folder_list):
        """Called by anyone with a list of folders to queue.
            In this code, that is the submission pane."""
        self.queue.extend(folder_list)
        self.log_text.AppendText("\n".join(folder_list))

    def OnClose(self, e):
        self.Close(True)

#---
#

class RunningPane(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)

        self.parent = parent

        self.buttonClose3 = wx.Button(self, -1, "Quit", pos=(195,170))
        self.buttonClose3.Bind(wx.EVT_BUTTON, self.OnClose)

        self.running_log = wx.TextCtrl(self, -1, pos=(35, 210), size=(720,400),
                                       style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
        self.Show()

    def OnClose(self, e):
        self.Close(True)
#
#---

app = wx.App()
MainWindow(None, -1, 'Application')
app.MainLoop()

rawDescription: wxpython print to tabbed panel

description: Wxpython print to tabbed panel


code:
with open('test_file.txt') as fin:
    csvin = csv.reader(fin, delimiter='\t')
    has_fantastic = (row for row in csvin if any('fantastic' in col.lower() for col in row[1:]))
    ids = [row[0] for row in has_fantastic]

rawDescription: Using python to count string occurrences in a flat file


code:
import itertools
import multiprocessing
from collections import deque
from multiprocessing.managers import BaseManager, MakeProxyType

class DequeManager(BaseManager):
   pass

BaseDequeProxy = MakeProxyType('BaseDequeProxy', (
    '__add__', '__contains__', '__delitem__', '__getitem__', '__len__',
    '__mul__', '__reversed__', '__rmul__', '__setitem__',
    'append', 'count', 'extend', 'extendleft', 'index', 'insert', 'pop',
    'remove', 'reverse', 'sort', 'appendleft', 'popleft', 'rotate',
    '__imul__'
    ))
class DequeProxy(BaseDequeProxy):
    def __iadd__(self, value):
        self._callmethod('extend', (value,))
        return self
    def __imul__(self, value):
        self._callmethod('__imul__', (value,))
        return self

DequeManager.register('deque', deque, DequeProxy)

cur_best = d_sol = d_names = None

def init_globals(best, sol, names):
    """ This will be called in each worker process.

    A global variable (cur_best) will be created in each worker.
    Because it is a multiprocessing.Value, it will be shared
    between each worker, too.

    """
    global cur_best, d_sol, d_names
    cur_best = best
    d_sol = sol
    d_names = names

def calculate(vals):
    global cur_best
    sol = sum(int(x[2]) for x in vals)
    if sol > cur_best.value:
        cur_best.value = sol
        names = [x[0] for x in vals]
        print(", ".join(names) + " = " + str(cur_best.value))
        d_sol.append(cur_best.value)
        d_names.append(names)
    return sol

def process():
    global d_sol, d_names
    cur_best = multiprocessing.Value("I", 0)  # unsigned int

    m = DequeManager()
    m.start()
    d_sol = m.deque(maxlen=9)
    d_names = m.deque(maxlen=9)

    pool = multiprocessing.Pool(processes=4, initializer=init_globals,
                                initargs=(cur_best, d_sol, d_names))
    prod = itertools.product([x[2], x[4], x[10]] for x in Data1)
    result = pool.map(calculate, prod)  # map instead of map_async
    pool.close()
    pool.join()
    return result  # Result will be a list containing the value of `sol` returned from each worker call

if __name__ == "__main__":
    print(process())

rawDescription: python no output when using pool.map_async

description: Python no output when using pool.map_async


code: '{%s}' % ','.join('(%s)' % element for element in x)

rawDescription: Construct String based off length of list


code:
df=pd.DataFrame ([123456789012345])
writer = pd.ExcelWriter ('e.xlsx', engine='openpyxl')
df.to_excel (writer, 'sheet1')
ws = writer.sheets['sheet1']
ws['A1'].style.number_format.format_code='@'
writer.save ()
pd.read_excel ('e.xlsx')

rawDescription: pandas set cell format in excel writer

description: Pandas set cell format in excel writer


code:
self.positionX -= diff_norm[0]
self.positionY -= diff_norm[1]
self.rect.x = int(self.positionX)
self.rect.y = int(self.positionY)

rawDescription: Python/Pygame Vector Math

description: Python/Pygame Vector Math


code:
class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(Anniversary)
    address = models.ForeignKey(Address)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

rawDescription: Foreign Key Django Model

description: Foreign Key Django Model


code:
df['time'] = pd.to_datetime(df['time'])
df = df.set_index('time')
df['value1'] = df['value1'].astype(bool)

rawDescription: How to specify type of input data for Pandas DataFrame

description: Specify type of input data for Pandas DataFrame


code:
import os
import hashlib

mypath = 'testdup'
onlyfiles = [f for f in os.listdir(mypath)
                if os.path.isfile(os.path.join(mypath,f)) ]

files = {}
for filename in onlyfiles:
    filehash = hashlib.md5(open(os.path.join(mypath, filename), 'rb')
                              .read()).hexdigest()
    try:
        files[filehash].append(filename)
    except KeyError:
        files[filehash] = [filename]

for filehash, filenames in files.items():
    print('{0} files have this content:'.format(len(filenames)))
    print(open(os.path.join(mypath,filenames[0])).read())

rawDescription: count duplicate Files

description: Count duplicate Files


code:
# Calculate count after thresholding with x and summing along first axis
count = (ice > x).sum(axis=0)

# Get percentages (ratios) by dividing with first axis length
percent_ice = np.true_divide(count,ice.shape[0])

rawDescription: Counting the number of times a threshold is met or exceeded in a multidimensional array in Python


code:
from textblob import TextBlob
txt = """The maker of Sam Global Ent, Sam Helsen has bought many stocks in a private intelligence firm Samligence."""
blob = TextBlob(txt)
blob.noun_phrases

rawDescription: Extracting Nouns and Entities using Regex and POS


code:
import re
s = 'Hello @Simon, I had a great day today. #StackOverflow'
re.sub(r'(?:^|\s)[@#].*?(?=[,;:.!?]|\s|$)', r'', s)

rawDescription: Remove words from string that have a prefix of # or @?


code:
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED
import zlib
from cStringIO import StringIO
from urllib2 import urlopen
from urlparse import urlparse
from os import path

images = ['http://sstatic.net/so/img/logo.png',
          'http://sstatic.net/so/Img/footer-cc-wiki-peak-internet.png']

buf = StringIO()
# By default, zip archives are not compressed... adding ZIP_DEFLATED
# to achieve that. If you don't want that, or don't have zlib on or
# system, delete the compression kwarg
zip_file = ZipFile(buf, mode='w', compression=ZIP_DEFLATED)

for image in images:
    internet_image = urlopen(image)
    fname = path.basename(urlparse(image).path)
    zip_file.writestr(fname, internet_image.read())

zip_file.close()

output = open('images.zip', 'wb')
output.write(buf.getvalue())
output.close()
buf.close()

rawDescription: Parsing an html file and adding found images to a zip file


code:
import os
os.chdir('/foo/bar')
f = open('foobar.txt', 'r')

rawDescription: reading a file in python from different directory

description: Reading a file in python from different directory


code:
import numpy as np
import scipy as sp
import scipy.ndimage

import Image

import matplotlib.pyplot as plt

def main():
    im = Image.open('mri_demo.png')
    im = im.convert('RGB')
    data = np.array(im)

    plot_polar_image(data, origin=None)
    plot_directional_intensity(data, origin=None)

    plt.show()

def plot_directional_intensity(data, origin=None):
    """Makes a cicular histogram showing average intensity binned by direction
    from "origin" for each band in "data" (a 3D numpy array). "origin" defaults
    to the center of the image."""
    def intensity_rose(theta, band, color):
        theta, band = theta.flatten(), band.flatten()
        intensities, theta_bins = bin_by(band, theta)
        mean_intensity = map(np.mean, intensities)
        width = np.diff(theta_bins)[0]
        plt.bar(theta_bins, mean_intensity, width=width, color=color)
        plt.xlabel(color + ' Band')
        plt.yticks([])

    # Make cartesian coordinates for the pixel indicies
    # (The origin defaults to the center of the image)
    x, y = index_coords(data, origin)

    # Convert the pixel indices into polar coords.
    r, theta = cart2polar(x, y)

    # Unpack bands of the image
    red, green, blue = data.T

    # Plot...
    plt.figure()

    plt.subplot(2,2,1, projection='polar')
    intensity_rose(theta, red, 'Red')

    plt.subplot(2,2,2, projection='polar')
    intensity_rose(theta, green, 'Green')

    plt.subplot(2,1,2, projection='polar')
    intensity_rose(theta, blue, 'Blue')

    plt.suptitle('Average intensity as a function of direction')

def plot_polar_image(data, origin=None):
    """Plots an image reprojected into polar coordinages with the origin
    at "origin" (a tuple of (x0, y0), defaults to the center of the image)"""
    polar_grid, r, theta = reproject_image_into_polar(data, origin)
    plt.figure()
    plt.imshow(polar_grid, extent=(theta.min(), theta.max(), r.max(), r.min()))
    plt.axis('auto')
    plt.ylim(plt.ylim()[::-1])
    plt.xlabel('Theta Coordinate (radians)')
    plt.ylabel('R Coordinate (pixels)')
    plt.title('Image in Polar Coordinates')

def index_coords(data, origin=None):
    """Creates x & y coords for the indicies in a numpy array "data".
    "origin" defaults to the center of the image. Specify origin=(0,0)
    to set the origin to the lower left corner of the image."""
    ny, nx = data.shape[:2]
    if origin is None:
        origin_x, origin_y = nx // 2, ny // 2
    else:
        origin_x, origin_y = origin
    x, y = np.meshgrid(np.arange(nx), np.arange(ny))
    x -= origin_x
    y -= origin_y
    return x, y

def cart2polar(x, y):
    r = np.sqrt(x**2 + y**2)
    theta = np.arctan2(y, x)
    return r, theta

def polar2cart(r, theta):
    x = r * np.cos(theta)
    y = r * np.sin(theta)
    return x, y

def bin_by(x, y, nbins=30):
    """Bin x by y, given paired observations of x & y.
    Returns the binned "x" values and the left edges of the bins."""
    bins = np.linspace(y.min(), y.max(), nbins+1)
    # To avoid extra bin for the max value
    bins[-1] += 1

    indicies = np.digitize(y, bins)

    output = []
    for i in xrange(1, len(bins)):
        output.append(x[indicies==i])

    # Just return the left edges of the bins
    bins = bins[:-1]

    return output, bins

def reproject_image_into_polar(data, origin=None):
    """Reprojects a 3D numpy array ("data") into a polar coordinate system.
    "origin" is a tuple of (x0, y0) and defaults to the center of the image."""
    ny, nx = data.shape[:2]
    if origin is None:
        origin = (nx//2, ny//2)

    # Determine that the min and max r and theta coords will be...
    x, y = index_coords(data, origin=origin)
    r, theta = cart2polar(x, y)

    # Make a regular (in polar space) grid based on the min and max r & theta
    r_i = np.linspace(r.min(), r.max(), nx)
    theta_i = np.linspace(theta.min(), theta.max(), ny)
    theta_grid, r_grid = np.meshgrid(theta_i, r_i)

    # Project the r and theta grid back into pixel coordinates
    xi, yi = polar2cart(r_grid, theta_grid)
    xi += origin[0] # We need to shift the origin back to
    yi += origin[1] # back to the lower-left corner...
    xi, yi = xi.flatten(), yi.flatten()
    coords = np.vstack((xi, yi)) # (map_coordinates requires a 2xn array)

    # Reproject each band individually and the restack
    # (uses less memory than reprojection the 3-dimensional array in one step)
    bands = []
    for band in data.T:
        zi = sp.ndimage.map_coordinates(band, coords, order=1)
        bands.append(zi.reshape((nx, ny)))
    output = np.dstack(bands)
    return output, r_i, theta_i

if __name__ == '__main__':
    main()

rawDescription: image information along a polar coordinate system

description: Image information along a polar coordinate system


rawDescription: Pythonic way to sort on tuple, dict item and convert to array


code:
from mymath import powerval

def summer(lst):
    total = 0

    for n in range(0, 13, 2):
        total += powerval(lst[n], lst[n + 1])

    return total

rawDescription: How I add values in a list I am using as the parameter for a function?


code:
def func(x):

    # Note the r!
    r'''Boring function

    Notes
    -----
    Let :math:`\bar{x}_k = \sum_{i=1}^{n_k}x_{ik}`,
    '''

rawDescription: Latex command \bar not working properly in Python docstring


code:
hdrs = ("A","B","C","D","E","F","G","H","% Done")
fmt_string = ''.join("%%-%is" % (len(h)+2) for h in hdrs)
print(fmt_string % hdrs)
print(fmt_string % tuple("-"*(len(h)+1) for h in hdrs))

rawDescription: print python list with width specifiers

description: Print python list with width specifiers


code:
setup(name='django-g-recaptcha',
      version='0.1.2',
      description='Django view decorator to validate google recaptcha forms',
      url='https://bitbucket.org/deltaskelta/django-g-recaptcha-validate/overview',
      author='Jeff Willette',
      author_email='jrwillette88@gmail.com',
      keywords = ['django', 'recaptcha', 'catpcha'],
      packages = ['g_recaptcha',],
      include_package_data = True
)

rawDescription: pypi package isn't installing with all the files?

description: Pypi package isn't installing with all the files


code:
import ast
value = u'{"city": u"\\xc1vila", "name": u"\\xc1vila, Castilla y Le\\xf3n, Spain", "zip": "", "country": "Spain", "longitude": -4.7, "state": "Castilla y Leon", "latitude": 40.65, "id": 113972385284243}'
ast.literal_eval(value)

rawDescription: How to decode a JSON unicode escaped entry from Facebook in python?

description: Decode a JSON unicode escaped entry from Facebook in python


code:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
from pylab import *

figure(figsize=(15, 8))
# use ginput to select markers for the sensors
matplotlib.pyplot.hot()

markers = [(269, 792, 0.65), (1661, 800, 0.5), (1017, 457, 0.8)]
x,y,t = zip(*markers)

img = mpimg.imread('floor.png')
imgplot = plt.imshow(img, cmap=cm.hot)
scatter(x, y, marker='h', c=t, s=150)

colorbar()
show()

rawDescription: Python Matplotlib point colour

description: Python Matplotlib point colour


code:
connection, pcc_address = pce.accept()
pcc_client = StreamSocket(connection, basecls=PCEPCommonHeader)

rawDescription: sr*() method not dissecting the answered packets in scapy

description: Sr*() method not dissecting the answered packets in scapy


code:
import foo
reload(foo)

rawDescription: How to update a executed script import in the Python shell after editing it?

description: Update a executed script import in the Python shell after editing it


code:
class Prompt:
    def __str__(self):
        # Logic to randomly determine string
        return string

rawDescription: Randomly change the prompt in the Python interpreter


code:
g = sns.FacetGrid(mapping, col=options.facetCol, row=options.facetRow, col_order=sorted(cols), hue=options.group, sharex=False)
g.map(sns.distplot, options.axis)
g.map(stats, options.axis)

# custom function that allows us to create a distplot and add offset annotations to each facet that is not empty
def stats(x, label, **kwargs):

    # calculate stats and create label
    n = len(x)
    mean = np.mean(x)
    std = np.std(x)
    label = r"%s: n=%s, $\mu$=%.2f $\sigma$=%.2f" %(label, n, mean, std)

    # create annotation
    y = 0.9 - len(ax.texts) * 0.05
    ax.annotate(label, xy=(0.05,y), xycoords='axes fraction', ha='left', size=8)

rawDescription: skipping empty facets in seaborn facetgrid for annotations

description: Skipping empty facets in seaborn facetgrid for annotations


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

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 4
  }
}

class App:

  @cherrypy.expose
  def default(self, *args, **kwargs):
    return u'It is me again at {0} with {1}'.format(args, kwargs)

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: cherrypy catch all route

description: Cherrypy catch all route


code:
import urllib2
from bs4 import BeautifulSoup as bs4

def get_all_info():
    i = 0
    while i < len(list1):
        url = urllib2.urlopen("https://in.finance.yahoo.com/q?s=" + list1[i] + "&ql=0")
        soup = bs4(url,"html.parser")
        price = soup.find(attrs={'id':"yfs_l84_" + list1[i]})
        if price:
            print ("real time price (for {0}): {1}".format(list1[i],price.contents[0]))
        i += 1

if __name__ == "__main__":
    stocks = raw_input("enter stocks names (space separated): ")
    list1 = stocks.split()
    get_all_info()

rawDescription: why did the raw_input fail?

description: Why did the raw_input fail


code:
from Bio import SeqUtils
pat = "ATNTTRTCNGGHGCN"
SeqUtils.nt_search("CCCCCCCATCTTGTCAGGCGCTCCCCCC", pat)

rawDescription: Search for motifs with degenerate positions


code:
import cv2
img = cv2.imread("lenna.png")
crop_img = img[200:400, 100:300] # Crop from x, y, w, h -> 100, 200, 300, 400
# NOTE: its img[y: y + h, x: x + w] and *not* img[x: x + w, y: y + h]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)

rawDescription: How to crop an image in OpenCV using Python

description: Crop an image in OpenCV using Python


code:
sites=['aaa', 'bbb']
contains = ' or '.join('contains(@href,(%s))' % site for site in sites)
anchor_xpath = etree.XPath('//a[%s][descendant::img]' % contains)

rawDescription: Select all anchor tags with an href attribute that contains one of multiple values via xpath in lxml / Python


code:
from bokeh.plotting import figure, output_file, show, ColumnDataSource, hplot
from bokeh.models import HoverTool, Callback, ColumnDataSource
import pandas as pd
output_file("bla.html")

# Mock data
m = np.ones((6,11))
for i in range(2,6):
    for j in range(11):
        m[i,j] = i+j
x = [0,1,2,3,4,5]; y = [0,2,4,6,8,10]
m0 = m.transpose()
m1 = pd.DataFrame(m0, index=['0','1','2','3','4','5','6','7','8','9','10'], columns=[np.arange(0,len(m),1).astype(str)])

#First plot
s1 = ColumnDataSource(data=dict(x=x,y=y))
p1 = figure(tools=["lasso_select"], plot_width=600, plot_height=400)
p1.scatter('x', 'y', fill_color='black', line_color=None, size=10, source=s1)

#Second plot
s2 = ColumnDataSource(data=dict(x=[],y=[],y2=[]))
p2 = figure(plot_width=400, plot_height=400, tools =[])

m1 = ColumnDataSource(m1) #Actual Datasource for the second plot
p2.line(np.arange(0,100,1), 'y' , source=s2) # From original data - series 1
p2.line(np.arange(0,100,1), 'y2' , source=s2) # From original data - series 2

s1.callback = Callback(args=dict(s2=s2, m1=m1), code="""
  var inds = cb_obj.get('selected')['1d'].indices;
  var d1 = m1.get('data');
  var d2 = s2.get('data');
  d2['y'] = []
  d2['y2'] = []
  for (i = 0; i < 11; i++) {
    d2['y'].push(d1[inds['0']][i]),
    d2['y2'].push(d1[inds['1']][i])
  }
  s2.trigger('change');
""")

layout = hplot(p1, p2)
show(layout)

rawDescription: Have Bokeh Callback update a list instead of a ColumnDataSource?


code:
def f(a, b, c):
    param_values = locals()  # Line must be very first in function.
    print(param_values)
f(1, 2, 3)

rawDescription: Is it possible to get formal argument names/values as a dictionary?


code:
class LeaderboardTable(tables.Table):
    rank = tables.Column()
    name = tables.Column(order_by=("first_name", "last_name"))
    team = tables.Column()
    points = tables.Column()

    def render_name(self, record):
        return u"%s %s" % (record.user.first_name, record.user.last_name)

rawDescription: django-tables2 refreshes on sorting and page change

description: Django-tables2 refreshes on sorting and page change


code:
def get_single_table_data(cursor, tbl):
    '''
    Generator to get all data from one table.
    Does this one row at a time, so we don't load
    too much data in at once
    '''
    sql = "SELECT * from %s" % tbl
    cursor.execute(sql)
    while True:
        row = cursor.fetchone()
        if row is None:
            break
        yield row

def print_all_table_data(cursor, schema):
    for tbl, cols in schema.items():
        print(cols)
        rows = get_single_table_data(cursor, tbl)
        for row in rows:
            print(row)

rawDescription: Reading large amount of data from Access database


code:
class Node(db.Model):
    children = db.ListProperty(db.Key)

rawDescription: Google appengine datastore tree structure


code:
import os
import sys
import imp
import contextlib

@contextlib.contextmanager
def preserve_value(namespace, name):
    """ A context manager to preserve, then restore, the specified binding.

        :param namespace: The namespace object (e.g. a class or dict)
            containing the name binding.
        :param name: The name of the binding to be preserved.
        :yield: None.

        When the context manager is entered, the current value bound to
        `name` in `namespace` is saved. When the context manager is
        exited, the binding is re-established to the saved value.

        """
    saved_value = getattr(namespace, name)
    yield
    setattr(namespace, name, saved_value)

def make_module_from_file(module_name, module_filepath):
    """ Make a new module object from the source code in specified file.

        :param module_name: The name of the resulting module object.
        :param module_filepath: The filesystem path to open for
            reading the module's Python source.
        :return: The module object.

        The Python import mechanism is not used. No cached bytecode
        file is created, and no entry is placed in `sys.modules`.

        """
    py_source_open_mode = 'U'
    py_source_description = (".py", py_source_open_mode, imp.PY_SOURCE)

    with open(module_filepath, py_source_open_mode) as module_file:
        with preserve_value(sys, 'dont_write_bytecode'):
            sys.dont_write_bytecode = True
            module = imp.load_module(
                    module_name, module_file, module_filepath,
                    py_source_description)

    return module

def import_program_as_module(program_filepath):
    """ Import module from program file `program_filepath`.

        :param program_filepath: The full filesystem path to the program.
            This name will be used for both the source file to read, and
            the resulting module name.
        :return: The module object.

        A program file has an arbitrary name; it is not suitable to
        create a corresponding bytecode file alongside. So the creation
        of bytecode is suppressed during the import.

        The module object will also be added to `sys.modules`.

        """
    module_name = os.path.basename(program_filepath)

    module = make_module_from_file(module_name, program_filename)
    sys.modules[module_name] = module

    return module

rawDescription: Import arbitrary-named file as a Python module, without generating bytecode file


rawDescription: Python Difference between x = x+1 and x += 1


code:
class StoryWidget(GridLayout):
    def __init__(self,**kwargs):
        self.cols=1
        self.rows=1
        super(StoryWidget, self).__init__(**kwargs)
        topLayout=BoxLayout(orientation = "vertical")
        topLayout.add_widget(Button(text="first"))
        topLayout.add_widget(Button(text="second"))
        self.add_widget(topLayout)

    with self.canvas.before:
        Color(.9,.9,1)
        self.Backgroud = Rectangle(pos=self.pos,size=self.size)

    self.bind(pos=self.repaint,size=self.repaint)
    self.bind(pos=self.resize,size=self.resize)

rawDescription: Kivy - Create new widget and set its position and size


code:
df = pd.DataFrame(['foo','bar','baz', 'foo','bar'], columns=['test'])
df['test'].value_counts()

rawDescription: Python - how to pass a dynamic Series name and DataFrame name as a function argument?


code:
modelName = ['Toyota', 'Nissan',  'Honda']
fuelEfficiency = [15.0, 20.0, 30.0]
priceGas = 2.41
totalCost1 = (10000 * priceGas)/15.0
totalCost2 = (10000 * priceGas)/20.0      # totalCost = list(map(lambda x: (10000*priceGas)/x, fuelEfficiency))
totalCost3 = (10000 * priceGas)/30.0
totalCost = [totalCost1, totalCost2, totalCost3]

print("Model", "Cost(MPG)", "TOTALCOST")
for x in range(3):
    print(modelName[x], fuelEfficiency[x], totalCost[x])

rawDescription: how to loop through 3 lists and get 3 columns in Python?

description: Loop through 3 lists and get 3 columns in Python


code:
class Spam:
    ...
    def __init__(self):
        self.filename = None

    def saveFile(self):
        if not self.filename:
            self.filename = QtGui.QFileDialog.getSaveFileName(...)
            # here you should check if the dialog wasn't cancelled
        with open(filename, 'w') as f:
            f.write(self.text.toPlainText())
    ...

rawDescription: Save Dialog only appear once?

description: Save Dialog only appear once


code:
from turtle import *

screen = Screen() # create the screen

turtle = Turtle() # create the first turtle
screen.onscreenclick(turtle.goto) # set up the callback for moving the first turtle

turtle2 = Turtle() # create the second turtle

def move_second(): # the function to move the second turtle
    turtle2.back(100)
    turtle2.forward(200)
    turtle2.back(100)
    screen.ontimer(move_second) # which sets itself up to be called again

screen.ontimer(move_second) # set up the initial call to the callback

screen.mainloop() # start everything running

rawDescription: Python - Move Two Turtle Objects At Once


code:
import re
import json

point_re = re.compile('.*routePoints =(.*);')
point_json = point_re.search(str(soup)).group(1)
point_data = json.loads(point_json)

rawDescription: Scraping javascript using python

description: Scraping javascript using python


code:
def patterns(prefix, *args):
    warnings.warn(
        'django.conf.urls.patterns() is deprecated and will be removed in '
        'Django 1.10. Update your urlpatterns to be a list of '
        'django.conf.urls.url() instances instead.',
        RemovedInDjango110Warning, stacklevel=2
    )

rawDescription: What is the benefit of using django.conf.urls.patterns versus a list of url in Django


code:
class a:
    @classmethod
    def spam(cls):
        # not really pass, but you get the idea
        pass

    lut = [1,
           3,
           17,
           [12,34],
           5,
           spam]

assert a().lut[-1] == a.spam
assert a.spam() is None

rawDescription: referencing class methods in class lists in Python

description: Referencing class methods in class lists in Python


rawDescription: How do I push coordinates from a pandas dataframe to into a List?

description: Push coordinates from a pandas dataframe to into a List


code:
import sys
# This is bad, but Iam lazy
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyWindow(QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.main_menu = self.menuBar()
        widget = QWidget()
        self.menuList = []
        layout2 = QVBoxLayout(widget)
        self.menuButton = QPushButton("Add Menu")
        self.menuRmButton = QPushButton("Remove Menu")
        layout2.addWidget(self.menuButton)
        layout2.addWidget(self.menuRmButton)
        self.menuButton.clicked.connect(self.create_menu)
        self.menuRmButton.clicked.connect(self.removeMenu)
        self.setCentralWidget(widget)

    def create_menu(self):
        menu2 = self.main_menu.addMenu('Menu 1')
        self.menuList.append(menu2)
        Action1=QAction('Menu 1 0',self)
        Action1.triggered.connect(self.action_1)
        menu2.addAction(Action1)

        Action2=QAction('Menu 1 1',self)
        Action2.triggered.connect(self.action_2)
        menu2.addAction(Action2)

    def removeMenu(self):
        if self.menuList:
            for eachMenu in self.menuList:
                menuAct = eachMenu.menuAction()
                self.main_menu.removeAction(menuAct)
                # just for safe side
                menuAct.deleteLater()
                eachMenu.deleteLater()

    def action_1(self):
        print('Menu 1 0')

    def action_2(self):
        print('Menu 1 1')

if __name__ == '__main__':
    app=QApplication(sys.argv)
    new=MyWindow()
    new.show()
    app.exec_()

rawDescription: Remove top level QMenu from QMenubar programmatically


code:
class Celebrity(models.Model):
    name = models.CharField()

class Image(models.Model):
    celebrity = models.ForeignKey(Celebrity)
    image = models.ImageField()

class InlineImage(admin.TabularInline):
    model = Image

class CelebrityAdmin(admin.ModelAdmin):
    inlines = [InlineImage]

admin.site.register(Celebrity, CelebrityAdmin)

rawDescription: Uploading images using Django Admin?

description: Uploading images using Django Admin


code:
class FunctionDetail(DetailView):
     ...
     def get_context_data(self, **kwargs):
        context = super(FunctionDetail, self).get_context_data(**kwargs)

        if 'function_id' in kwargs:  #this is how you can get function_id's data from url
            _id = int(kwargs['function_id'] or '0')
        else:
            _id = 0
        function =  Function.objects.get(id=_id)
        context['role_function'] = RoletoFunction.objects.filter(function=function)
        return context

rawDescription: filter view from url parameter with an intermediate model?

description: Filter view from url parameter with an intermediate model


code:
import re
regex = re.compile('foo (?:bar)*')
regex.pattern

rawDescription: How to decompile a regex?

description: Decompile a regex


rawDescription: Pandas object from Pickle - Type not known by the IDE


code:
import matplotlib.pyplot as plt
import numpy as np
zvals = np.loadtxt("sharedGradient.txt")

zvals = zvals/200
plt.subplot(2,2,1)
img = plt.imshow(zvals,interpolation='nearest')
plt.colorbar(img)
plt.subplot(2,2,2)
img = plt.imshow(zvals)
plt.colorbar(img)
plt.subplot(2,2,3)
img = plt.imshow(zvals)
plt.colorbar(img)
plt.subplot(2,2,4)
img = plt.imshow(zvals)
plt.colorbar(img)
plt.show()

rawDescription: Gradient four figures scale

description: Gradient four figures scale


code:
with open(keyfile, 'rb') as f:
    key = f.read()
encrypt = 1
cipher = Cipher(alg='des_ede3_ecb', key=key, op=encrypt, iv='\0'*16)
ciphertext = cipher.update(plaintext)
ciphertext += cipher.final()

rawDescription: How to 3DES encrypt in Python using the M2Crypto wrapper?


code:
class RemoveNodeDiGraph(DiGraph):
    def remove_node(self, n):
        DiGraph.remove_node(self, n)
        print("Remove node: %s"%n)

    def remove_nodes_from(self, nodes):
        for n in nodes:
            self.remove_node(n)

if __name__=='__main__':
    G = RemoveNodeDiGraph()
    G.add_node('foo')
    G.add_nodes_from('bar',weight=8)
    G.remove_node('b')
    G.remove_nodes_from('ar')

rawDescription: Networkx node deletion / removal callback


code:
import threading

def task1():
    pass
def task2():
    pass
def task3():
    pass
def task4():
    pass
def task5():
    pass
def task6():
    pass

def dep1():
    t1 = threading.Thread(target=task1)
    t2 = threading.Thread(target=task2)
    t3 = threading.Thread(target=task3)

    t1.start()
    t2.start()
    t3.start()

    t1.join()
    t2.join()
    t3.join()

def  dep2():
    t4 = threading.Thread(target=task4)
    t5 = threading.Thread(target=task5)

    t4.start()
    t5.start()

    t4.join()
    t5.join()

def dep3():
    d1 = threading.Thread(target=dep1)
    d2 = threading.Thread(target=dep2)

    d1.start()
    d2.start()

    d1.join()
    d2.join()

d3 = threading.Thread(target=dep3)
d3.start()
d3.join()

rawDescription: Executing tasks in parallel in python

description: Executing tasks in parallel in python


code:
import io
import matplotlib.pyplot as plt
from PySide.QtGui import QApplication, QImage

def add_clipboard_to_figures():
    # use monkey-patching to replace the original plt.figure() function with
    # our own, which supports clipboard-copying
    oldfig = plt.figure

    def newfig(*args, **kwargs):
        fig = oldfig(*args, **kwargs)
        def clipboard_handler(event):
            if event.key == 'ctrl+c':
                # store the image in a buffer using savefig(), this has the
                # advantage of applying all the default savefig parameters
                # such as background color; those would be ignored if you simply
                # grab the canvas using Qt
                buf = io.BytesIO()
                fig.savefig(buf)
                QApplication.clipboard().setImage(QImage.fromData(buf.getvalue()))
                buf.close()

        fig.canvas.mpl_connect('key_press_event', clipboard_handler)
        return fig

    plt.figure = newfig

add_clipboard_to_figures()

rawDescription: How to add clipboard support to Matplotlib figures?

description: Add clipboard support to Matplotlib figures


code:
def __add__(self, other):
    """Returns two FootMeasures added together"""
    return FootMeasure(self.__feet + other.__feet,
                       self.__inches + other.__inches)

rawDescription: How to make an add method to a Python class?

description: Make an add method to a Python class


code:
import numpy as np

A = [[2,3,1,3,2,3,3], [4,2,1,4]]
B = [[np.zeros(2)]*len(A[0]), [np.zeros(2)]*len(A[1])]

indices = np.array([np.unique(a, True)[1] for a in A])

A = np.array([np.array(arr)[index] for arr, index in zip(A, indices)])
B = np.array([np.array(arr)[index] for arr, index in zip(B, indices)])

rawDescription: Recover data from lists in Python

description: Recover data from lists in Python


code:
import whatever

def this_is_a_function(parameter):
    pass

whatever.this_is_a_function = this_is_a_function

rawDescription: How can I hook a function in a python module?

description: Hook a function in a python module


rawDescription: Python - dictionary of lists

description: Python - dictionary of lists


code:
import urllib

form_fields = {
  "first_name": "Albert",
  "last_name": "Johnson",
  "email_address": "Albert.Johnson@example.com"
}
form_data = urllib.urlencode(form_fields)
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
result = urlfetch.fetch(url=url,
                        payload=form_data,
                        method=urlfetch.POST,
                        headers=headers)

rawDescription: Google App Engine self.redirect post

description: Google App Engine self.redirect post


code:
import re
string= '#$#&^&#$@||||123515'
string = re.sub('[\W\_]','',string)
string

rawDescription: How to remove all special char in string by python?

description: Remove all special char in string by python


code:
import web

urls = (
    '/(\d+)', 'index',
    '/number', 'novo'
)

class index:
    def GET(self, number):
        return "Number: %i " % number

class number:
    def GET(self):
        get_index = index()
        return get_index.GET(3)

app = web.application(urls, globals())
if __name__ == "__main__":
    app.run()

rawDescription: Webpy, calling a view from another method


code:
classes = {}
for name in classlist:
    class Handler(BaseHandler):
        def get(self):
            response = HTTPResponse()
            response.write(self.__class__.__name__)
            return response
    Handler.__name__ = name
    classes[name] = Handler

rawDescription: Create multiple classes from List of Strings


code:
import base64
import requests

response = requests.get(url)
uri = ("data:" +
       response.headers['Content-Type'] + ";" +
       "base64," + base64.b64encode(response.content))

rawDescription: Python requests base64 image

description: Python requests base64 image


code:
img = None
for f in files:
    im=pl.imread(f)
    if img is None:
        img = pl.imshow(im)
    else:
        img.set_data(im)
    pl.pause(.1)
    pl.draw()

rawDescription: Display sequence of images using matplotlib


code:
import matplotlib.pyplot as plt
import matplotlib.dates as md

import datetime

fig = plt.figure()
ax = fig.add_subplot(111)

t0 = datetime.datetime(2015,4,1)
t = [t0+datetime.timedelta(days=j) for j in xrange(20)]
y = range(20)
ax.plot(t, y)

x0 = md.date2num(datetime.datetime(2015,4,5))
y0 = 10
xw = md.date2num(datetime.datetime(2015,4,7)) - x0
yw = 10
arr = plt.Arrow(x0, y0, xw, yw, edgecolor='black')
ax.add_patch(arr)
arr.set_facecolor('b')
fig.autofmt_xdate()
plt.show()

rawDescription: How to draw an arrow in matplotlib if one axis contains time?

description: Draw an arrow in matplotlib if one axis contains time


code:
input = '/Users/Opus_Magnum/Desktop/list.txt'
input_dir = os.path.dirname(input)
output = 'test_output.txt'
temp_out = os.path.join(input_dir, output)

rawDescription: Analagous operations to achieve os.path.split in Python?


code:
class Article(db.Model):
  body = db.TextProperty()

class Comment(db.Model):
  article = db.ReferenceProperty(Article)
  body = db.TextProperty()

comment = Comment.all().get()

# The explicit reference from one comment to one article
# is represented by a Key object
article_key = comment.article

# which gets lazy-loaded to a Model instance by accessing a property
article_body = comment.article.body

# The implicit back-reference from one article to many comments
# is represented by a Query object
article_comments = comment.article.comment_set

# If the article only has one comment, this gives us a round trip
comment = comment.article.comment_set.all().get()

rawDescription: How to do a back-reference on Google AppEngine?

description: Do a back-reference on Google AppEngine


rawDescription: matching 1d arrays in 2d arrays in python

description: Matching 1d arrays in 2d arrays in python


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

# the input data is in a list of tuples (x, y, z)
# where x and y are coordinates in (0..n-1) and z a base type in TCAG
indata = [
    (0,1,'C'),
    (0,2,'G'),
    (0,3,'T'),
    (1,2,'C'),
    (1,1,'H'),
    (1,3,'G'),
    (2,1,'T'),
    (2,2,'C'),
    (2,3,'G') ]

# you want to have a color for each character:
colordict = {
    'C': (1, 1, 0, 1),
    'G': (0, 1, 0, 1),
    'A': (1, 0, 0, 1),
    'T': (0, 1, 1, 1),
    'H': (1, 0, .5, 1) }

# find the maximum positions in x and y
xmax = max(indata, key=lambda p: p[0])[0]
ymax = max(indata, key=lambda p: p[1])[1]

# create an image
img = np.zeros((ymax+1, xmax+1, 4))

# populate the image with the correct colors
for p in indata:
    img[p[1], p[0]] = colordict[p[2]]

# show the color map:
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(img, aspect='auto', interpolation='nearest', origin='lower')

rawDescription: How plot data from VMD *.tml file with color coding guided by an Alphabetic Character


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.window_1 = wx.SplitterWindow(self, wx.ID_ANY, style=wx.SP_3D | wx.SP_BORDER)
        self.window_1_pane_1 = wx.Panel(self.window_1, wx.ID_ANY)
        self.window_1_pane_2 = wx.Panel(self.window_1, wx.ID_ANY)

        self.__set_properties()
        self.__do_layout()

    def __set_properties(self):
        self.SetTitle("frame_1")
        self.window_1_pane_1.SetBackgroundColour(wx.Colour(255, 255, 0))
        self.window_1_pane_2.SetBackgroundColour(wx.Colour(50, 153, 204))

    def __do_layout(self):
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2)
        sizer_1.Add(self.window_1, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()

if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    frame_1 = MyFrame(None, wx.ID_ANY, "")
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()

rawDescription: Make a wxPanel resizable by the user

description: Make a wxPanel resizable by the user


code:
import numpy as np
foo_array = [38,26,14,55,31,0,15,8,0,0,0,18,40,27,3,19,0,49,29,21,5,38,29,17,16]
foo = np.array(foo_array)
# Compute the median of the non-zero elements
m = np.median(foo[foo > 0])
# Assign the median to the zero elements
foo[foo == 0] = m

rawDescription: replace zeroes in numpy array with the median value

description: Replace zeroes in numpy array with the median value


code:
# state_slugs lets you lookup either state name or code => its slug
state_slugs = {}
# states_from_slugs lets you lookup the slug => the state name
states_from_slugs = {}

for state_name, state_code in state_dict.items():
    slug = state_name.lower().replace(' ', '_')
    state_slugs[state_name] = slug
    state_slugs[state_code] = slug
    states_from_slugs[slug] = state_name

rawDescription: Dealing with spaces in Flask url creation


code:
import numpy
m = 10
X = numpy.random.rand(m, m)
Y = numpy.random.rand(m)
indices = numpy.random.permutation(m)
indices
Y
Y = Y[indices]
Y
X = X[indices, :]

rawDescription: How to shuffle a matrix and an array accordingly

description: Shuffle a matrix and an array accordingly


code:
import numpy
numpy.__version__
A = numpy.matrix([[1,3,7],[2,8,3],[7,8,1]])
numpy.linalg.matrix_rank(A)

rawDescription: Calculate Matrix Rank using scipy

description: Calculate Matrix Rank using scipy


code:
def add(args):
    conn = sqlite3.connect('todo.db')
    c = conn.cursor()
    c.execute("INSERT INTO todo VALUES (args, timestamp)")

parser.add_argument('-a', '--add', type=add)

rawDescription: Execute function via arg

description: Execute function via arg


rawDescription: numpy array : can not find how to transform the array

description: Numpy array : can not find how to transform the array


code:
from fabric.context_managers import settings
from fabric.api import *
with settings(host_string='username@host',user='runcommand_user'):
     run('command')

rawDescription: Run python script in a remote machines as a sudo user


rawDescription: How to properly store object reference in treemodel?

description: Properly store object reference in treemodel


code:
from collections import defaultdict

places_by_state = defaultdict(list)
for place in Place.objects.all():
   places_by_state[place.state].append(place)
list_of_places_by_state = places_by_state.values()

rawDescription: What is the best way of creating a list of querysets in django?


code:
from struct import pack, unpack
unpack('BB', pack('H',300))
# gives (44, 1), the two bytes you were asking for

rawDescription: Representing a number using two bytes

description: Representing a number using two bytes


rawDescription: Why does an assignment for double-sliced numpy arrays not work?


code:
import itertools
def hash_on_each_end_permutations(array):
    array = list(array)
    array.remove('#')
    array.remove('#')
    for subpermutation in itertools.permutations(array):
        yield '#' + ''.join(subpermutation) + '#'

rawDescription: Filter through Permutations

description: Filter through Permutations


rawDescription: Writing title for a figure with calculated values NetworkX


code:
i = xminf

zaehler = 0

while(i < xmaxf):
    j = yminf
    while(j < ymaxf):
        arcpy.AddMessage("Check in-While, Klappe Nr: " + str(zaehler))
        zaehler += 1
        arcpy.AddMessage(str(i) + " " +str(j))
        j += cellsizef
    i += cellsizef

rawDescription: While-Loop does not work correctly

description: While-Loop does not work correctly


code:
import twitter
from inspect import getfile

print(getfile(twitter))

rawDescription: which package does 'import twitter' import?

description: Which package does 'import twitter' import


rawDescription: Writing unicode with python - what is wrong with this character


code:
data2 = {k: {m: n for i in v for m, n in i.iteritems()} for x in data for k, v in x.iteritems()}
data2
pd.DataFrame(data2)

rawDescription: Reorganizing the data in a dataframe

description: Reorganizing the data in a dataframe


code: for cmd in command: os.system(cmd)

rawDescription: Event loop in Python for CMD interaction


rawDescription: Python: int to binary stream element?

description: Python: int to binary stream element


code:
import numpy as np
import matplotlib.pyplot as plt
menMeans   = (5, 15, 30, 40)
menStd     = (2, 3, 4, 5)
ind  = np.arange(4)    # the x locations for the groups
width= 0.7
labels = ('A', 'B', 'C', 'D')

# Pull the formatting out here
bar_kwargs = {'width':width,'color':'y','linewidth':2,'zorder':5}
err_kwargs = {'zorder':0,'fmt':None,'lw':2,'ecolor':'k'}

X = ind+width/2

fig, ax = plt.subplots()
ax.p1 = plt.bar(ind, menMeans, **bar_kwargs)
ax.errs = plt.errorbar(X, menMeans, yerr=menStd, **err_kwargs)

# Custom function to draw the diff bars

def label_diff(i,j,text,X,Y):
    x = (X[i]+X[j])/2
    y = 1.1*max(Y[i], Y[j])
    dx = abs(X[i]-X[j])

    props = {'connectionstyle':'bar','arrowstyle':'-',\
                 'shrinkA':20,'shrinkB':20,'lw':2}
    ax.annotate(text, xy=(X[i],y+7), zorder=10)
    ax.annotate('', xy=(X[i],y), xytext=(X[j],y), arrowprops=props)

# Call the function
label_diff(0,1,'p=0.0370',X,menMeans)
label_diff(1,2,'p<0.0001',X,menMeans)
label_diff(2,3,'p=0.0025',X,menMeans)

plt.ylim(ymax=60)
plt.xticks(X, labels, color='k')
plt.show()

rawDescription: Indicating the statistically significant difference in bar graph


code:
while True:
    buffer += ser.read(ser.inWaiting())
    if '\n' in buffer:
        if buffer[0] == '$':
            x= re.sub("[^0-9\,]","", buffer)
            x1 = x.rstrip()
            x2= x1.split(",")
            print((x2[0]),(x2[1]),(x2[2]))
        buffer = ""

rawDescription: Python error in If-Then statement

description: Python error in If-Then statement


rawDescription: pymongo - querying most recent N items

description: Pymongo - querying most recent N items


code:
import matplotlib.pyplot as plt
# Builtin colourmap "seismic" has the blue-white-red
#   scale you want
plt.pcolor(np.array(data), cmap=plt.cm.seismic, vmin=0, vmax=2)
plt.colorbar()
plt.show()

rawDescription: How to create predefined color range in Matplotlib heat map from a Pandas Dataframe

description: Create predefined color range in Matplotlib heat map from a Pandas Dataframe


code:
# Python immports
import functools

# Tornado imports
import tornado.ioloop
import tornado.web
import tornado.httpserver

# XMLRpc imports
import xmlrpclib

# Asynchronous gevent decorator
def gasync(func):
    @tornado.web.asynchronous
    @functools.wraps(func)
    def f(self, *args, **kwargs):
        return gevent.spawn(func, self, *args, **kwargs)
    return f

# Our XML RPC service
xml_service = xmlrpclib.ServerProxy('http://remote_host/rpc/')

class MyHandler(tornado.web.RequestHandler):
    @gasync
    def get(self):
        # This doesn't block tornado thanks to gevent
        # Which patches all of xmlrpclib's socket calls
        # So they no longer are blocking
        result = xml_service.system.listmethods()

        # Do something here

        # Write response to client
        self.write('hello')
        self.finish()

# Our URL Mappings
handlers = [
   (r"/", MyHandler),
]

def main():
    # Setup app and HTTP server
    application = tornado.web.Application(handlers)
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8000)

    # Start ioloop
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

rawDescription: Python. Tornado. Non-blocking xmlrpc client


code:
import file2

object = file2.file2()  # create an instance of the class
object.function()       # call the function to parse the arguments

rawDescription: Inheriting command a file lib argparser

description: Inheriting command a file lib argparser


code:
@app.route('/hello')
def hello():
    r = requests.get('http://www.google.com')
    return r.text

rawDescription: how to call another webservice api from flask

description: Call another webservice api from flask


code:
h, w = np.shape(new_image)
new_image = new_image[max(0, -y):min(h, h-y),max(0, -x):min(w, w-x)]

h, w = np.shape(new_base)
new_base = new_base[max(0, y):min(h, h+y),max(0, x):min(w, w+x)]

rawDescription: Is there a nice way to slice Python numpy ndarrays without checking sign of the bounds?


code:
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter, landscape
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, Frame,Table, TableStyle, NextPageTemplate, PageTemplate, BaseDocTemplate
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus.flowables import Flowable, PageBreak
from pyPdf import PdfFileReader, PdfFileWriter
import glob, os
from reportlab.lib.pagesizes import letter, A4

def make_portrait(canvas,doc):
    canvas.setPageSize(letter)

def make_landscape(canvas,doc):
    canvas.setPageSize(landscape(letter))

doc = BaseDocTemplate("NextPageExample.pdf",showBoundary=1)
elements = []
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name='normal', fontSize=6, leading = 7, alignment=TA_LEFT))

frame1 = Frame(doc.leftMargin, doc.height-5*inch,
                doc.width, 5*inch,
                leftPadding = 0, rightPadding = 0,
                topPadding = 0, bottomPadding = 0,
                id='frame1')

ptemplate = PageTemplate(id='portrait',frames =[frame1], onPage=make_portrait)
ltemplate = PageTemplate(id='landscape',frames =[frame1], onPage=make_landscape)
doc.addPageTemplates([ptemplate, ltemplate])
elements.append(Paragraph("Table is here.",styles["normal"]))
elements.append(NextPageTemplate('landscape'))
elements.append(PageBreak())
elements.append(Paragraph("Pictures are to be placed here.",styles["normal"]))

doc.build(elements)
del elements

rawDescription: How do you change from Landscape to Portrait Layout in python ReportLab?

description: Change from Landscape to Portrait Layout in python ReportLab


code:
class Subnet(models.Model):
    network_address = models.IPAddressField()
    subnet_prefix = models.ForeignKey(SubnetPrefix)

    def save(self, *args, **kwargs):
        created = not self.pk
        super(Subnet, self).save(*args, **kwargs)
        if created:
            create_ip_addresses(self)

rawDescription: How do I run a method when a model gets created?

description: Run a method when a model gets created


code:
class Post(models.Model):
    ...
    comments = models.ManyToManyField('Comment')
    # link to all comments, even children of comments

class Comment(models.Model):
    ...
    child_comments = models.ManyToManyField('Comment')
    # You may find it easier to organise these into a tree
    # if you use a parent_comment ForeignKey. That way the
    # top level comments have no parent and can be easily spotted.

Post.objects.all().select_related('comments').get(pk=1)

rawDescription: Django Threaded Commenting System

description: Django Threaded Commenting System


code:
df["B"].str.contains("apple", case=False)
df[df["B"].str.contains("apple", case=False)]

rawDescription: Regex to find instance of word in any circumstance within a line


code:
import os
import re

print([x for x in os.listdir(".") if re.match(r"[a-z]+[0-9]+", x)])

rawDescription: SCons Regexp Instead of Glob?

description: SCons Regexp Instead of Glob


code:
dict = {}
list = []
for a in A.objects.all():
    dict[a] = a.things.all().order_by("-score")[0].text
for k, v in sorted(dict.items(), key=lambda x: x[1]):
    list.append(k)

rawDescription: Django: order by field of many-to-many relation


code:
class SomeClass:
    class_dict = {0:0,1:1,2:2,3:3}

newClass = SomeClass()

for n, o in newClass.class_dict.iteritems():
    print(o)

rawDescription: Python: "as" keyword for shorthand

description: Python: "as" keyword for shorthand


code: {{ user.username|e }}

rawDescription: jinja2: html escape variables

description: Jinja2: html escape variables


code: thr_core0 = (thr_core0 + [fpid[thread]])[:2]

rawDescription: Limit length of list python

description: Limit length of list python


code:
def mylogin(request):
    app = request.GET.get('app')
    ...

rawDescription: django: passing parameters in URLConf

description: Django: passing parameters in URLConf


code:
x="hai this is an exe file created from python scripts using cxfreeze. Press Enter to exit >> "
y=input(x)

rawDescription: How to make others use my Python Script

description: Make others use my Python Script


code:
class api(tornado.web.RequestHandler):
    def initialize(self, *args, **kwargs):
        self.remote_ip = self.request.headers.get('X-Forwarded-For', self.request.headers.get('X-Real-Ip', self.request.remote_ip))
        self.using_ssl = (self.request.headers.get('X-Scheme', 'http') == 'https')
    def get(self):
        self.write("Hello " + ("s" if self.using_ssl else "") + " " + self.remote_ip)

rawDescription: Retrieve browser headers in Python

description: Retrieve browser headers in Python


code:
class FibSet:
    '''Fibonacci sequence with the in operator defined'''

    def __init__(self):
        self.a, self.b = 0, 1
        self.fib = set()

    def __contains__(self, n):
        if n > self.b:
            self.compute_upto(n)
        return n in self.fib

    def compute_upto(self, n):
        while self.b < n:
            self.fib.add(self.a)
            self.a, self.b = self.b, self.a + self.b

rawDescription: python using the fibonacci sequence

description: Python using the fibonacci sequence


code:
import Tkinter as tk
from PIL import ImageTk
import glob

IMAGES = glob.glob("*.png")
DEFAULT_IMAGE = IMAGES[0]

class QuestionWindow(tk.Frame):
    def __init__(self,parent):
        self.parent=parent
        tk.Frame.__init__(self)
        self.init_window()

    def update_image(self,move=0):
        """
        move = +1 jumps to the next image in the sequence
        move = -1 skips back to the previous image in the sequence
        move = +2 jumps... you get it.
        """
        self.img_idx += move
        fname = IMAGES[self.img_idx%len(IMAGES)]

        # here generate the image and make sure a reference is
        # kept in the form of a class attribute.
        self.img = ImageTk.PhotoImage(file=fname)

        # set the label image.
        self.question_lbl.configure(image=self.img)

    def init_window(self):
        self.img_idx = 0

        # choose a default image for startup
        self.img = ImageTk.PhotoImage(file=DEFAULT_IMAGE)

        # This is the question label that will contain the image
        self.question_lbl = tk.Label(self,image=self.img)
        self.question_lbl.pack(anchor=tk.N, side=tk.TOP, fill=tk.BOTH, expand=1)

        # These are the next and prev buttons. Note that they are using lambdas to
        # generate partial functions that call update_image,
        self.next_btn = tk.Button(self,text="Next",command=lambda:self.update_image(+1))
        self.next_btn.pack(anchor=tk.S,side=tk.RIGHT)

        self.prev_btn = tk.Button(self,text="Previous",command=lambda:self.update_image(-1))
        self.prev_btn.pack(anchor=tk.S,side=tk.LEFT)

if __name__ == "__main__":
    root = tk.Tk()
    qw = QuestionWindow(root)
    qw.pack()
    root.mainloop()

rawDescription: Tkinter changing image on a canvas

description: Tkinter changing image on a canvas


code:
import csv

f1 = open ("ted.csv")
oldFile1 = csv.reader(f1, delimiter=',')
oldList1 = list(oldFile1)

f2 = open ("ted2.csv")
newFile2 = csv.reader(f2, delimiter=',')
newList2 = list(newFile2)

f1.close()
f2.close()

output1 = set(tuple(row) for row in newList2 if row not in oldList1)
output2 = set(tuple(row) for row in oldList1 if row not in newList2)

with open('Michal_K.csv','w') as csvfile:
        wr = csv.writer(csvfile,delimiter=',')
        for line in (output2).difference(output1):
            wr.writerow(line)

rawDescription: Python how to write a set of tuples to csv


rawDescription: Python convert list of str to list of lists


code:
x, y, z = randn(100), randn(100), randn(100)
fig = plt.figure()
from mpl_toolkits.mplot3d import Axes3D
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c=randn(100))
plt.show()

rawDescription: Python matplotlib : plot3D with a color for 4D


code:
from TorCtl import TorCtl

conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="123")

TorCtl.Connection.send_signal(conn, "NEWNYM")

rawDescription: Python - Controlling Tor

description: Python - Controlling Tor


code:
related_fields = ['customer__name', 'customer__address__postcode', 'date']
item_fields = Item.objects.filter(pk=item).values_list(*related_fields, flat=True)[0]

rawDescription: Elegant way of finding related fields in Django


code:
if sys.platform == 'linux2':
    subprocess.call(["xdg-open", file])
else:
    os.startfile(file)

rawDescription: How to open a file with the standard application?

description: Open a file with the standard application


code:
import numpy as np
from PIL import Image

im = Image.open('my_file.tif')
im = im.convert('RGBA')
data = np.array(im)
# just use the rgb values for comparison
rgb = data[:,:,:3]
color = [246, 213, 139]   # Original value
black = [0,0,0, 255]
white = [255,255,255,255]
mask = np.all(rgb == color, axis = -1)
# change all pixels that match color to white
data[mask] = white

# change all pixels that don't match color to black
##data[np.logical_not(mask)] = black
new_im = Image.fromarray(data)
new_im.save('new_file.tif')

rawDescription: Remove background colour from image using Python/PIL


code:
def __init__(self):
    super(TestLayer, self).__init__()
    self.sprite = cocos.sprite.Sprite('grossini.png')
    self.sprite.position = 320, 340
    self.add(sprite)
    self.sprite_move_action = None

def on_key_press(self, symbol, modifiers):
    if symbol ==key.RIGHT:
        move = MoveBy((1, 0), 0.1)
        repeat = Repeat(move)
        self.sprite_move_action = repeat
        self.sprite.do(repeat)

def on_key_release(self, symbol, modifiers):
    if symbol == key.RIGHT and self.sprite_move_action is not None:
        self.sprite.remove_action(self.sprite_move_action)
        self.sprite_move_action = None

rawDescription: How to stop an action in cocos2d?

description: Stop an action in cocos2d


code:
email_lines = []
for row in result:
    line = do_something_with(row)
    email_lines.append(line)
email_body = '\n'.join*(email_lines)

rawDescription: is there a more efficient way to write results from a query in python?

description: Is there a more efficient way to write results from a query in python


code:
from collections import defaultdict

d = defaultdict(list)

with open('john_file.txt') as f:
    for line in f:
        fields = line.split('\t')
        d[fields[1]].append(line)

rawDescription: In python, how to parse a file into lists based on a specific value?


code:
def f(x):
    if x == 0:
        print("x is zero")
        print("where am i?")

rawDescription: why python is strict about indentation

description: Why python is strict about indentation


code: {{ value|stringformat:"i" }}

rawDescription: Django template convert to string

description: Django template convert to string


code:
import curses
import time

scr = curses.initscr()
while True:
    try:
        scr.addstr(0, 0, str(time.time()))
        scr.refresh()
    except KeyboardInterrupt: break
curses.endwin()

rawDescription: How do I show a statement repeatedly on the command line using curses?

description: Show a statement repeatedly on the command line using curses


rawDescription: I want one backslash - not two

description: I want one backslash - not two


code: Check_OM()  # forgot the parentheses :)

rawDescription: Python function and output issue

description: Python function and output issue


code:
def execute(self, cmd):
    if '\n' in cmd:
        self.pty.println(
            '__cmd_func__(){\n%s\n' % cmd +
            '}; echo __"cmd_start"__; __cmd_func__; echo __"cmd_end"__; unset -f __cmd_func__'
        )
    else:
        self.pty.println('echo __"cmd_start"__; %s; echo __"cmd_end"__' % cmd)

    resp = ''
    while not '__cmd_start__\r\n' in resp:
        resp += self.pty.read()

    resp = resp[resp.find('__cmd_start__\r\n') + 15:] # 15 == len('__cmd_start__\r\n')

    while not '_cmd_end__' in resp:
        resp += self.pty.read()

    return resp[:resp.find('__cmd_end__')]

rawDescription: Python SSH via Pseudo TTY Clear

description: Python SSH via Pseudo TTY Clear


code:
class MyModelAdmin(admin.ModelAdmin):
    list_display = ('get_sub_title',)

    def get_sub_title(self, obj):
        if obj.sub_title:
            return obj.sub_title
        else:
            return 'Not Available'

    get_sub_title.short_description = 'Subtitle'

rawDescription: Custom value for list_display item on Django admin


code:
import time
time.time()
_

rawDescription: Can one grab instantiated objects that were not assigned to a variable?


code:
def sparse_col_vec_dot(csc_mat, csc_vec):
    # row numbers of vector non-zero entries
    v_rows = csc_vec.indices
    v_data = csc_vec.data
    # matrix description arrays
    m_dat = csc_mat.data
    m_ind = csc_mat.indices
    m_ptr = csc_mat.indptr
    # output arrays
    sizes = m_ptr.take(v_rows+1) - m_ptr.take(v_rows)
    sizes = np.concatenate(([0], np.cumsum(sizes)))
    data = np.empty((sizes[-1],), dtype=csc_mat.dtype)
    indices = np.empty((sizes[-1],), dtype=np.intp)
    indptr = np.zeros((2,), dtype=np.intp)

    for j in range(len(sizes)-1):
        slice_ = slice(*m_ptr[[v_rows[j] ,v_rows[j]+1]])
        np.multiply(m_dat[slice_], v_data[j], out=data[sizes[j]:sizes[j+1]])
        indices[sizes[j]:sizes[j+1]] = m_ind[slice_]
    indptr[-1] = len(data)
    ret = sps.csc_matrix((data, indices, indptr),
                         shape=csc_vec.shape)
    ret.sum_duplicates()

    return ret

rawDescription: Improving Performance of Multiplication of Scipy Sparse Matrices


code:
a = {}
b = ['some', 'list']
hash(b)
a[b] = 'some'

rawDescription: Is a Python dictionary an example of a hash table?


code:
pos=nx.spring_layout(G) # positions for all nodes

for i in range(0, len(sets)):

    nx.draw_networkx_nodes(G,pos, sets[i],
    node_color='r', node_size=500,  alpha=0.8)

    rest = []
    for j in nodes:
            if j not in sets[i]:
                rest.append(j)

    nx.draw_networkx_nodes(G,pos, rest,
        node_color='w', node_size=500,  alpha=0.8)

    nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5)

    plt.axis('off')
    plt.show(block=False)

rawDescription: Matplotlib doesn't show last figure

description: Matplotlib doesn't show last figure


code:
from django.db.models import Count

events_this_month = Event.objects.values('created_by', 'kind') \
                         .filter(created_at__year=2013, created_at__month=5) \
                         .annotate(cc=Count('kind'))

rawDescription: Use django count or values_list counter, which is better?


code:
for counter, item in enumerate(ids):
    user = users[counter % len(users)]
    myfunction(item, user)

rawDescription: Python - injecting data into for loop

description: Python - injecting data into for loop


code:
import win32api
import win32pdhutil
import win32con

def killProcName(procname):
    """Kill a running process by name.  Kills first process with the given name."""
    try:
        win32pdhutil.GetPerformanceAttributes("Process", "ID Process", procname)
    except:
        pass

    pids = win32pdhutil.FindPerformanceAttributesByName(procname)

    # If _my_ pid in there, remove it!
    try:
        pids.remove(win32api.GetCurrentProcessId())
    except ValueError:
        pass

    handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pids[0])
    win32api.TerminateProcess(handle, 0)
    win32api.CloseHandle(handle)

rawDescription: Python 2.6 on Windows: how to terminate subprocess.Popen with "shell=True" argument?


code:
Present = ['A_Pre',  'B_Pre',  'C_Pre' ]
Absent = ['A_Abs',  'B_Abs',  'C_Abs' ]

for string in Present:
    DF[string] = pd.Series([1 if stat == 'Present' and sect == string[0] else 0
                            for stat, sect in zip(DF['Status'], DF['Section'])],
                            index = DF.index)
for string in Absent:
    DF[string] = pd.Series([1 if stat == 'Absent' and sect == string[0] else 0
                            for stat, sect in zip(DF['Status'], DF['Section'])],
                            index = DF.index)

DF.groupby(['Date', 'type']).agg(sum)

rawDescription: Groupby and aggregate operation on Pandas Dataframe


code:
def initialize(self):
    """Hook for subclass initialization.

    A dictionary passed as the third argument of a url spec will be
    supplied as keyword arguments to initialize().

    Example::

        class ProfileHandler(RequestHandler):
            def initialize(self, database):
                self.database = database

            def get(self, username):
                ...

        app = Application([
            (r'/user/(.*)', ProfileHandler, dict(database=database)),
            ])
    """
    pass

rawDescription: Use cases of RequestHandler.initialize() in Tornado


code:
with open(propertyfile_name) as f:
    content= f.read()
    for (server,h) in re.findall(RE,content):
        dico[server]['host']=h

    for (server,n) in re.findall(RE1,content):
        dico[server]['name']=n

    for (server,s) in re.findall(RE2,content):
        dico[server]['sslport']=s

    for (server,p) in re.findall(RE3,content):
        dico[server]['port']=p

rawDescription: Assistance with re module script

description: Assistance with re module script


code:
class Thing(object): # New-style class
    def __init__(self, whatever):
        self._whatever = whatever

    @property
    def whatever(self):
        return self._whatever # Insert complicated calculation here

rawDescription: Best way to retrieve data attributes in Python?

description: Retrieve data attributes in Python


code: urlretrieve(your_url, your_zip_path)

rawDescription: How to download a zip file from a site (python)

description: Download a zip file from a site (python)


code:
import os.path
import time
tmp_fname = '/tmp/tst'
with open(tmp_fname, 'w') as f:
    pass
os.path.getctime('/tmp/tst')
time.ctime(os.path.getctime(tmp_fname))

rawDescription: How to store files with random name on disk and only read those fit in a specific time period in python efficiently

description: Store files with random name on disk and only read those fit in a specific time period in python efficiently


code:
class Stuff(Base):
    __tablename__ = 'stuff'
    id = Column(Integer, primary_key=True)
    name = Column(String)

Base.metadata.create_all(engine)
session = Session()

from sqlalchemy import event
@event.listens_for(session, 'after_flush')
def _handle_event(session, context):
    print('>> --- after_flush started ---')
    rows = session.execute("SELECT 1 AS XXX").fetchall()
    print(rows)
    print('>> --- after_flush finished ---')

# create test data
s1 = Stuff(name='uno')
session.add(s1)
print('--- before calling commit ---')
session.commit()
print('--- after  calling commit ---')

rawDescription: How to make SQLAlchemy issue additional SQL after flushing the current session?

description: Make SQLAlchemy issue additional SQL after flushing the current session