code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.l1 = tk.Label(self, text="Hover over me")
        self.l2 = tk.Label(self, text="", width=40)
        self.l1.pack(side="top")
        self.l2.pack(side="top", fill="x")

        self.l1.bind("<Enter>", self.on_enter)
        self.l1.bind("<Leave>", self.on_leave)

    def on_enter(self, event):
        self.l2.configure(text="Hello world")

    def on_leave(self, enter):
        self.l2.configure(text="")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand="true")
    root.mainloop()

rawDescription: Display message when going over something with mouse cursor in Python


code:
def cutoff(category, cut, direction):

    if direction == 0:
        comply = list(zip(df[df[category] < cut].Major, df[df[category] < cut][category]))

    if direction == 1:
        comply = list(zip(df[df[category] > cut].Major, df[df[category] > cut][category]))

    return comply

rawDescription: How do I call a heading as an argument when defining a function in Python?

description: Call a heading as an argument when defining a function in Python


code:
print(re.search('GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)', ll))
print(re.search('GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)', ll).groups())
print(re.search('GOOGLE_MAPS_LATITUDE:\s*(\d+\.\d+)', ll).group(1))

rawDescription: reqular expression is giving None always

description: Reqular expression is giving None always


code:
from sqlalchemy import func, desc
session.query(
    func.count(tablename.id).label('qty')
    ).group_by(tablename.category
    ).order_by(desc('qty'))

rawDescription: Finding most frequent values in column of array in SQL Alchemy


code:
for pageid, pagedetails in res["query"]["pages"].iteritems():
    for revision in pagedetails["revisions"]:
        if revision["user"] == "TechBot":
            do.something()

rawDescription: Extract specific users comments from a list using Wikipedia API and Python 2.7


code: mydata = json.dumps({'json': list}, indent=0)

rawDescription: Trying to POST json data from Python to PHP


code:
import matplotlib.pyplot as plt
from numpy.random import random, randint

X = random(10)
Y = random(10)
val_arr = randint(low=0, high=3, size=10)
plt.scatter(X, Y, c=val_arr,
            s=40)
plt.colorbar()
plt.show()

rawDescription: How to assign color to scatter point

description: Assign color to scatter point


code:
# First parse you input file and create the menu list
with open("food.txt", "r") as foodfile:
    menu_items = ' '.join(foodfile.readlines()).strip().split(',')
menu_items = [item.strip() for item in menu_items]

# menu_items is now the list ['lamb curry', 'indian', 'chicken curry' ... etc

# I made the next part into a loop, so you can test several search terms.
# instead of searching on user input, you can split the menu into several lists
# but in most real world cases that is not really useful. With this approach
# users can search for "pizza" or "chicken" in addition to "mexican", "italian" etc.

while True:
    cho = input("What cusine would you like to view the menu for? ").lower().strip()
    if not cho:
        break  # break the loop if user submits an empty search string
    search_results = [food for food in menu_items if cho in food.lower()]
    print('\nFound %d items on the meny matching "%s"' % (len(search_results), cho))
    print(', '.join(search_results))

print('\ngoodbye')

rawDescription: How to find specific word in a text file?

description: Find specific word in a text file


code:
import importlib
import inspect

class LoadSomething:
    def load(self, modulename):
        module = importlib.import_module(modulename)
        modname = modulename.rpartition('.')[-1]  # support packages too
        for clsname, cls in inspect.getmembers(module, inspect.isclass):
            if clsname == modname.title():
                return cls()

rawDescription: Python: When using compile() - how do I create find the classname & create it?


code:
def create_bombs(self):
    bombs_flagged = 0
    existing_bomb_coords = set()  # All bomb coordinates so far
    # Creates the bombs
    while len(existing_bomb_coords) < self.bomb_num:  # Looping as much as needed
        bomb_row = randint(0, self.board_size-1)
        bomb_col = randint(1, self.board_size)
        bomb_coords = (bomb_row, bomb_col)
        if bomb_coords not in existing_bomb_coords:  # Very fast test
            self.bomb_list.append(Bomb(bomb_row, bomb_col, self, bombs_flagged))
            existing_bomb_coords.add(bomb_coords)  # New bomb registration

rawDescription: python - generating a non repeating random pairs of numbers

description: Python - generating a non repeating random pairs of numbers


code:
import numpy
from PIL import Image, ImageDraw

# polygon = [(x1,y1),(x2,y2),...] or [x1,y1,x2,y2,...]
# width = ?
# height = ?

img = Image.new('L', (width, height), 0)
ImageDraw.Draw(img).polygon(polygon, outline=1, fill=1)
mask = numpy.array(img)

rawDescription: SciPy Create 2D Polygon Mask

description: SciPy Create 2D Polygon Mask


code:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
y = [100, 99, 93, 88, 85, 43]
xt = [0, 5, 4, 3, 2, 1]
ax.plot(y)
ax.set_xticklabels(xt)
fig.savefig("out.png")

rawDescription: How to produce Matplotlib plot with x-axis out of order?

description: Produce Matplotlib plot with x-axis out of order


code:
from PyQt4 import QtGui
import sys

def main():

    app     = QtGui.QApplication(sys.argv)
    tabW    = QtGui.QTabWidget()
    tabW.setStyleSheet("QTabBar::tab:disabled {"+\
                        "width: 300px;"+\
                        "color: transparent;"+\
                        "background: transparent;}")
    pushButton1 = QtGui.QPushButton("QPushButton 1")
    pushButton2 = QtGui.QPushButton("QPushButton 2")

    tab1    = QtGui.QWidget()
    tab2    = QtGui.QWidget()
    emptySpace = QtGui.QWidget()
    tab3    = QtGui.QWidget()

    vBoxlayout    = QtGui.QVBoxLayout()
    vBoxlayout.addWidget(pushButton1)
    vBoxlayout.addWidget(pushButton2)

    #Resize width and height
    tabW.resize(500, 500)

    #Set Layout for Third Tab Page
    tab3.setLayout(vBoxlayout)

    tabW.addTab(tab1,"Tab 1")
    tabW.addTab(tab2,"Tab 2")
    tabW.addTab(emptySpace,"ES")
    tabW.setTabEnabled(2,False)
    tabW.addTab(tab3,"Tab 3")

    tabW.setWindowTitle('PyQt QTabWidget Add Tabs and Widgets Inside Tab')
    tabW.show()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: QTabWidget. How to move one tab to right position?


code:
for line in source:
    line = line.rstrip('\n')
    line = line.decode('unicode_escape').replace(u'\n', u'\\n').encode('utf8')
    target.write(line + '\n')

rawDescription: Why file read/write adds additional lines to the file?


code:
def parse(self, response):
        for href in response.xpath('//span[@class ="itemlistinginfo"]/a/@href'):
            full_url = urljoin(href.extract())
            item = DmozItem()
            item['link'] = full_url
            yield item

rawDescription: How to scrape url using Scrapy in Python

description: Scrape url using Scrapy in Python


code:
def perform_create(self, serializer):
    serializer.save(user=self.request.user)

rawDescription: Django Rest Framework add field to model before saving in viewset using ModelSerializer


code:
class Subject(models.Model):
    parent = models.ForeignKey("self")
    name = models.CharField(max_length=100)
    hebrew_name = models.CharField(max_length=100)

class Summary(models.Model):
    ...
    subject = models.ForeignKey("Subject")
    ...

class SubjectForm(forms.Form):
    subject = forms.ModelChoiceField(queryset=Subject.objects.none())
    ...

    def __init__(self, *args, **kwargs): # see http://stackoverflow.com/a/4880869/1477364
        sub = kwargs.pop('parent_subject')
        super(SubjectForm, self).__init__(*args, **kwargs)
        parent_subject = Subject.objects.get(name=sub)
        sub_subjects = Subject.objects.filter(parent=parent_subject)
        self.fields['subject'].queryset = forms.ModelChoiceField(queryset=sub_subjects)

rawDescription: Changing the choices in Django Model according to a field value


code:
m = re.findall(r'"info":"([^"]+)', str)
m

rawDescription: how to regex a value of a specific key in python

description: Regex a value of a specific key in python


rawDescription: Convert binary string to hex string and keep its leading zeros


code:
import struct
from collections import namedtuple
record = 'raymond   \x32\x12\x08\x01\x08'
Student = namedtuple('Student', 'name serialnum school gradelevel')
Student._asdict(Student._make(struct.unpack('<10sHHb', record)))

rawDescription: python struct unpack into a dict

description: Python struct unpack into a dict


code:
def getLocalDomainSuffix():
    domainSuffixSet = set()
    netKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters')
    for keyName in ("DhcpDomain", "SearchList"):
        value, type = _winreg.QueryValueEx(netKey, keyName)
        if value:
            for item in value.split(','):
                domainSuffixSet.add(item)
    return domainSuffixSet

rawDescription: Get DNS search suffix in Python

description: Get DNS search suffix in Python


code:
import glob
import imp
import os

def load_modules(module_names=None):
    if module_names is None:
        cur_dir = os.path.realpath(os.path.dirname(__file__))
        module_wc = '{}/*.py'.format(cur_dir)
        module_names = [mn for mn in glob.glob(module_wc) if not mn.startswith('_')]
    modules = map(imp.load_source, module_names)
    return modules

rawDescription: PEP8 compliant way to toggle logging for a whole package


code:
class Mx:
  def __matmul__(self, other):
    return "matmul {0} {1}".format(self, other)

print(Mx() @ 0)

rawDescription: Python 3.5 shows @ as matrix multiplication. How to use it?


code:
def test_only_with_mapfields(self):

    class BlogPost(Document):
        content = StringField()
        author = MapField(field=StringField())

    BlogPost.drop_collection()

    post = BlogPost(content='Had a good coffee today...',
                    author={'name': "Ross", "age": "20"}).save()

    obj = BlogPost.objects.only('author__name',).get()

    self.assertEquals(obj.author['name'], "Ross")
    self.assertEquals(obj.author.get("age", None), None)

rawDescription: Mongoengine, retriving only some of a MapField


code:
result = ' ' * 8
width = house.get_width() - 4 # subtract 4 to allow for 'CAT '
for i in range(house.get_cat_count()): # or xrange
    result += 'CAT %-*c' % (width, ord('A') + i)

rawDescription: Is there a more agile way to re-factor the following string formating code


code: filename = os.path.join(sys.prefix, "share", "xxx", "xxx.png")

rawDescription: Install static files for Python package

description: Install static files for Python package


code:
import pymc as pm
import numpy as np
M0=1e15

@pm.stochastic(dtype=np.float, observed=False, trace=True)
def ma(name='ma',value=0.1, rate = 1):
    """mass is a stochastic parameter with exponential distribution.p(M)~exp(-M/10^15)"""
    return pm.exponential_like(value, rate)
@pm.potential
def ma_bound(ma=ma):
    if ((ma >= 0.01) and (ma < 10)):
       return 0.0
    else:
       return -np.inf

M=pm.MCMC([ma,ma_bound])
M.sample(15000,5000,50)

rawDescription: Defining the exponential prior with jumping order of magnitude in parameter space


code:
import numpy as np
a = np.arange(10).reshape((5,2))
a
B,C = a
B,C = a.T
B
C

rawDescription: python data analysis, difficulty understanding cookbook code

description: Python data analysis, difficulty understanding cookbook code


code:
import time
import turtle

WIDTH = 800
HEIGHT = 600

seconds = 0

def text(text, posx, posy, size):
    turtle.pencolor('black')
    turtle.goto(posx, posy)
    turtle.write(text, font=("Arial", size, "normal"))

def press_space():
    global seconds
    seconds = time.time()
    turtle.onkeypress(None, ' ')

def release_space():
    if time.time() - seconds >= 3.0:
        turtle.onkeyrelease(None, ' ')
        text("thank you.", -200, 200, 15)

# ScreenRender
turtle.screensize(WIDTH, HEIGHT)
turtle.hideturtle()
turtle.penup()

# Text
text('Hold Space for 3 seconds...', -400, 200, 15)

# Event Handlers
turtle.listen()
turtle.onkeypress(press_space, ' ')
turtle.onkeyrelease(release_space, ' ')

# End
turtle.done()

rawDescription: Hold key - Python Turtle

description: Hold key - Python Turtle


code:
handlers = [
            (r'/favicon.ico', tornado.web.StaticFileHandler, {'path': favicon_path}),
            (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': static_path}),
            (r'/', WebHandler)
]

rawDescription: Using Tornado, how do I serve static files and serve a favicon.ico from a different directory than the static path?


code:
def break_long_words(s, width, fix):
  return " ".join(x if len(x) < width else fix(x) for x in s.split())

def handle_long_word(s):  # choose a name that describes what action you want
  # do something
  return s

s = "a" * 20
s = break_long_words(s, 60, handle_long_word)

rawDescription: Shortest way to break-up long string (add whitespace) after 60 chars?


code:
# Renamed seq0 so it doesn't interfere with below variable
for sequence0 in df.CD:
    alns = pairwise2.align.globalms(seq, sequence0,  match, mismatch, gap_open, gap_extend)
    # This is how you would get the first group of items from each tuple
    first_group_of_items = alns[0]

    # Now to get the seq variables you asked for
    # Since this variable is seq0, the above seq0 was renamed
    seq0 = first_group_of_items[0]
    seq1 = first_group_of_items[1]

rawDescription: unclear python data structure and parse python

description: Unclear python data structure and parse python


code:
devnull = open('/dev/null', 'w')
oldstdout_fno = os.dup(sys.stdout.fileno())
os.dup2(devnull.fileno(), 1)
makesomenoise()
os.dup2(oldstdout_fno, 1)

rawDescription: Suppressing output of module calling outside library


rawDescription: Create two list with 10 instances, then a third that contains x and y 10 times


code:
from ast import literal_eval
mystr = '[[1, 2, 3], [4, 5, 6]]'
x = literal_eval(mystr)
x
type(x)

rawDescription: string to numeric array

description: String to numeric array


code:
import wx

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

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

        self.slider = wx.Slider(self, value=1, minValue=0, maxValue=100, size=(250, -1),
                                style=wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS)
        self.slider.SetTickFreq(5, 1)
        self.slider.Bind(wx.EVT_SCROLL, self.onScroll)
        self.toggle = wx.ToggleButton(self, label="Start")
        self.toggle.Bind(wx.EVT_TOGGLEBUTTON, self.onToggle)

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

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.slider, 0, wx.ALL, 5)
        sizer.Add(self.toggle, 0, wx.ALL, 5)
        self.SetSizer(sizer)

    #----------------------------------------------------------------------
    def onScroll(self, event):
        """
        Fires when you manually scroll the slider
        """
        value = self.slider.GetValue()
        self.slider_value = value

    #----------------------------------------------------------------------
    def onToggle(self, event):
        """
        Start / Stop the slider incrementing
        """
        value = self.toggle.GetValue()
        if value:
            self.toggle.SetLabel("Pause")
            self.timer.Start(1000)
        else:
            self.timer.Stop()
            self.toggle.SetLabel("Start")

    #----------------------------------------------------------------------
    def onUpdate(self, event):
        """
        Increment the slider
        """
        self.slider_value += 1
        self.slider.SetValue(self.slider_value)

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

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

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

rawDescription: How can I stop a loop with a Toggle Button

description: Stop a loop with a Toggle Button


rawDescription: Numpy: find elements within range

description: Numpy: find elements within range


code:
# Import modules
import subprocess, sys, os
script_path = os.path.dirname(__file__)
myutils_path = os.path.join(script_path, '../myutils')
sys.path.append(myutils_path)
import myutils

rawDescription: sys.path.append modules relative to path of script being run

description: Sys.path.append modules relative to path of script being run


code:
def deleteWidget(self, index):
    delete_me = self.splitter.widget(index)
    delete_me.hide()
    delete_me.deleteLater()

rawDescription: Remove a specific QWidget from a QSplitter


code:
from scapy.all import *

ip=IP(dst="216.239.32.10")

request = DNS(rd=1, qd=DNSQR(qname = "google.be", qtype="A")) #size = 27(dec) = 1b (hex)
twoBytesRequestSize = "\x00\x1b" #BIG ENDIAN
completeRequest = str(request) + twoBytesRequestSize

SYN=ip/TCP(sport=RandNum(1024,65535), dport=53, flags="S", seq=42)
SYNACK=sr1(SYN)

ACK=ip/TCP(sport=SYNACK.dport, dport=53, flags="A", seq=SYNACK.ack, ack=SYNACK.seq + 1)
send(ACK)

DNSRequest = ip/TCP(sport=SYNACK.dport, dport=53, flags="PA", seq=SYNACK.ack, ack=SYNACK.seq + 1) / completeRequest
DNSReply = sr1(DNSRequest, timeout = 1)

rawDescription: Scapy DNS request malformed only with TCP


rawDescription: Python, making shallow copy of a list doesn't work with object attributes?


code: list(x[x > 0].stack().index)

rawDescription: Getting (index, column) pairs for True elements of a boolean DataFrame in Pandas


code: out = a[:, :-shift] + mult_factor * a[:, shift:]

rawDescription: Python column addition of numpy arrays with shift


code:
class Info(models.Model):
    ...
    def save(self, *args, **kwargs):
        # validate all multiChoice belong in lookup
        lookup_id_list = Lookup.objects.filter(id__in=self.multiChoice)\
            .values_list('id', flat=True)
        assert set(lookup_id_list) == set(self.multiChoice)
        super(Info, self).save(*args, **kwargs)

rawDescription: Django Arrayfield with referential constraint for postgres


code:
from passlib.hash import bcrypt

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    username = Column(String(15), nullable=False, unique=True)
    email = Column(String(300))
    password = Column(String(300), nullable=False)

    def __init__(self, username, password, email):
        self.username = username
        self.password = bcrypt.encrypt(password)
        self.email = email

    def validate_password(self, password):
        return bcrypt.verify(password, self.password)

    def __repr__(self):
        return "<User(username ='%s', password='%s', email='%s')>" % (self.username, self.password, self.email)

rawDescription: Storing and validating encrypted password for login in Pyramid


code:
import pylab
fig = pylab.figure()
pylab.axis('off')
pylab.plot([1,3,1,2,3])
pylab.plot([3,1,1,2,1])
fig.get_size_inches()    # check default size (width, height)
fig.set_size_inches(4,3)
fig.get_dpi()            # check default dpi (in inches)
fig.set_dpi(40)
fig.savefig('out.svg', transparent=True, bbox_inches='tight', pad_inches=0)

rawDescription: Matplotlib savefig image trim

description: Matplotlib savefig image trim


rawDescription: sending a period to end a mail DATA telnet session in python

description: Sending a period to end a mail DATA telnet session in python


code:
from pylab import *
from matplotlib import colors
# A = [[1,2,3,4,5]]
A = [[0],[1]]
Amap = colors.ListedColormap(['blue','green'])

fig = figure(1)
ax = fig.add_subplot(111, autoscale_on=False)
imshow(A, cmap=Amap, interpolation='nearest')
ax.annotate('AA BB', fontsize=20, xy=(.25, .75),
            xycoords='data', xytext=(150, -6),
            textcoords='offset points',
            arrowprops=dict(arrowstyle="->",
                            linewidth = 5.,
                            color = 'red')
            )
ax.annotate('CC DD', fontsize=20, xy=(.25, .25),
            xycoords='data', xytext=(150, -6),
            textcoords='offset points',
            arrowprops=dict(width = 5.,
                            headwidth = 15.,
                            frac = 0.2,
                            shrink = 0.05,
                            linewidth = 2,
                            color = 'red')
            )
axis('off')
savefig('graph-py.pdf')
show()
close()

rawDescription: How do you annotate a matplotlib imshow map with an arrow *and* text?

description: Annotate a matplotlib imshow map with an arrow *and* text


code:
s = "[A1A B2B, C3C, D4D, E5E]"
l = [val.strip('[,]') for val in s.split()]
l[2:4]

rawDescription: Extract certain words from a python string


code:
ser = serial.Serial('/dev/ttyUSB0',9600)
ser.open()
while 1:
  line = ser.readline()
  if line != "":
    db.data.insert({"Light" : line, "Ts" : time()})
ser.close()

rawDescription: Dealing with microcontroller data over time


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

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")

# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)

# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')

plt.show()

rawDescription: Adding an arbitrary line to a matplotlib plot in ipython notebook


code:
class A(object):
    def __init__(self):
        print('Constructing A')

    def __del__(self):
        print('Destructing A')

class B(object):
    a = A()

rawDescription: Is it really OK to do object closeing/disposing in __del__?


code:
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

fig, ax = plt.subplots()

x = [0, 1]
y = [0, 0]

ax.plot(x, y)

dy = 5/72

i = 1  # 0 for dx

tmp = ax.transData.transform([(0,0), (1,1)])
tmp = tmp[1,i] - tmp[0,i]  # 1 unit in display coords
tmp = 1/tmp  # 1 pixel in display coords
tmp = tmp*dy*ax.get_figure().get_dpi()  # shift pixels in display coords

ax.plot(x, y)

ax.annotate("", [0,tmp], [1,tmp],
            size = 10,
            arrowprops = dict(arrowstyle = '<|-|>'))

plt.show()

rawDescription: How do I offset lines in matplotlib by X points

description: Offset lines in matplotlib by X points


code:
count = 0
def outerLoop(hGraph, N):
    explored    = [False for iii in range(N+1)]
    finish      = {}

    for vertex in range(N, -1, -1):
        if explored[vertex] == False:
            dfs(vertex, hGraph, explored, finish)

    return finish

def dfs(vertex, graph, explored, finish):
    global count
    stack       = [[]]                              #stack contains the possible edges to explore
    traceBack   = []
    traceBack.append(vertex)

    while len(stack) > 0:
        explored[vertex] = True

        try:
            for n in graph[vertex]:
                if explored[n] == False:
                    if n not in stack[-1]:          #to prevent double adding (when we backtrack to previous vertex)
                        stack[-1].append(n)
                else:
                    if n in stack[-1]:              #make sure num exists in array before removing
                        stack[-1].remove(n)
        except IndexError: pass

        if len(stack[-1]) == 0:                     #if current stack is empty then there are no outgoing edges:
            finish[count] = traceBack.pop()         #thus, we can add finishing times
            count += 1

            if len(traceBack) > 0:                  #to prevent popping empty array
                vertex = traceBack[-1]
            stack.pop()
        else:
            vertex = stack[-1][-1]                  #pick last element in top of stack to be new vertex

            stack.append([])
            traceBack.append(vertex)

rawDescription: How do I add finishing times for iterative depth-first search?

description: Add finishing times for iterative depth-first search


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pylab as pl
from PIL import Image
import numpy as np
import pylab

img = Image.open('40.jpg').convert('L')
z   = np.asarray(img)
mydata = z[::1,::1]
fig = pl.figure(facecolor='w')
ax1 = fig.add_subplot(1,2,1)
im = ax1.imshow(mydata,interpolation='nearest',cmap=pl.cm.jet)
ax1.set_title('2D')

ax2 = fig.add_subplot(1,2,2,projection='3d')
x,y = np.mgrid[:mydata.shape[0],:mydata.shape[1]]
ax2.plot_surface(x,y,mydata,cmap=pl.cm.jet,rstride=1,cstride=1,linewidth=0.,antialiased=False)
ax2.set_title('3D')
ax2.set_zlim3d(0,100)
pl.show()

rawDescription: Python: 3D contour from a 2D image - pylab and contourf


code:
def contact_view_full(request, contact_id):
    c = get_object_or_404(Contact, id=contact_id)
    a = c.addresses.all()
    return render_to_response('contact_full.html', {'contact_item': c, 'addresses' : a }, context_instance=RequestContext(request))

rawDescription: Django - provide additional information in template


code:
splits = x['name'].split()
df['first'] = splits.str[0]
df['last'] = splits.str[1]

rawDescription: Quickly applying string operations in a pandas DataFrame


code:
import numpy as np
from matplotlib import pyplot as plt
im = np.arange(256).reshape(16,16)

fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(211)

ax.imshow(im)
plt.show()

transAxes = ax.transAxes
invFig = fig.transFigure.inverted()

llx,urx = plt.xlim()
lly,ury = plt.ylim()

llx0, lly0 = transAxes.transform((0,0))
llx1, lly1 = transAxes.transform((1,1))

plt.draw()
spleft = ax.spines['left'].get_verts()
spright = ax.spines['right'].get_verts()
llx0 = spleft[0,0]
llx1 = spright[0,0]

axp = invFig.transform(((lly0,llx0),(lly1,llx1)))
ax2 = fig.add_axes([axp[0,1],axp[0,0]-0.5,axp[1,1]-axp[0,1],axp[1,0]-axp[0,0]])
ax2.plot(np.arange(10))
plt.draw()

rawDescription: Python Matplotlib line plot aligned with contour/imshow


code:
from collections import Counter
totals = Counter()
for dct in dictionary.values():
    totals.update(dct)

rawDescription: How can I use chain for X number of dictionaries?

description: Use chain for X number of dictionaries


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

x,y = np.mgrid[-2:2:0.1, -2:2:0.1]
data = np.sin(x)*(y+1.05**(x*np.floor(y))) + 1/(abs(x-y)+0.01)*0.03

fig = plt.figure()
ax = fig.add_subplot(111)
ticks_at = [-abs(data).max(), 0, abs(data).max()]
cax = ax.imshow(data, interpolation='nearest',
                origin='lower', extent=[0.0, 0.1, 0.0, 0.1],
                vmin=ticks_at[0], vmax=ticks_at[-1])
cbar = fig.colorbar(cax,ticks=ticks_at,format='%1.2g')
fig.savefig('out.png')

rawDescription: Modifying axes on matplotlib colorbar plot of 2D array


code: y = sorted(set(x), key=lambda s:s.lower())

rawDescription: Flatten, remove duplicates, and sort a list of lists in python


code:
arr1 = ['name','age','sex']
val1 = ['Jone','20','male']
dict(zip(arr1, val1))

rawDescription: python key value pairing

description: Python key value pairing


code:
import Tkinter as tk

class App(object):
    def __init__(self, master):
        dismiss = tk.Button(master, text = 'dismiss', command = self.on_dismiss)
        ok = tk.Button(master, text = 'ok', command = self.on_ok)
        ok.bind('<Return>', self.on_ok)
        dismiss.bind('<Escape>', self.on_dismiss)
        ok.focus()
        dismiss.pack(fill = tk.BOTH)
        ok.pack(fill = tk.BOTH)
    def on_ok(self, event = None):
        print("Aww, it's okay!")
    def on_dismiss(self, event = None):
        print("Dismissed!")
root = tk.Tk()
app = App(root)
root.mainloop()

rawDescription: Python - Tkinter pre-selected button

description: Python - Tkinter pre-selected button


code:
l = []
gc.disable()
for x in xrange(10**6):
  l.append(x)
gc.enable()

rawDescription: Python garbage collection can be that slow?


code:
chk.blockSignals()
# then you change the checkbox as you want
chk.unblockSignals()

rawDescription: How can I disable a QCheckBox WITHOUT triggering an event?

description: Disable a QCheckBox WITHOUT triggering an event


rawDescription: Converting nested lists of data into multidimensional Numpy arrays


code:
mylist=[['a', 9, 3], ['we', 2], ['will', 2, 10], ['x', 4], ['z', 4]]
for sublist in mylist:
    sublist[1:] = sorted(sublist[1:], reverse=True)

rawDescription: How to sort list with nested lists alphabetically by the name in the nested lists, then sort the nested list by highest value in Python

description: Sort list with nested lists alphabetically by the name in the nested lists, then sort the nested list by highest value in Python


code: nosetests

rawDescription: Which Python testing framework to use?

description: Which Python testing framework to use


code:
import Foo
def new_g(x):
    print(x + x + x)
Foo.g = new_g
if __name__ == '__main__':
    foo =  Foo.Foo()
    foo.f()

rawDescription: How to redefine the function that a function I import in python uses?

description: Redefine the function that a function I import in python uses


rawDescription: webbrowser.open() in python

description: Webbrowser.open() in python


code:
cmd = """line %d
      line %d
      line %d""" % (
      1,
      2,
      3)

rawDescription: Multi line string with arguments. How to declare?


code:
aElements = browser.find_elements_by_tag_name("a")
for name in aElements:
    if(name.get_attribute("href") is not None and "javascript:void" in name.get_attribute("href")):
        print("IM IN HUR")
        name.click()
        break

rawDescription: Selenium and Python can't click href="javascript:void(0);" with .click()


code:
s = open('data.txt', "r").read()

x = re.findall(r'x:(.*), ', s)
y = re.findall(r'y:(.*),', s)
z = re.findall(r'z:(.*) ', s)

with open('axeX.txt', 'w') as f: f.write('\n'.join(x))
with open('axeY.txt', 'w') as f: f.write('\n'.join(y))
with open('axeZ.txt', 'w') as f: f.write('\n'.join(z))

rawDescription: extract data from file with python

description: Extract data from file with python


code:
from collections import OrderedDict

lines = OrderedDict()
for line in file:
    lines[line[0:12]] = line

rawDescription: Find lines beginning with same string and keep last occurance


code:
content_types = ['series', 'seasons', 'episodes', 'movies', 'bundles']
for url in previous_urls:
    for content_type in content_types:
        if getattr(self, content_type).get(url):
            del getattr(self, content_type)[url]
            break

rawDescription: How to reduce repetitive code in if/elif statement

description: Reduce repetitive code in if/elif statement


code:
#!/usr/bin/env python
import os, nose, unittest

class Test(unittest.TestCase):
    def test_env(self):
        self.assertEquals(os.environ.get('HELLO'), 'WORLD')

if __name__ == '__main__':
    os.environ["HELLO"] = "WORLD"
    nose.run()

rawDescription: nosetests framework: how to pass environment variables to my tests?

description: Nosetests framework: how to pass environment variables to my tests


rawDescription: Generator returning Mocks that fail assert_called_with


code:
import tkinter as tk
import tkinter.ttk as ttk
from ctypes import windll

GWL_EXSTYLE=-20
WS_EX_APPWINDOW=0x00040000
WS_EX_TOOLWINDOW=0x00000080

def set_appwindow(root):
    hwnd = windll.user32.GetParent(root.winfo_id())
    style = windll.user32.GetWindowLongPtrW(hwnd, GWL_EXSTYLE)
    style = style & ~WS_EX_TOOLWINDOW
    style = style | WS_EX_APPWINDOW
    res = windll.user32.SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style)
    # re-assert the new window style
    root.wm_withdraw()
    root.after(10, lambda: root.wm_deiconify())

def main():
    root = tk.Tk()
    root.wm_title("AppWindow Test")
    button = ttk.Button(root, text='Exit', command=lambda: root.destroy())
    button.place(x=10,y=10)
    root.overrideredirect(True)
    root.after(10, lambda: set_appwindow(root))
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Tkinter, Windows: How to view window in windows task bar which has no title bar?


code: {{ object.column }}

rawDescription: django - how to get value of key-value queryset from values()

description: Django - how to get value of key-value queryset from values()


code:
fig, ax1 = plt.subplots()
df['Close'].plot(ax=ax1,color='g',linewidth=1.0)
sp['Close'].plot(secondary_y=True, ax=ax1,color='b',linewidth=1.0)
ax = df['Close'].plot();
ax.set_ylabel('WLL', fontsize=10);
sp['Close'].plot(ax=ax, secondary_y=True);

plt.xlabel('xlabel', fontsize=10)
plt.ylabel('S&P 500', fontsize=10, rotation=-90)

rawDescription: How to label y-axis when using a secondary y-axis?

description: Label y-axis when using a secondary y-axis


code:
print [u'Hello: \xc9']
print [u'Hello: \xc9'][0]

rawDescription: Python csv.DictReader embeds non-unicode characters


code: {{ user.player }}

rawDescription: (Django) Passing 'context' (basic info) to every page, even forms?


code: soup.findAll("table", {"width": "585"})

rawDescription: Extracting tables containing a string with BeautifulSoup


rawDescription: Extract Mandrill Merge Tags With Regex (star and pipe)


code: dataset.rename(columns={typo: 'Address' for typo in AddressCol}, inplace=True)

rawDescription: Python Pandas Replacing column names

description: Python Pandas Replacing column names


code:
import urllib2

urllib2.urlopen('http://example.com', 'a=1&b=2')

rawDescription: how to make post requests in python/django?

description: Make post requests in python/django


code:
for event in pygame.event.get(): # If user did something
    enter_pressed = False
    if event.type == pygame.QUIT: # If user clicked close
        done = True
    elif event.type == pygame.KEYDOWN: # If user pressed a key
        if event.key == pygame.K_RETURN: # If user pressed enter
            # Makes the start screen go away
            enter_pressed = True
            # Increments question_number
            question_number += 1

            # Where I Draw the question screen

    elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and enter_pressed:
                    print("Derp")

rawDescription: pygame mouse button down not working

description: Pygame mouse button down not working


code:
class PortConfig(Serializable):
    port = models.ForeignKey(Port, editable=False)
    machine = models.ForeignKey("vmm.machine", editable=False)
    is_open = models.CharField(max_length=16, default="not_open", choices=is_open_choices)

class Rule(Serializable):
    ip_source = models.CharField(max_length=24)
    port_config = models.ForeignKey(PortConfig)

rawDescription: Django : presenting a form very different from the model and with multiple field values in a Django-ish way?


code:
O = viz.pick(1, viz.WORLD)

BackSetts = ["set_b1b", "set_b2a", "set_b1a",  "set_b2b"]
LeftSetts = ["set_l1a", "set_l1b", "set_l2a", "set_l1b"]
NormSetts = ["set_nr_a", "set_nr_b"]
Maps = ["MapA","MapB"]
anyset = []

if O.name in BackSetts:
    anyset = set(BackSetts)|set(Maps)

elif O.name in LeftSetts:
    anyset = set(LeftSetts)|set(Maps)

elif O.name in NormSetts:
    anyset = NormSetts

for i in anyset:
    WORLD[i].alpha(abs(WORLD[i].getAlpha()-1))

rawDescription: Is there a better way to write this?

description: Is there a better way to write this


rawDescription: How to run Python's subprocess and leave it in background

description: Run Python's subprocess and leave it in background


rawDescription: Regular Expression for Stripping Strings from Source Code


code:
import unittest

def execute_all_tests(tests_folder):
    suites = unittest.TestLoader().discover(tests_folder)
    text_runner = unittest.TextTestRunner().run(suites)

rawDescription: Unit testing: How can i import test classes dynamically and run?


rawDescription: pandas plot datetime groupby distribution

description: Pandas plot datetime groupby distribution


code:
import pandas as pd
import matplotlib.pyplot as plt

# replace this with your existing code to read the dataframe
df = pd.read_clipboard()

plt.scatter(df.X, df.Y, s=df.Magnitude)

# annotate the plot
# unfortunately you have to iterate over your points
# see http://stackoverflow.com/q/5147112/553404

for idx, row in df.iterrows():
    # see http://stackoverflow.com/q/5147112/553404
    # for better annotation options
    plt.annotate(row['Qname'], xy=(row['X'], row['Y']))

plt.show()

rawDescription: Mapping Column Data to Graph Properties

description: Mapping Column Data to Graph Properties


code:
import ctypes
from ctypes import wintypes

def get_appdata_directory():
    CSIDL_APPDATA = 0x001a

    dll = ctypes.windll.shell32
    app_data_directory = ctypes.create_unicode_buffer(wintypes.MAX_PATH)

    found = dll.SHGetFolderPathW(0, CSIDL_APPDATA, 0, 0, app_data_directory)

    # FYI: if `found` is False, then it failed to locate the appdata directory
    # and app_data_directory.value is empty. So you might want to add some
    # code here to verify that a valid path is going to be returned.

    # This would probably only happen on older versions of windows,
    # but, this is just a guess as I don't have any older OSs available
    # for testing. (see my note below)

    return app_data_directory.value

appdata = get_appdata_directory()
print(appdata)
# outputs something such as: 'C:\Users\bob\AppData'

rawDescription: run as administrator problem with py2exe

description: Run as administrator problem with py2exe


code:
import ast
ast.literal_eval("[{u'text': u'this', u'freq': 1}, {u'text': u'is', u'freq': 1}, {u'text': u'a', u'freq': 1}, {u'text': u'test', u'freq': 1}]")

rawDescription: loading string of json arrays in python

description: Loading string of json arrays in python


rawDescription: How to visualise the number of dimensions in an array for python numpy

description: Visualise the number of dimensions in an array for python numpy


code:
def twovarfunc(x, z):
    return x**2 - 2 - z

def solve_twovarfunc(z, low, high):
    # Find root between low and high for some value of z
    def onevarfunc(x):
        return twovarfunc(x, z)
    return opt.bisect(onevarfunc, low, high)

rawDescription: Find root of function of 2 variables, with one variable set to constant


code:
import matplotlib
matplotlib.use('PDF')

rawDescription: Disable/skip show()

description: Disable/skip show()


code:
def initUI(self):
    self.outputBox = Text(self.parent, bg='black', height= 10, fg='green', relief=SUNKEN, yscrollcommand='TRUE')
    self.outputBox.pack(fill='both', expand=True)
    path = "../img/Stalin.jpeg"
    self.img = ImageTk.PhotoImage(Image.open(path))
    panel = Label(self.parent, image = self.img)
    panel.pack(side = "bottom", fill = "both", expand = "yes")

rawDescription: tkinter can't add photo in class that not include mainloop

description: Tkinter can't add photo in class that not include mainloop


code: dict2 = {k: x[:i] + x[i+1:] for x in dict1.values() for i, k in enumerate(x)}

rawDescription: Create python dictionary from value of another dictionary?


code:
import logging

logger = logging.getLogger(__name__)

def logging_decorator(fn):
    def func(*a, **kw):
       logger.info('%s(%s, %s)', fn, a, kw)
       return fn(*a, **kw)
    return func

rawDescription: Create a function decorator that logs arguments


code:
say_base = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
    'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
    'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']

say_tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy',
    'eighty', 'ninety']

def hundreds_i(num):
    hundreds, rest = divmod(num, 100)
    if hundreds:
        yield say_base[hundreds]
        yield ' hundred'
    if 0 < rest < len(say_base):
        yield ' and '
        yield say_base[rest]
    elif rest != 0:
        tens, ones = divmod(rest, 10)
        yield ' and '
        yield say_tens[tens]
        if ones > 0:
            yield '-'
            yield say_base[ones]

assert "".join(hundreds_i(245)) == "two hundred and forty-five"
assert "".join(hundreds_i(999)) == 'nine hundred and ninety-nine'
assert "".join(hundreds_i(200)) == 'two hundred'

rawDescription: Convert numbers to English strings

description: Convert numbers to English strings


code:
from BeautifulSoup import BeautifulSoup as parser

def detect_feeds_in_HTML(input_stream):
    """ examines an open text stream with HTML for referenced feeds.

    This is achieved by detecting all ``link`` tags that reference a feed in HTML.

    :param input_stream: an arbitrary opened input stream that has a :func:`read` method.
    :type input_stream: an input stream (e.g. open file or URL)
    :return: a list of tuples ``(url, feed_type)``
    :rtype: ``list(tuple(str, str))``
    """
    # check if really an input stream
    if not hasattr(input_stream, "read"):
        raise TypeError("An opened input *stream* should be given, was %s instead!" % type(input_stream))
    result = []
    # get the textual data (the HTML) from the input stream
    html = parser(input_stream.read())
    # find all links that have an "alternate" attribute
    feed_urls = html.findAll("link", rel="alternate")
    # extract URL and type
    for feed_link in feed_urls:
        url = feed_link.get("href", None)
        # if a valid URL is there
        if url:
            result.append(url)
    return result

rawDescription: Automatically Extracting feed links (atom, rss,etc) from webpages


code:
starts = signals & (signals != signals.shift())
(close.where(starts).ffill() * signals).fillna(0)

rawDescription: fill a dataframe of 0 and 1 series with the first values of another dataframe pandas

description: Fill a dataframe of 0 and 1 series with the first values of another dataframe pandas


code:
import webbrowser
from itertools import product
with open('servers.txt') as infile:
    servers = list(map(str.strip, infile.readlines()))
with open('PRINTERS_toDelete.txt') as infile:
    queues = list(map(str.strip,infile.readlines()))
strTemp1 = 'cscript c:\\windows\\system32\\prnmngr.vbs -d -p %s -s %s\n'
with open('RUN_THIS.txt', 'w') as outfile:
    outfile.writelines(strTemp1 % (queue,server) for queue,server in product(queues,servers))
webbrowser.open('RUN_THIS.txt')

rawDescription: Having issues with spacing on output file - using itertools product for looping using variables from two different text files to output to a third


code:
import datetime
data_set = [{'option_type': 'Call', 'expiry': datetime.datetime(1993, 3, 4, 15, 20, 26), 'vega': 2, 'notional': 7840, 'delta': 1, 'strike': 520, 'theta': 5, 'gamma': 3}, {'option_type': 'Call', 'expiry': datetime.datetime(1995, 11, 14, 10, 25, 50), 'vega': 2, 'notional': 1930, 'delta': 1, 'strike': 1960, 'theta': 5, 'gamma': 3}, {'option_type': 'Put', 'expiry': datetime.datetime(1993, 3, 7, 17, 2, 30), 'vega': 2, 'notional': 5530, 'delta': 1, 'strike': 1520, 'theta': 5, 'gamma': 3}]

counts = {'vega': 0, 'theta': 0, 'delta': 0, 'gamma': 0}

for data in data_set:
    for key in counts.keys():
        counts[key] += data[key]

counts

rawDescription: How to add the values of dictionary with same keys in Python

description: Add the values of dictionary with same keys in Python


code:
import difflib
matcher = difflib.SequenceMatcher(None, 'foo', 'for')
sum(size for start, end, size in matcher.get_matching_blocks())
max(map(len, ('foo', 'for'))) - _
matcher = difflib.SequenceMatcher(None, 'foo', 'food')
sum(size for start, end, size in matcher.get_matching_blocks())
max(map(len, ('foo', 'food'))) - _

rawDescription: Python "regex" module: Fuzziness value

description: Python "regex" module: Fuzziness value


code: log = [line.split(',') for line in open('log.csv')]

rawDescription: Create 2d array from csv file in python 3


code: my_validator = QRegExpValidator(rx)

rawDescription: How to make IP validation for QtGui.QInputDialog.GetText()

description: Make IP validation for QtGui.QInputDialog.GetText()


code:
import time
import threading
import Tkinter as tk

class App():
    def __init__(self, root):
        self.button = tk.Button(root)
        self.button.pack()
        self._resetbutton()
    def _resetbutton(self):
        self.running = False
        self.button.config(text="Start", command=self.startthread)
    def startthread(self):
        self.running = True
        newthread = threading.Thread(target=self.printints)
        newthread.start()
        self.button.config(text="Stop", command=self._resetbutton)
    def printints(self):
        x = 0
        while self.running:
            print(x)
            x += 1
            time.sleep(1) # Simulate harder task

rawDescription: Multiprocessing in Python tkinter

description: Multiprocessing in Python tkinter


code:
import textwrap

labeltext = textwrap.fill(labeltext, width=30)

rawDescription: Label break line if string is too big

description: Label break line if string is too big


code:
def permutation(numberList,array,place):
    if (place==len(numberList)):
        print(array)
    else:
        x=0
        while (x < len(numberList)):
            array.append(numberList[x])
            permutation(numberList,array,place+1)
            array.pop()
            x+=1

rawDescription: Permutations of a list of input numbers in Python


code:
prescriptions = {}
prescriptions2 = {}

#Open ABCD table and create a dictionary mapping A,B,C to D
with open(table_file) as table:
    reader = csv.reader(table, delimiter = '\t')
    for row in reader:
        code = (row[0], row[1], row[2])
        prescriptions[code]=row[3]
        key = (row[0],row[1])
        if not key in prescription2:
            prescription2[key] = []
        value = (row[2],row[3])
        prescription2[key].append(value)

for x in objects:
    x_code = (x.A, x.B)
    if x_code in prescription2:
        for item in prescription2[x_code]:
            line = ",".join(x_code+item)+"\n"
            output.write(line)

rawDescription: Matching Indices from Two Sets of Data

description: Matching Indices from Two Sets of Data


code:
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

class Category(MPTTModel):
    name = models.CharField(max_length=255)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

    def __unicode__(self):
        ancestors = self.get_ancestors(ascending=False, include_self=True)
        return ' -> '.join(category.name
                           for category in ancestors)

rawDescription: Loop over parent ForeignKey

description: Loop over parent ForeignKey


code:
def get_context_data(self, **kwargs):
    context = super(StateListView, self).get_context_data(**kwargs)
    context.update({'state': self.kwargs['location_state']})
    return context

rawDescription: Django template: access query_set and non-query_set results in same template


code:
for row in qres:
    d = str(row.asdict()['birth'].toPython())
    print(d)

rawDescription: How do I print term literal from rdflib in a readble way?

description: Print term literal from rdflib in a readble way


code:
s = "-o-pp-gg-s-h"
ss = s.split("-")
series = ["-".join(ss[:x]) for x in range(2,len(ss)+1)]

rawDescription: Splitting strings in python, then joining them into so that each string is one substring longer than the next


code:
with open("example.csv") as f:
    allData = [line.strip().split(",") for line in f]

    firstColumn  = [data[0] for data in allData]
    secondColumn = [data[1] for data in allData]
    thirdColumn  = [data[2] for data in allData]

rawDescription: Python: How to append certain information from a CSV file onto an array


code:
fn = lambda ts: set(ts) if len( ts.unique( ) ) > 1 else ts.iloc[0]
df.groupby( ['col1','col3'], as_index=False ).aggregate( fn )

rawDescription: Pandas - Combine Rows with Similar Data

description: Pandas - Combine Rows with Similar Data


code:
with open('test.txt', 'r') as inf:
    lst = inf.readlines()  # much easier than iterating and accumulating

lst[1:] = sorted(lst[1:])  # this will leave the first line: "Test List" intact

with open('test.txt', 'w') as outf:
    outf.writelines(lst)  # re-write the file

rawDescription: Sorting Lists into Alphabetical Order

description: Sorting Lists into Alphabetical Order


code: [lx for li in fieldlist for lx in li[1] if li[1]]

rawDescription: List Comprehension in Nested Lists

description: List Comprehension in Nested Lists


code:
from glob import glob
path = "path_to/"
files = glob(path+"[1,5,8]*")

rawDescription: multiple matches using file's startswith

description: Multiple matches using file's startswith


code: data = open("filename.txt").readlines()

rawDescription: Read same lines in different context few lines after a match in python


code:
from mako.template import Template
Template(filename='template.mako', module_directory='.')

rawDescription: Some questions regarding Mako modules, Mako's TemplateLookup function, and Pyramid


code: samples = [1 if i in (1, 2, 3) else i for i in samples]

rawDescription: Using the logical "or" in conditional indexing in python arrays


code:
if condition:
    return redirect('/dashboard/')
else:
    return super(UserFormView, self).get(request)

rawDescription: Django: FormView: How to add initial logic?


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

x = np.char.array(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct', 'Nov','Dec'])
y = np.array([234, 64, 54,10, 0, 1, 0, 9, 2, 1, 7, 7])
colors = ['yellowgreen','red','gold','lightskyblue','white','lightcoral','blue','pink', 'darkgreen','yellow','grey','violet','magenta','cyan']
porcent = 100.*y/y.sum()

patches, texts = plt.pie(y, colors=colors, startangle=90, radius=1.2)
labels = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(x, porcent)]

sort_legend = True
if sort_legend:
    patches, labels, dummy =  zip(*sorted(zip(patches, labels, y),
                                          key=lambda x: x[2],
                                          reverse=True))

plt.legend(patches, labels, loc='left center', bbox_to_anchor=(-0.1, 1.),
           fontsize=8)

plt.savefig('piechart.png', bbox_inches='tight')

rawDescription: How to avoid overlapping of labels & autopct in a matplotlib pie chart?

description: Avoid overlapping of labels & autopct in a matplotlib pie chart


code:
from collections import defaultdict

spaces = defaultdict(list) # space -> [(answer1, index1), (answer2, index2), ...]
for answer in answers:
    for i, space in enumerate(answer.spaces):
        spaces[space].append((answer, i))
intersections = [occurrences for occurrences in spaces.values()
                 if len(occurrences) > 1]

rawDescription: Getting Intersection Between 2 Lists in Python 3


code:
PRINTER_DEFAULTS = {"DesiredAccess":win32print.PRINTER_ACCESS_ADMINISTER}
win32print.OpenPrinter(self.printers[i]['pPrinterName'], PRINTER_DEFAULTS)

rawDescription: Access denied when attempting to remove printer


code:
def _match_function(name):
    def f(matchobj):
        lMatch = matchobj.group(1)
        return "EXTEND WITH %s" % (name, lMatch, lMatch)
    return f

lReturn = re.sub(r'\[usecase:([ \w]+)]', _match_function(pCurrentProjectName), lReturn)

rawDescription: Passing values into regex match function


rawDescription: gevent.StreamServer and non-blocking raw_input()?

description: Gevent.StreamServer and non-blocking raw_input()


code:
import cv2
import time

cv2.namedWindow("Hawk Eye", 1)

capture = cv2.VideoCapture(0)
capture.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 800)
capture.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 600)

x_offset=y_offset=50
arrows = cv2.imread("hawk.png")

while True:
    ret, webcam = capture.read()
    if ret:
        webcam[y_offset:y_offset+arrows.shape[0], x_offset:x_offset+arrows.shape[1]]=arrows
        cv2.imshow("Hawk Eye", webcam)
        if cv2.waitKey(10) == 27:
            break
cv2.destroyAllWindows()

rawDescription: Superimposing image over webcam feed using OpenCV 2.4.7.0 in Python 2.7


code:
root = Tk()
L1 = Label(root, text="Your description")
T1 = Text(root)
L1.pack(side=LEFT)
T1.pack(side=RIGHT)
root.mainloop()

rawDescription: Titles for elements in tkinter

description: Titles for elements in tkinter


code: subprocess.check_output("echo hello world", shell=True).strip()

rawDescription: python subprocess output without \n

description: Python subprocess output without \n


code:
def worker(lines):
    """Make a dict out of the parsed, supplied lines"""
    result = {}
    for line in lines.split('\n'):
        k, v = parse(line)
        result[k] = v
    return result

if __name__ == '__main__':
    # configurable options.  different values may work better.
    numthreads = 8
    numlines = 100

    lines = open('input.txt').readlines()

    # create the process pool
    pool = multiprocessing.Pool(processes=numthreads)

    # map the list of lines into a list of result dicts
    result_list = pool.map(worker,
        (lines[line:line+numlines] for line in xrange(0,len(lines),numlines) ) )

    # reduce the result dicts into a single dict
    result = {}
    map(result.update, result_list)

rawDescription: parallel file parsing, multiple CPU cores

description: Parallel file parsing, multiple CPU cores


rawDescription: How to Split by Various Symbols Using Python?

description: Split by Various Symbols Using Python


rawDescription: regex for state abbreviations (python)

description: Regex for state abbreviations (python)


code:
key = "H"
my_key = getattr(uinput,"KEY_"+key)
device.emit(my_key, 1) # Press.
device.emit(my_key, 0) # Release.

rawDescription: Using uinput.emit() Dynamically

description: Using uinput.emit() Dynamically


code:
def multiply_funcs(f, g):
    def multiplied(x):
        return f(x) * g(x)
    return multiplied

rawDescription: Defining multiplication over functions in Python?


code:
line = 'the quick brown fox jumps over the lazy dog'
from collections import Counter
c = Counter(line)
c

rawDescription: python syntax error in dict comprehension

description: Python syntax error in dict comprehension


code:
cols = ["Value_A", "Value_B"]
df[~(df[cols] == df[cols].shift()).all(axis=1)]

rawDescription: Drop duplicates in pandas time series dataframe


code:
import re
with open('filename', 'r') as f:
    list1 = [re.split('[(#]+', line.strip())[0].split() for line in f]

rawDescription: read a file into python and remove values

description: Read a file into python and remove values


code:
version = '1.2.3.4.5-RC4'                 # the end can vary a lot
api = '.'.join(version.split('.')[0:3])   # extract '1.2.3'

rawDescription: Simplify statement '.'.join( string.split('.')[0:3] )


rawDescription: How can I see print() statements in behave (BDD)

description: See print() statements in behave (BDD)


rawDescription: Add a New Sublist to an Existing List

description: Add a New Sublist to an Existing List


code: dict_to_str = lambda x: ','.join("%s:%s" % (str(k), str(v)) for (k, v) in x.iteritems()) if isinstance(x, dict) else x

rawDescription: lambda function to convert dict to string as a lambda expression in python

description: Lambda function to convert dict to string as a lambda expression in python


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

height, width = 50, 33 #in pixels
spines = 'left', 'right', 'top', 'bottom'

labels = ['label' + spine for spine in spines]

tick_params = {spine : False for spine in spines}
tick_params.update({label : False for label in labels})

img = np.random.randint(0, 4097, (height, width))

img *= 255. / 4096

desired_width = 8 #in inches
scale = desired_width / float(width)

fig, ax = plt.subplots(1, 1, figsize=(desired_width, height*scale))
img = ax.imshow(img, cmap=cm.Greys_r, interpolation='none')

#remove spines
for spine in spines:
    ax.spines[spine].set_visible(False)

#hide ticks and labels
ax.tick_params(**tick_params)

#preview
plt.show()

#save
fig.savefig('test.png', dpi=300)

rawDescription: Creating a good quality grayscale image from an multidimensional numpy array


code:
import numpy as np
np.set_printoptions(linewidth=132)
a = np.arange(100).reshape(2,50)
a

rawDescription: wrapping a numpy array in python

description: Wrapping a numpy array in python


code:
from bs4 import BeautifulSoup
import requests

from urllib.parse import urlparse, urljoin

MAX_DEPTH = 4

already_visited = set()

def _get_uri(base_url, href):
    if href.startswith('#'):
        print('discarding anchor {}'.format(href))
        return None

    # We use urljoin to deal with relative hrefs (e.g. <a href="../about.html">)
    # urljoin resolves them using the base_url we provide
    absolute_url = urljoin(base_url, href)

    # Here we take the hostname and we strip www because we want to consider
    # www.test.com and test.com as the same location
    base_url_host = urlparse(base_url).hostname.replace('www.', '')
    absolute_url_host = urlparse(absolute_url).hostname.replace('www.', '')

    # Skip if the href is external (outside of the starting domain)
    # Note that we just stripped www so that www.foo.com and foo.com are considered ==
    if absolute_url_host != base_url_host:
        print('Skipping {}'.format(href))
        return None

    return absolute_url

def spider(start_address):
    _crawl_page(start_address, '/', [])

def _crawl_page(start_address, uri, followed_path):
    path = followed_path[:]
    if len(path) > MAX_DEPTH:
        return

    # For better debugging, we keep track of the current recursion path by creating a list
    # of the hrefs visited by this recursion branch. Instead of using curr_deep, we can just check
    # the length of the visited list, as we append items as we visit them.
    path.append(uri)

    print('Visiting: {}, path: {}'.format(uri, path))

    # Update a set with the current href, so that we don't visit twice the same uri.
    # In practice hrefs should be normalised here to be safe, it's not trivial to deal with
    # all the possible edge cases consistently.
    already_visited.add(uri)

    pageFull = requests.get(start_address)
    pageText = pageFull.text
    soup = BeautifulSoup(pageText, "html.parser")

    for link in soup.findAll("a"):
        uri = _get_uri(start_address, link.get("href"))

        if uri and uri not in already_visited:
            # Recursively visit the links.
            # Note this is a depth-first search (DFS) visit of a tree.
            _crawl_page(start_address, uri, path)

spider("http://www.sheldonbrown.com/index.html")

rawDescription: Python: spider recursive loop

description: Python: spider recursive loop


code:
d = pq("<option value='1'><option value='2'>")
d('option[value="1"]')

rawDescription: JQuery/CSS selectors in Python?

description: JQuery/CSS selectors in Python


code:
class MyBaseModel(BaseModel):
    def serialize():
        abstract # this will throw an error if it's called without being overwritten

class Post(MyBaseModel):
    title = db.stringProperty()
    body = db.textProperty()
    user = db.referenceProperty(User)

    # etc etc etc
    def serialize(self):
        return {
            'title' : self.title,
            'body' : self.body,
            'user' : self.user.serialize()
            # etc
        }

rawDescription: How do I handle database ORM situations like this in Django?

description: Handle database ORM situations like this in Django


code:
import os
f = open('/tmp/test.txt', 'w')
os.unlink(f.name)
# You can still use f here, it's just only visible for people having a handle.
# close it when you're finished.

rawDescription: Removing a file with only the python file object


code:
s = '0-1'
[int(x) for x in s.split('-')]

rawDescription: Calculating cartesian coordinates using python


code:
import pymongo
import datetime

mongo_con = pymongo.Connection('localhost', 27017)
mongo_db = mongo_con.Mongo_database
mongo_col = mongo_db.my_TTL_collection

timestamp = datetime.datetime.now()
utc_timestamp = datetime.datetime.utcnow()

mongo_col.ensure_index("date", expireAfterSeconds=3*60)

mongo_col.insert({'_id': 'session', "date": timestamp, "session": "test session"})
mongo_col.insert({'_id': 'utc_session', "date": utc_timestamp, "session": "test session"})
# the utc_session will be deleted after around 3 minutes,
# the other depending on your timezone

rawDescription: Mongodb TTL expires documents early

description: Mongodb TTL expires documents early


code:
from xml.sax import saxutils as su
s = '<foo>bar</foo>'
su.unescape(s)

rawDescription: From escaped html -> to regular html? - Python


code: pics = Picture.objects.filter(categories__in = [1,2,3]).filter(visible=True)

rawDescription: Database query across django ManyToManyField


code: result = doc.xpath("//tr")[0:-2]

rawDescription: How do I select all of the tr's except the last two tr's

description: Select all of the tr's except the last two tr's


code:
from django.template import Context

def getdjtemplate():
    dj_template = """

        {% for field in form %}

{{ field }}

        {% endfor %}

        """
    return dj_template

form = old_form()
djtemplate = getdjtemplate()
newtmpl = Template(djtemplate)
c = Context({'form': form})
newtmpl.render(c)

rawDescription: How to customize a django form (adding multiple columns)

description: Customize a django form (adding multiple columns)


code:
def set_row_csr(A, row_idx, new_row):
    '''
    Replace a row in a CSR sparse matrix A.

    Parameters
    ----------
    A: csr_matrix
        Matrix to change
    row_idx: int
        index of the row to be changed
    new_row: np.array
        list of new values for the row of A

    Returns
    -------
    None (the matrix A is changed in place)

    Prerequisites
    -------------
    The row index shall be smaller than the number of rows in A
    The number of elements in new row must be equal to the number of rows in matrix A
    '''
    assert sparse.isspmatrix_csr(A), 'A shall be a csr_matrix'
    assert row_idx < A.shape[0], \
            'The row index ({0}) shall be smaller than the number of rows in A ({1})' \
            .format(row_idx, A.shape[0])
    try:
        N_elements_new_row = len(new_row)
    except TypeError:
        msg = 'Argument new_row shall be a list or numpy array, is now a {0}'\
        .format(type(new_row))
        raise AssertionError(msg)
    N_cols = A.shape[1]
    assert N_cols == N_elements_new_row, \
            'The number of elements in new row ({0}) must be equal to ' \
            'the number of rows in matrix A ({1})' \
            .format(N_elements_new_row, N_cols)

    idx_start_row = A.indptr[row_idx]
    idx_end_row = A.indptr[row_idx + 1]
    additional_nnz = N_cols - (idx_end_row - idx_start_row)

    A.data = np.r_[A.data[:idx_start_row], new_row, A.data[idx_end_row:]]
    A.indices = np.r_[A.indices[:idx_start_row], np.arange(N_cols), A.indices[idx_end_row:]]
    A.indptr = np.r_[A.indptr[:row_idx + 1], A.indptr[(row_idx + 1):] + additional_nnz]

rawDescription: Set row of csr_matrix

description: Set row of csr_matrix


code:
import matplotlib
from matplotlib import pyplot as plt

matplotlib.rc('savefig', facecolor='black')
matplotlib.rc('axes', edgecolor='white')
matplotlib.rc('xtick', color='white')
matplotlib.rc('ytick', color='white')
matplotlib.rc('axes', labelcolor='white')
matplotlib.rc('axes', facecolor='black')

plt.plot([0, 1], [0, 1])
plt.savefig('test.png')

rawDescription: change sunpy / pyplot color

description: Change sunpy / pyplot color


code:
auth.define_tables(username=True, signature=False)
auth_table = auth.settings.table_user
auth_table.username.requires = IS_NOT_IN_DB(db, auth_table.username)

rawDescription: web2py adding username validation

description: Web2py adding username validation


code:
from mod_python import apache

def requesthandler(req):
    req.content_type = "text/plain"
    req.write("Hello World!")
    return apache.OK

rawDescription: How to access to the root path in a mod_python directory?

description: Access to the root path in a mod_python directory


code:
import urllib
urllib.urlretrieve("http://www.example.com/songs/mp3.mp3", "/home/download/mp3.mp3")

rawDescription: How to Download Files using Python?

description: Download Files using Python


code:
answer = []
with open('path/to/file') as infile:
    for line in infile:
        answer.append(line.partition('=')[0].strip())

rawDescription: cut the right side of a '=' delimited string and storing into a list in python

description: Cut the right side of a '=' delimited string and storing into a list in python


code:
answer = input('What is wrong with you?')
answer = answer.lower()

heat = ['temperature', 'hot']
cold = ['freezing', 'cold']

for word in answer.split():
    if word in heat:
        problem = 'heat'
    if word in cold:
        problem = 'cold'

print('you have a problem with', problem)

rawDescription: Partial match in a list, from a user input


code: from __future__ import absolute_import

rawDescription: Refer to stdlib module from inside a module of the same name


code:
from operator import itemgetter

lst = [{'modo': itemgetter(j)} for j in range(2)]

rawDescription: Sequence of dictionaries in python

description: Sequence of dictionaries in python


code:
return map(lambda x: x.doSomething(),
           filter(lambda x: x[0] == "z", getIterator()))

rawDescription: How do I convert a python list comprehension to a map/filter function calls?

description: Convert a python list comprehension to a map/filter function calls


code:
def uses_all(required):
    ret = []
    fin = open('words.txt')
    for line in fin:
        # Let´s try and find all our required letters in that word.
        for letter in required:
            if letter not in line:
                break # We`re missing one! Break!

        else: # else block executes if no break occured
            ret.append(line)

    return ret

rawDescription: Use Function to Return a List of Words Containing Required Letters


code:
import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        frame = QtGui.QFrame()
        frame.setFrameStyle(QtGui.QFrame.Panel |
                QtGui.QFrame.Plain)

        label = QtGui.QLabel('This is random text')

        dockWidget = QtGui.QDockWidget('Main', self)
        # set the widget to non-movable, non-floatable and non-closable
        dockWidget.setFeatures(dockWidget.NoDockWidgetFeatures)
        dockWidget.setWidget(label)

        # add the QDockWidget to the QLayout
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(dockWidget)

        # set the layout of the QFrame
        frame.setLayout(hbox)

        # create another QLayout to add QFrame
        vbox = QtGui.QVBoxLayout()
        vbox.addStretch(1)
        vbox.addWidget(frame)

        self.setLayout(vbox)

        self.setGeometry(300, 300, 500, 400)
        self.setWindowTitle('Test')

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: how to add QDockWidget to QFrame in PyQt4

description: Add QDockWidget to QFrame in PyQt4


code: column_list = ['id', 'name', 'other_column']

rawDescription: Change order of columns in Flask-Admin list view


code:
class JHtmlEscapingFlask(Flask):

    def select_jinja_autoescape(self, filename):
        if filename is None:
            return False
        if filename.endswith('.jhtml'):
            return True
        return Flask.select_jinja_autoescape(self, filename)

app = JHtmlEscapingFlask(__name__)

rawDescription: How do I enable autoescaping in templates with a .jhtml extension in Flask?

description: Enable autoescaping in templates with a .jhtml extension in Flask


code: fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

rawDescription: How to make more room for subplot text fields in Python's matplotlib?

description: Make more room for subplot text fields in Python's matplotlib


code:
def test(classToMimic):

    class Test(classToMimic):

        def methodToOverwrite(self):
            doStuffForTest

    return Test

rawDescription: python dynamically changing super

description: Python dynamically changing super


code:
from sklearn.cross_validation import KFold, cross_val_score
from sklearn.datasets import load_iris
from sklearn.svm import SVC

iris = load_iris()
kf = KFold(len(iris.target), 5, random_state=0)
clf = SVC(kernel='linear', C=1)
scores = cross_val_score(clf, iris.data, iris.target, cv=kf)

rawDescription: How to get the folds themselves that are partitioned internally in sklearn.cross_validation.cross_val_score?

description: Get the folds themselves that are partitioned internally in sklearn.cross_validation.cross_val_score


code:
import pandas as pd
from StringIO import StringIO

st = """
Site|Roadname|Count|id|Count_norm
9|A316 Twickenham Rd, Richmond|1474|9SOUTHBOUND|1428
9|A316 Twickenham Rd, Richmond|1375|9SOUTHBOUND|1329
9|A316 Twickenham Rd, Richmond|1052|9SOUTHBOUND|1006
9|A316 Twickenham Rd, Richmond|986|9SOUTHBOUND|940
9|A316 Twickenham Rd, Richmond|1071|9SOUTHBOUND|1025
9|A316 Twickenham Rd, Richmond|1206|9SOUTHBOUND|1160
9|A316 Twickenham Rd, Richmond|1474|9NORTHBOUND|1428
9|A316 Twickenham Rd, Richmond|1375|9NORTHBOUND|1329
9|A316 Twickenham Rd, Richmond|1052|9NORTHBOUND|1006
9|A316 Twickenham Rd, Richmond|986|9NORTHBOUND|940
9|A316 Twickenham Rd, Richmond|1071|9NORTHBOUND|1025
9|A316 Twickenham Rd, Richmond|1206|9NORTHBOUND|1160
"""

data = pd.read_csv(StringIO(st), delimiter="|", error_bad_lines=False)

#get a list of unique ids
ids = pd.unique(data["id"].values.ravel())

grouped_data = data.groupby("id")
for id in ids:
    #get the dataframe for the current id
    df = grouped_data.get_group(id)
    #export current id's dataframe to a csv file with its name
    df.to_csv(str(id)+".csv", sep="|", index=False)

rawDescription: Iterative creation of csv files by series in Pandas


code:
class SimpleServer(gevent.server.StreamServer):

    def handle(self, socket, address):
        socket.sendall('hello and goodbye!')

class Test(unittest.TestCase):

    def test(self):
        server = SimpleServer(('127.0.0.1', 0))
        server.start()
        client = gevent.socket.create_connection(('127.0.0.1', server.server_port))
        response = client.makefile().read()
        assert response == 'hello and goodbye!'
        server.stop()

rawDescription: Python: unit testing socket-based code?

description: Python: unit testing socket-based code


code:
import types
import functools

def make_delegating_type(delegatee):
    class DelegatingType(type):
        def __getattr__(self, name):
            obj = getattr(delegatee, name)
            if isinstance(obj, (types.FunctionType, types.MethodType)):
                @functools.wraps(obj)
                def wrapper(*args, **kwargs):
                    result = obj(*args, **kwargs)
                    if isinstance(result, delegatee):
                        return self(result)
                    return result
                return wrapper
            return obj
    return DelegatingType

class Foo(object):
    def __init__(self, a): self.a = a

    @classmethod
    def from_a(cls, a): return cls(a)

class Bar(object):
    __metaclass__ = make_delegating_type(Foo)
    def __init__(self, foo): self._foo = foo

    def __getattr__(self, name): return getattr(self._foo, name)

rawDescription: Delegating @classmethods in python

description: Delegating @classmethods in python


code:
x =  (((-300, 49.3878), (-300, 400), (-220.045, 400), (-169.193, 204.22), (-300, 49.3878)))

y = tuple(tuple(i / 100.0 for i in inner) for inner in x)

# You can remove the tuple and instead use [] if you don't mind it being a list.
y_list = [[i / 100.0 for i in inner] for inner in x]

rawDescription: scaling each element in a tuple in python

description: Scaling each element in a tuple in python


code:
f = open('filename.ext', 'rb')
f.seek(255) # skip the first 255 bytes
rest = f.read() # read rest

rawDescription: Remove number of bytes from beginning of file


code:
import random

candidateWords = ['AETHER', 'BADGED', 'BALDER', 'BANDED', 'BANTER', 'BARBER']

candidateWordsShuffled = random.sample(candidateWords, min(len(candidateWords), 8))

def wordlist():
    for index, item in enumerate(candidateWordsShuffled):
        print(index, ") ", item, sep='')

one = random.choice(candidateWordsShuffled)
print(one)

print("Welcome to the Guess-The-Word Game.\nThe Password is one of these words:")
wordlist()

rawDescription: Generating a random permutation of a list


code:
import glob
from collections import Counter
dic=dict()
g_iter = glob.iglob(r'c:\\python32\fol\*')
for x in g_iter:

    lis=[]
    with open(x) as f:
        inp = f.readlines()
    for line in inp:
        num=line.split()[-1]
        lis.append(num)
    C=Counter(lis)
    dic=dict( (n, dic.get(n, 0)+C.get(n, 0)) for n in set(dic)|set(C) )
for x in dic:
    print(x,'\t',dic[x])

rawDescription: generating a single outfile after analyzing multiple files in python

description: Generating a single outfile after analyzing multiple files in python


code:
# FULL WORKING POST FOR JSON & FILE
def post(self, request, format=None):
    up_file = request.data.get('file')
    serializer = ridesSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        if up_file is not None:
            if socket.getfqdn() == 'STG' or socket.getfqdn() == 'PRD':
                destination = open(PRD_UPLOAD + up_file.name, 'wb+')
            else:
                destination = open('/Users/ncole/Documents/rides/ridesAPI/uploads/' + up_file.name, 'wb+')
            for chunk in up_file.chunks():
                destination.write(chunk)
                destination.close()
            return Response(up_file.name, status=status.HTTP_201_CREATED)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

rawDescription: Python/Django REST Framework POST based on Content-Type header


code:
class _ListProxy:
    def __init__(self, system):
        self._system = system

    def __getitem__(self, index):
        return self._system._components[index].attr

    def __setitem__(self, index, value):
        self._system._components[index].attr = value

class System:
    ...
    @property
    def attrs(self):
        return _ListProxy(self)

rawDescription: How to implement a list of references in python?

description: Implement a list of references in python


rawDescription: Adding Submatrix in Numpy without Loop

description: Adding Submatrix in Numpy without Loop


rawDescription: Scrapy Extract number from page text with regex


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup("""
<text>
<smtng>1</smtng>
<smtngelse>5</smtngelse>
</text>
""")

value1 = soup.find('smtng').text
value2 = soup.find('smtngelse').text

with open('output.txt', 'a') as f:
    f.write('%s\t%s\n' % (value1, value2))

rawDescription: Python & regexp - returning integers from various lines then write then delimited by tab into a different file


code:
with open("test.txt") as f:
  for line in f:
    if re.match("BREAK", line):
      print("Break")
      break
    m = re.match(r'((((2)([0-3]))|(([0-1])([0-9])))([0-5])([0-9]))', line)
    if m:
      print(m.group(0))

rawDescription: using two regular expressions to search a file

description: Using two regular expressions to search a file


code:
def Create(filename):
    global file
    UserFile = open(str(filename), "wt")
    file = (str(filename))
    #return file  -- I commented this since there is no real reason to return now with a global

rawDescription: How do I send a variable back to the main program from a function?

description: Send a variable back to the main program from a function


code:
def get_email_google(request):
    # social = request.user.social_auth.get(provider='google-oauth2')
    user =request.user

    # Code dependent upon django-allauth. Will change if we shift to another module

    # if request.user.userprofile.get_provider() != "google":
    a = SocialAccount.objects.get(user=user)
    b = SocialToken.objects.get(account=a)
    # access = b.token
    access_token = b.token
    url = 'https://www.google.com/m8/feeds/contacts/default/full' + '?access_token=' + access_token + '&max-results=100'
    req = urllib2.Request(url, headers={'User-Agent' : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.30 (KHTML, like Gecko) Ubuntu/11.04 Chromium/12.0.742.112 Chrome/12.0.742.112 Safari/534.30"})
    contacts = urllib2.urlopen(req).read()
    contacts_xml = etree.fromstring(contacts)
    # print
    # return render(request, 'search/random_text_print.html', locals())

    result = []

    for entry in contacts_xml.findall('{http://www.w3.org/2005/Atom}entry'):
        for address in entry.findall('{http://schemas.google.com/g/2005}email'):
            email = address.attrib.get('address')
            result.append(email)
    return render(request, 'search/random_text_print.html', locals())

rawDescription: How to use google contacts api to allow my users to invite their gmail contacts to my django website

description: Use google contacts api to allow my users to invite their gmail contacts to my django website


code:
cherrypy.server.socket_host = 'www.machinename.com'
cherrypy.engine.start()
cherrypy.engine.block()

rawDescription: How do I configure the ip address with CherryPy?

description: Configure the ip address with CherryPy


code:
import Cocoa
def evthandler(event):
  pass # this is where you do stuff; see NSEvent documentation for event
observer = Cocoa.NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDown, evthandler)
# when you're done
Cocoa.NSEvent.removeMonitor_(observer)

import Quartz
def evthandler(proxy, type, event, refcon):
    pass # Here's where you do your stuff; see CGEventTapCallback
    return event
source = Quartz.CGEventSourceCreate(Quartz.kCGEventSourceStateHIDSystemState)
tap = Quartz.CGEventTapCreate(Quartz.kCGSessionEventTap,
                              Quartz.kCGHeadInsertEventTap,
                              Quartz.kCGEventTapOptionListenOnly,
                              (Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) |
                               Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp)),
                              handler,
                              refcon)

rawDescription: Something like pyHook on OS X

description: Something like pyHook on OS X


code:
from BeautifulSoup import BeautifulSoup
text1 = 'Consultant Registration Number  :  16043646	'
text2 = 'Consultant Registration Number  :	'
BeautifulSoup(text1).td.font.nextSibling
BeautifulSoup(text2).td.font.nextSibling

rawDescription: Get text outside one tag and inside another


code:
import re
s = 'apple_orange_banana_common_fruit'
re.search(r'([a-zA-Z]+)_common', s).group(1)

rawDescription: Extracting a substring of a string in Python based on presence of another string


code:
from xml.dom.minidom import parse
doc = parse("filename.xml")

rawDescription: XML parsing in Python

description: XML parsing in Python


code:
class E(C, D):
    def do_c_thing(self):
        # Call C's version
        C.some_method(self, ...)

    def do_d_thing(self):
        # Call D's version
        D.some_method(self, ...)

rawDescription: Python multiple inheritence issues

description: Python multiple inheritence issues


code:
from datetime import datetime, date, time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
with open('sample-2dayslineEURUSDM1.csv', 'r') as fh:
    print(fh.readline())
    print(fh.readline())
    data = pd.read_csv('sample-2dayslineEURUSDM1.csv',
               parse_dates={'Timestamp':['Date','Time']},
               index_col='Timestamp')
data.index
ticks = data.ix[:,['Close']]
ticks.head()
ticks.ix['2005-02-15 01:35:00':'2005-02-16 23:59:00'].plot()

rawDescription: Ploting datetime data from pandas datetime


code:
import some_module

class MyClass(object):
    def foo(self, x, y, z):
        result = some_module.bar(x, y, z)
        return result[0] + 2, result[1] * 2, result[2] - 2

class TestMyClass(TestCase):
    @mock.patch('some_module.bar')
    def test_myclass(self, mocked_bar):
        mocked_bar.return_value = (10, 20, 30)

        mc = MyClass()

        # calling MyClass.foo returns a result based on bar()
        self.assertEquals(mc.foo('spam', 'ham', 'eggs'),
            (12, 40, 28))
        # some_class.bar() was called with the original arguments
        mocked_bar.assert_called_with('spam', 'ham', 'eggs')

rawDescription: Python Mock - How to get the return of a MagicMock as if it was a normal method


code:
def get_or_create_task_logger(func):
    """ A helper function to create function specific logger lazily. """

    # https://docs.python.org/2/library/logging.html?highlight=logging#logging.getLogger
    # This will always result the same singleton logger
    # based on the task's function name (does not check cross-module name clash,
    # for demo purposes only)
    logger = logging.getLogger(func.__name__)

    # Add our custom logging handler for this logger only
    # You could also peek into Celery task context variables here
    #  http://celery.readthedocs.org/en/latest/userguide/tasks.html#context
    if len(logger.handlers) == 0:
        # Log to output file based on the function name
        hdlr = logging.FileHandler('%s.log' % func.__name__)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)
        logger.setLevel(logging.DEBUG)

    return logger

@app.task(base=CallbackTask)
def calc(syntax):
    logger = get_or_create_task_logger(calc)
    some_func()
    logger.info('started')

rawDescription: Celery: log each task run to it's own file?


code:
import keyring
keyring.set_password("my_api_key", "username", "ABC1234SEKRIT")
keyring.get_password("my_api_key", "username")

rawDescription: How can I hide sensitive data before commiting to GitHub (or any other Git repo)?

description: Hide sensitive data before commiting to GitHub (or any other Git repo)


code:
class LogEntryAdmin(ModelAdmin):
    actions = None
    list_display = (
        'action_time', 'user',
        'content_type', 'object_repr',
        'change_message')

    search_fields = ['=user__username', ]
    fieldsets = [
        (None, {'fields':()}),
        ]

    def __init__(self, *args, **kwargs):
        super(LogEntryAdmin, self).__init__(*args, **kwargs)
        self.list_display_links = (None, )

rawDescription: Disable link to edit object in django's admin (display list only)?


code:
#!/usr/bin/env python
import os

def application(environ, start_response):
    # Mimetype
    ctype = 'text/html'

    # Directory
    dir = environ["SCRIPT_FILENAME"][:environ["SCRIPT_FILENAME"].rindex("/")]
    # Get File Contents
    file_contents = b""
    with open(dir+"/main.html", "rb") as file:
        file_contents = file.read()

    # Add Dynamic Content
    response_body = b"This is a header!".join( \
        b"".join( \
            file_contents.split(b"%(HEAD)") \
        ).split(b"%(HEADING)") \
    )

    # Heading
    status = '200 OK'
    response_headers = [ \
        ('Content-Type', ctype), ('Content-Length', str(len(response_body))) \
    ]

    # Send Response
    start_response(status, response_headers)
    return [response_body.encode('utf-8') ]

rawDescription: How to access other files from mod_wsgi on OpenShift

description: Access other files from mod_wsgi on OpenShift


code:
items_by_start = dict((i.start, i) for i in your_items)

ordered_items = [your_items[0]]
for _ in xrange(len(your_items)-1):
    ordered_items.append(items_by_start[ordered_items[-1].end])

rawDescription: What's the best way to do this in Python?


code:
gameOver = False
playerScore = 0
computerScore = 0

while not gameOver:
    player_wins = main()
    if player_wins == True:
        playerScore += 1
        computerScore = 0
    if player_wins == False:
        playerScore = 0
        computerScore += 1
    if player_wins == None:
        # Draw, do nothing to the scores
        pass
    if playerScore == 2 or computerScore == 2:
        print("Game over")
        print("  playerScore:", playerScore)
        print("  computerScore:", computerScore)
        gameOver = True

rawDescription: Python Rock Paper Scissors game ( Loop for certain condition )


code:
import os
import importlib

#new_module = __import__("module")
new_module = importlib.import_module("module")

new_module_filename = os.path.realpath(new_module.__file__)
if new_module_filename.endswith(".pyc"):
    new_module_filename = new_module_filename[:-1]

with open(new_module_filename) as ff:
    source = ff.read()
print(source)

rawDescription: Converting the *.py script into a string


code:
#!/usr/bin/python

parent=''
child=''

for line in open('input.txt'):
        if line.find('#Parent') > -1 or line.find('# Parent') > -1:
                parent = field_extract(line) # fun where you extract parent value
                parent_id = ... # write it down or generate
                # INSERT into PARENT
        elif line:
                child = field_extract(line)
                # INSERT into CHILDREN with parent_id and child values

rawDescription: Parsing text file to sql database using python


code:
counter = 0
while True: #your main loop
    smoke = digital_read() #assume 0 = no alarm, 1 = alarm
    if smoke:
        counter += 1
    else:
        counter = 0
    if counter >= 4: #there was smoke for the last 4 seconds
        call_the_fire_brigade()
    time.sleep(1) #wait one second

rawDescription: Python IF statement to see how long an input has been active


code:
def threshold(the_list, threshold, upper, lower):
  return [lower if item <= threshold else upper for item in the_list]

threshold([-1,2,5,3,-1,5,32,-6],0,1,0)
# => [0, 1, 1, 1, 0, 1, 1, 0]

rawDescription: Are lists immutable in python? And are they passed value in a function?


code:
def cmp_to_key(mycmp):
    'Convert a cmp= function into a key= function'
    class K(object):
        def __init__(self, obj, *args):
            print('obj created with ',obj)
            self.obj = obj
        def __lt__(self, other):
            print('comparing less than ',self.obj)
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            print('comparing greter than ',self.obj)
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            print('comparing equal to ',self.obj)
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            print('comparing less than equal ',self.obj)
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            print('comparing greater than equal',self.obj)
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            print('comparing not equal ',self.obj)
            return mycmp(self.obj, other.obj) != 0
    return K
def mycmp(a, b):
    print("In Mycmp for", a, ' ', b)
    if a < b:
        return -1
    elif a > b:
        return 1
    return 0
print(sorted([3,4,2,5],key=cmp_to_key(mycmp)))

rawDescription: Python: how does the functools cmp_to_key function works?


rawDescription: Aggregate Dataframe into weighted average series


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

# radius of each bar
radii = [10,  15, 20, 25]

# Value - width
width = np.pi/ 2

# angle of each bar
theta = np.radians([0,90,180,270])

ax = plt.subplot(111, polar=True)
bars = ax.bar(theta, radii, width=width, alpha=0.5)
plt.show()

rawDescription: fourfold display in matplotlib using polar axis

description: Fourfold display in matplotlib using polar axis


code: kafka[:] = [x for x in kafka if x not in stop]

rawDescription: How to delete specific words from a list?

description: Delete specific words from a list


rawDescription: remove multiple substrings inside a string

description: Remove multiple substrings inside a string


rawDescription: Python from variable file import

description: Python from variable file import


code:
asrock = Brand(name='Asrock')
asus = Brand(name='Asus')
mobo = Category(name='Motherboard')
proc = Category(name='Processor')
session.commit()

p1 = Product(name='N98', cost=2100.50, price=2500.50, order_quantity=5, unit='unit',
    category=mobo, brand=asrock)

p2 = Product(name='M-N98', cost=2300.50, price=2500.50, order_quantity=5, unit='unit',
    category=mobo, brand=asus)

session.commit()

rawDescription: Python Elixir OneToMany and ManyToOne implementation: On Inserting new record with OneToMany relationship?


code:
import pandas
import numpy
my_series = pandas.Series([0,0,1,2,0,3,4,0,0])
numpy.trim_zeros(my_series)

rawDescription: Pandas: remove trailing zeros from series


code:
from setuptools import setup

setup(
    name='foo',
    version='0.0.1',
    description='',
    url='',
    classifiers=[
        'Programming Language :: Python :: 2.7',
    ],
    install_requires=[
        'bpython',
        'Django==1.8.2',
    ],
)

rawDescription: How to create a Pure-Python wheel

description: Create a Pure-Python wheel


code: self.panel.SetScrollbars(1, 1, 1, 1)

rawDescription: Creating ScrolledWindow in wxPython

description: Creating ScrolledWindow in wxPython


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

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import Image
import ImageQt
import ImageEnhance
import time

class TestWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.scene = QGraphicsScene()
        self.view = QGraphicsView(self.scene)
        self.button = QPushButton("Do test")

        layout = QVBoxLayout()
        layout.addWidget(self.button)
        layout.addWidget(self.view)
        self.setLayout(layout)

        self.button.clicked.connect(self.do_test)

    def do_test(self):
        img = Image.open('image.png')
        enhancer = ImageEnhance.Brightness(img)
        for i in range(1, 8):
            img = enhancer.enhance(i)
            self.display_image(img)
            QCoreApplication.processEvents()  # let Qt do his work
            time.sleep(0.5)

    def display_image(self, img):
        self.scene.clear()
        w, h = img.size
        self.imgQ = ImageQt.ImageQt(img)  # we need to hold reference to imgQ, or it will crash
        pixMap = QPixmap.fromImage(self.imgQ)
        self.scene.addPixmap(pixMap)
        self.view.fitInView(QRectF(0, 0, w, h), Qt.KeepAspectRatio)
        self.scene.update()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = TestWidget()
    widget.resize(640, 480)
    widget.show()

    sys.exit(app.exec_())

rawDescription: Displayin an Image in a QGraphicsScene

description: Displayin an Image in a QGraphicsScene


code:
res = {'SGMB': [['SGMB', 'SANTM', 'CRSR', 'RAT']], 'CRSR': [['SGMB', 'SANTM', 'CRSR', 'RAT'], ['CRSR', 'RAT', 'ARG']], 'RAT': [['ARG', 'RAT'], ['SGMB', 'SANTM', 'CRSR', 'RAT'], ['CRSR', 'RAT', 'ARG']], 'PARTICIPANT_COLL_ID': [['PARTICIPANT_COLL_ID']], 'ARG': [['ARG', 'RAT'], ['CRSR', 'RAT', 'ARG']], 'SANTM': [['SGMB', 'SANTM', 'CRSR', 'RAT']]}
newres = {k: list({x for t in v for x in t if x != k}) for k, v in res.iteritems()}
newres

rawDescription: Python dictionaries: merging multiple value lists into a single list of unique values


code:
import re, json

json_str = """{u'spec1': {u'property1': u'12345', u'property2': 1234}, u'spec2': {u'property3': u'98754', u'property4': u'val1'}}"""
json_str = json_str.replace("\'", "\"")
json_str = re.sub(r"u\"", "\"", json_str)

json_dict = json.loads(json_str)

rawDescription: Converting JSON-like object to JSON

description: Converting JSON-like object to JSON


code:
import win32com.client
import subprocess
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate("DullRazor for Windows")
shell.SendKeys("{TAB}", 0)

rawDescription: Run an exe file with parameters to browse a file


rawDescription: Getting today's date in YYYY-MM-DD in Python?


code:
class Node(object):
    _id = 0

    def __init__(self):
        self._id = Node._id
        Node._id += 1

rawDescription: Giving unique IDs to all nodes?

description: Giving unique IDs to all nodes


rawDescription: How flatten a list of lists one step

description: How flatten a list of lists one step


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

# We'll use two separate gridspecs to have different margins, hspace, etc
gs_top = plt.GridSpec(5, 1, top=0.95)
gs_base = plt.GridSpec(5, 1, hspace=0)
fig = plt.figure()

# Top (unshared) axes
topax = fig.add_subplot(gs_top[0,:])
topax.plot(np.random.normal(0, 1, 1000).cumsum())

# The four shared axes
ax = fig.add_subplot(gs_base[1,:]) # Need to create the first one to share...
other_axes = [fig.add_subplot(gs_base[i,:], sharex=ax) for i in range(2, 5)]
bottom_axes = [ax] + other_axes

# Hide shared x-tick labels
for ax in bottom_axes[:-1]:
    plt.setp(ax.get_xticklabels(), visible=False)

# Plot variable amounts of data to demonstrate shared axes
for ax in bottom_axes:
    data = np.random.normal(0, 1, np.random.randint(10, 500)).cumsum()
    ax.plot(data)
    ax.margins(0.05)

plt.show()

rawDescription: Pylab - Adjust hspace for some of the subplots


code:
for thing in things:
    ...
    if (thing == 'something'):
        break
else:
    ... # Do something

rawDescription: Better pythonic idiom for this repeated piece code pattern


code:
a.levels
a.labels

rawDescription: How do I create a Categorial with my own levels in Pandas?

description: Create a Categorial with my own levels in Pandas


rawDescription: python absolute XPath returns empty list, generic query better?

description: Python absolute XPath returns empty list, generic query better


code:
from decimal import *
# create a `Context` to control decimal point precision
program_context = Context(prec=4)
# activate the `Context`
setcontext(program_context)
# from this point on all decimal numbers will be truncated to 4 decimal places.
# you can control the rounding behaviour when the `Context` is created; for example:
new_program_context = Context(prec=4, rounding=ROUND_UP)
# activate the new `Context`
setcontext(new_program_context)
# other rounding options include:
# ROUND_CEILING (towards Infinity),
# ROUND_DOWN (towards zero),
# ROUND_FLOOR (towards -Infinity),
# ROUND_HALF_DOWN (to nearest with ties going towards zero),
# ROUND_HALF_EVEN (to nearest with ties going to nearest even integer),
# ROUND_HALF_UP (to nearest with ties going away from zero), or
# ROUND_UP (away from zero).
# note that `Context`s only apply to numbers that are explicitly declared to be `Decimal`
a = Decimal(2)
b = Decimal(3)
a/b # evaluates to Decimal('0.6667')
c = 2
d = 3
c/d # evaluates to the floating point number 0.6666666666666666
# also, if constructing a Decimal number from a float, the float must be passed as
# as a string; eg:
e = Decimal("0.6678") # evaluates to Decimal('0.6678')
f = Decimal(0.6678)
# f evaluates to Decimal('0.6677999999999999491961943931528367102146148681640625')
# integers, however, can be created directly; eg:
h = Decimal(10) # evaluates to Decimal('10')

rawDescription: Is there any command that enables to set for the whole program the number of decimals in a float variable?


code:
content
tickers = []
for s in content:
    tickers.append(''.join(i for i in s if i.isupper()))

tickers

rawDescription: Python List Regex

description: Python List Regex


code:
import random

LOWEST = 1
HIGHEST = 100

def main():
    print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
    secret = random.randint(LOWEST, HIGHEST)

    tries = 0
    while True:
        guess = raw_input('Your guess: ').strip().lower()
        if guess.isdigit():
            tries += 1
            guess = int(guess)
            if guess < secret:
                print('Higher!')
            elif guess > secret:
                print('Lower!')
            else:
                print('You got it in {} tries!'.format(tries))
                break
        elif guess == "reveal":
            print('The secret number was {}'.format(secret))
            break
        else:
            print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))

if __name__=="__main__":
    main()

rawDescription: Could not convert string to float in input


code:
tasks = [Task(url=url_for('main.endpoints_worker'),params={'id': id}) for id in id_list]
rpc = Queue('event-message').add_async(tasks)
rpc.wait()

rawDescription: GAE - What is the fastest way to add tasks to queue? Why does this appear to be so slow?


code:
class EventForm(forms.ModelForm):

   def __init__(self, *args, **kwargs):
       self.request = kwargs.pop('request', None) # set 'request' if passed as kwarg
       return super(EventForm, self).__init__(*args, **kwargs)

rawDescription: Saving the user who created the model instance


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

def f(a):
   c1 = 0.327159886574049
   c2 = 29.3930964972769
   return a/(a+np.exp(c1-c2*a))

x = np.linspace(0, 1, 500)
y = f(x)
plt.plot(x,y)
plt.show()

rawDescription: plotting sympy results in python

description: Plotting sympy results in python


code:
dim = 40
mat = np.zeros((dim,dim))

for k in range(0,dim):
    for j in range(0,dim):
        mat[k,j] = data_res[(k*dim)+j,0]

rawDescription: Tricky Python array sorting

description: Tricky Python array sorting


code:
math
def f():
    global math
    import math
f()
math

rawDescription: Python: how to make global imports from a function


code:
from django.db.models import Func, F

class Sin(Func):
    function = 'SIN'

class Cos(Func):
    function = 'COS'

class Acos(Func):
    function = 'ACOS'

class Radians(Func):
    function = 'RADIANS'

radlat = Radians(latitude) # given latitude
radlong = Radians(longitude) # given longitude
radflat = Radians(F('latitude'))
radflong = Radians(F('longitude'))

Expression = 3959.0 * Acos(Cos(radlat) * Cos(radflat) *
                           Cos(radflong - radlong) +
                           Sin(radlat) * Sin(radflat))

Trader.objects.annotate(distance=Expression).order_by('distance')

rawDescription: Ordering queryset by distance relative to a given position


rawDescription: Maya - animation curves for selected objects using python