code:
import sys
from PySide.QtCore import *
from PySide.QtGui import *

class LinkItemDelegate(QItemDelegate):
    linkActivated = Signal(str)
    linkHovered = Signal(str)  # to connect to a QStatusBar.showMessage slot

    def __init__(self, parentView):
        QItemDelegate.__init__(self, parentView)
        assert isinstance(parentView, QAbstractItemView), \
            "The first argument must be the view"

        # We need that to receive mouse move events in editorEvent
        parentView.setMouseTracking(True)

        # Revert the mouse cursor when the mouse isn't over
        # an item but still on the view widget
        parentView.viewportEntered.connect(parentView.unsetCursor)

        # documents[0] will contain the document for the last hovered item
        # documents[1] will be used to draw ordinary (not hovered) items
        self.documents = []
        for i in range(2):
            self.documents.append(QTextDocument(self))
            self.documents[i].setDocumentMargin(0)
        self.lastTextPos = QPoint(0,0)

    def drawDisplay(self, painter, option, rect, text):
        # Because the state tells only if the mouse is over the row
        # we have to check if it is over the item too
        mouseOver = option.state & QStyle.State_MouseOver \
            and rect.contains(self.parent().viewport() \
                .mapFromGlobal(QCursor.pos())) \
            and option.state & QStyle.State_Enabled

        if mouseOver:
            # Use documents[0] and save the text position for editorEvent
            doc = self.documents[0]
            self.lastTextPos = rect.topLeft()
            doc.setDefaultStyleSheet("")
        else:
            doc = self.documents[1]
            # Links are decorated by default, so disable it
            # when the mouse is not over the item
            doc.setDefaultStyleSheet("a {text-decoration: none}")

        doc.setDefaultFont(option.font)
        doc.setHtml(text)

        painter.save()
        painter.translate(rect.topLeft())
        ctx = QAbstractTextDocumentLayout.PaintContext()
        ctx.palette = option.palette
        doc.documentLayout().draw(painter, ctx)
        painter.restore()

    def editorEvent(self, event, model, option, index):
        if event.type() not in [QEvent.MouseMove, QEvent.MouseButtonRelease] \
            or not (option.state & QStyle.State_Enabled):
            return False
        # Get the link at the mouse position
        # (the explicit QPointF conversion is only needed for PyQt)
        pos = QPointF(event.pos() - self.lastTextPos)
        anchor = self.documents[0].documentLayout().anchorAt(pos)
        if anchor == "":
            self.parent().unsetCursor()
        else:
            self.parent().setCursor(Qt.PointingHandCursor)
            if event.type() == QEvent.MouseButtonRelease:
                self.linkActivated.emit(anchor)
                return True
            else:
                self.linkHovered.emit(anchor)
        return False

    def sizeHint(self, option, index):
        # The original size is calculated from the string with the html tags
        # so we need to subtract from it the difference between the width
        # of the text with and without the html tags
        size = QItemDelegate.sizeHint(self, option, index)

        # Use a QTextDocument to strip the tags
        doc = self.documents[1]
        html = index.data() # must add .toString() for PyQt "API 1"
        doc.setHtml(html)
        plainText = doc.toPlainText()

        fontMetrics = QFontMetrics(option.font)
        diff = fontMetrics.width(html) - fontMetrics.width(plainText)

        return size - QSize(diff, 0)

rawDescription: Hyperlinks in QTreeView without QLabel

description: Hyperlinks in QTreeView without QLabel


code:
target = "dir where you want to copy contents of source"
basedir = "source dir containing content to be copied"
env.Accumulate(target, [os.path.join(basedir ,x) for x in os.listdir(basedir)])

rawDescription: Scons Multi-Directory copying/zipping

description: Scons Multi-Directory copying/zipping


code:
df
df.loc[:, (df != df.ix[0]).any()]

rawDescription: panda dataframe remove constant column

description: Panda dataframe remove constant column


rawDescription: Project Euler #8, I don't understand why I'm going wrong


code:
import pyPdf
pdf = pyPdf.PdfFileReader(open(filename, "rb"))
data = ''
for page in pdf.pages:
   data += page.extractText()
data2 = data.split('\n')

rawDescription: Mining pdf Data with python through clipboard - Python Scripting the OS


code:
import xxx
results = xxx.main('foo')
# Do something with results

rawDescription: How to run command line python script in django view?

description: Run command line python script in django view


code:
import numpy as np
from scipy import misc
pic = misc.imread("ri1.jpg", flatten=True)
x, y = np.meshgrid(np.arange(pic.shape[1]), np.arange(pic.shape[0]))
circle_x, circle_y, circle_radius = 200, 400, 100
args = np.argwhere( np.sqrt((x-circle_x)**2+(y-circle_y)**2)<circle_radius )
#pic[args] = np.median(pic[args])   # doesn't work?!?
pic[args[:,0], args[:,1]] = np.median(pic[args[:,0], args[:,1]])
misc.imsave("ri1_new.jpg", pic)

rawDescription: How to inpaint a region of a picture, with the median of that region?

description: Inpaint a region of a picture, with the median of that region


code:
from shapely.geometry import Point

if mypoly.is_empty:
    mypoly = Point(0, 0)

rawDescription: How to check if a polygon is empty in Python using Shapely?

description: Check if a polygon is empty in Python using Shapely


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        # a simple label, just to show there's something in the frame
        label = tk.Label(self, text="Example of using place")
        label.pack(side="top", fill="both", expand=True)

        # we'll place this image in every corner...
        self.image = tk.PhotoImage(data='''
            R0lGODlhEAAQALMAAAAAAP//AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
            AAAAAAAAAAAA\nAAAAACH5BAEAAAIALAAAAAAQABAAQAQ3UMgpAKC4hm13uJnWgR
            TgceZJllw4pd2Xpagq0WfeYrD7\n2i5Yb+aJyVhFHAmnazE/z4tlSq0KIgA7\n
        ''')

        # ... by creating four label widgets ...
        self.nw = tk.Label(self, image=self.image)
        self.ne = tk.Label(self, image=self.image)
        self.sw = tk.Label(self, image=self.image)
        self.se = tk.Label(self, image=self.image)

        # ... and using place as the geometry manager
        self.nw.place(relx=0.0, rely=0.0, anchor="nw")
        self.ne.place(relx=1.0, rely=0.0, anchor="ne")
        self.sw.place(relx=0.0, rely=1.0, anchor="sw")
        self.se.place(relx=1.0, rely=1.0, anchor="se")

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

rawDescription: Image in corner of tkinter window in python 3


code: print(' MENU '.center(80, '*'))

rawDescription: How to fill an entire line with * characters in Python

description: Fill an entire line with * characters in Python


code:
import sys
sys.getsizeof(23)
import pickle
len(pickle.dumps(23, -1))

rawDescription: How to get the size of a python object in bytes on Google AppEngine?

description: Get the size of a python object in bytes on Google AppEngine


code:
values = map(compare, new_subjects.values())
len([x for x in values if x]) == len(values) - 1

rawDescription: every element of list is True boolean

description: Every element of list is True boolean


rawDescription: Tkinter help viewer

description: Tkinter help viewer


code:
zip('foo', 'bar')
zip('foo', 'bar', 'baz')  # you can add more sequences
sizes = [5, 12, 18, 23, 42]
zip(sizes[:-1], sizes[1:])  # a sliding window of pairs

rawDescription: Python beginner, understanding some code


code: line = line.replace(item, ""+item+"")

rawDescription: Writing output of a python script to HTML with CGI


code:
import logging

class IgnoreURLFilter(logging.Filter):
    # simple example of log message filtering

    def __init__(self, ignore):
        self.ignore = 'GET /' + ignore

    def filter(self, record):
        return not self.ignore in record.getMessage()

app = cherrypy.tree.mount( YourApplication() )
app.log.access_log.addFilter( IgnoreURLFilter('foo') )
cherrypy.engine.start()

rawDescription: Silencing cherrypy access log for a particular method/api/url


code:
listt3=[]

for i in listt1:
    if i in listt2:
        listt3.append(1)
    else:
        listt3.append(0)

rawDescription: Finding matching and nonmatching items in lists


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

num = 30
t = np.linspace(0, 10*np.pi, num)
x, y = np.cos(t), np.sin(t)

fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
for i in range(num):
    ax.plot([x[i]], [y[i]], [t[i]], marker='${}$'.format(i),
            markersize=12, color='black')
plt.show()

rawDescription: Pylab or mplot3d: index as marker

description: Pylab or mplot3d: index as marker


code:
if letter in word:
    print('Yes, {} is in the word'.format(letter))  # or whatever message/outcome you want
else:
    print ('Nope, not there.')

rawDescription: How would I check if a letter was in a random word?


code:
for ind in range(len(cmd_list)):
    if cmd_list[ind]=='|':
        count+=1
cmnds=[]
j=0
for i in range(len(cmd_list)):
    if cmd_list[i]=='|':
        cmnds.append(cmd_list[j:i])
        j=i+1
cmnds.append(cmd_list[j:])
pipes=[]
for i in range(count):
    pipes.append(tuple(os.pipe()))
if os.fork()==0:
   os.dup2(pipes[0][1],1)
   for k in range(count):
       for j in range(2):
           os.close(pipes[k][j])
   os.execvp(cmnds[0][0],cmnds[0])
else:
    for i in range(1,count):
        if os.fork()==0:
            os.dup2(pipes[i-1][0],0)
            os.dup2(pipes[i][1],1)
            for k in range(count):
                for j in range(2):
                    os.close(pipes[k][j])
            os.execvp(cmnds[i][0],cmnds[i])
    if os.fork()==0:
        os.dup2(pipes[-1][0],0)
        for k in range(count):
            for j in range(2):
                os.close(pipes[k][j])
        os.execvp(cmnds[-1][0],cmnds[-1])
    else:
        for k in range(count):
           for j in range(2):
               os.close(pipes[k][j])
        for i in range(count):
            os.wait()
        os.wait()

rawDescription: mutistage piping for making a toy shell for unix in python

description: Mutistage piping for making a toy shell for unix in python


rawDescription: wxPython minimal size of Frame with a Panel

description: WxPython minimal size of Frame with a Panel


code:
import wx
import time
import thread

class Frame(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self, parent, id,
                          'Show Number',
                          size = (200,150),
                          style=wx.MINIMIZE_BOX | wx.RESIZE_BORDER
    | wx.SYSTEM_MENU | wx.CAPTION |  wx.CLOSE_BOX)
        self.initUI()

    def initUI(self):

        widgetPanel=wx.Panel(self, -1)
        widgetPanel.SetBackgroundColour('white')

        # Buttons for play the simulation
        playButton = wx.Button(widgetPanel, -1, "Play", pos=(10,10), size=(30,30))

        self.Bind(wx.EVT_BUTTON, self.play, playButton)
        playButton.SetDefault()

        # Time
        self.timeText = wx.TextCtrl(widgetPanel, -1, "", pos=(10, 50),
                                size =(100,30), style=wx.TE_CENTER)
        self.timeText.SetBackgroundColour('white')
        self.timeText.SetFont(wx.Font(20, wx.DECORATIVE, wx.NORMAL, wx.NORMAL))

    def play(self, event):
        #self.timeText.SetValue("19:32")
        #self.show_num()
        thread.start_new_thread(self.show_num,())

    def show_num(self):
        x = 0
        while(x < 10):
            self.timeText.SetValue(str(x))
            time.sleep(1)
            x += 1

if __name__ == "__main__":
    app = wx.App(False)
    frame = Frame(parent=None,id=-1)
    frame.Show()
    app.MainLoop()

rawDescription: wxPython: show number repeatedly

description: WxPython: show number repeatedly


code:
try:
    # Assume you get multiline text
    lines = text.splitlines()
except AttributeError:
    # If your assumption was wrong, then you should already have a list
    lines = text

rawDescription: Elegant way to handle strings, multi-line-strings and lists in Python


code:
def Input():
    global data
    c = raw_input ('Enter data1,data2: ')
    data = c.split(',')
    return data

rawDescription: Global static variables in Python

description: Global static variables in Python


code:
import random

guessesTaken = 0
number = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')

while guessesTaken < 6:
     print('Take a guess.\n')
     guess = input()
     guess = int(guess)
     guessesTaken = guessesTaken + 1
     if guess < number:
         print('Your guess is too low.')
     if guess > number:
         print('Your guess is too high.')
     if guess == number:
        break

if guess == number:
     guessesTaken = str(guessesTaken)
     print('Good job, You guessed my number in ' + guessesTaken + ' guesses!')

if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was ' + number)

rawDescription: Number guessing game

description: Number guessing game


code:
import collections
count = collections.Counter()

# add a list
for i in listb:
    if count[i] == 0:
        all_open.append(i)
    count[i] += 1

# delete a list
for i in listb:
    count[i] -= 1
    if count[i] == 0:
        all_open.remove(i)

rawDescription: Python algorithm for lists and sublists

description: Python algorithm for lists and sublists


code:
from haystack.forms import SearchForm
from haystack.generic_views import SearchView
from haystack import indexes

class QScriptIndex(indexes.SearchIndex, indexes.Indexable):
    v = indexes.CharField(document=True)

    def get_model(self):
        return QScript

class QScriptSearchForm(SearchForm):
    text_fuzzy = forms.CharField(required=False)

    def search(self):
        sqs = super(QScriptSearchForm, self).search()

        if not self.is_valid():
            return self.no_query_found()

        text_fuzzy = self.cleaned_data.get('text_fuzzy')
        if text_fuzzy:
            sqs = sqs.filter(text__fuzzy=text_fuzzy)

        return sqs

class QScriptSearchView(SearchView):
    form_class = QScriptSearchForm

rawDescription: How to use full-text search in sqlite3 database in django?

description: Use full-text search in sqlite3 database in django


code:
b = Tix.Balloon(root)
b.subwidget('label')['image'] = Tkinter.BitmapImage()

rawDescription: How do I get rid of the arrow in a Tix.Balloon widget?

description: Get rid of the arrow in a Tix.Balloon widget


code:
if __name__ == '__main__':
    unittest.main(defaultTest='suite')

rawDescription: How to split python 3 unittests into separate file with script to control which one to run?

description: Split python 3 unittests into separate file with script to control which one to run


code:
from orbited.cometsession import Port
...
reactor.listenWith(Port, factory=someFactoryYouWrote, resource=someResourceYouWrote, childName='tcp')

rawDescription: Building a comet server from twisted.web, for a twisted.web site


code:
for f, f2 in zip(os.listdir(pth1),os.listdir(pth2)):
    df = pd.read_csv(os.path.join(pth1, f))
    df2 = pd.read_csv(os.path.join(pth2, f2))

    outpath=os.path.join(outfile, f2)

    finalmerge=pd.merge(df, df2, left_on='Year', right_on='Year', how='right')
    finalmerge.to_csv(outpath)

rawDescription: merging files from separate folders

description: Merging files from separate folders


code:
foo = r"\frac{}{}"
foo

rawDescription: How do I get LaTeX code to be stored literally in Python?

description: Get LaTeX code to be stored literally in Python


code:
w = 'ab c'
' ' in w == True
(' ' in w) == True

rawDescription: Check if space is in a string

description: Check if space is in a string


code:
def rand_data(l, h):
    return np.random.uniform(low=l, high=h, size=(100,))

# Generate data.
x1, x2, y, z = rand_data(0., 1.), rand_data(100., 175.), \
rand_data(150., 200.), rand_data(15., 33.)

fig = plt.figure(figsize=(12,6))
gs=gridspec.GridSpec(1,3, width_ratios=[4,4,0.2])
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])
ax3 = plt.subplot(gs[2])
cm = plt.cm.get_cmap('RdYlBu')
ax1.scatter(x1, y, c=z, cmap=cm)
SC=ax2.scatter(x2, y, c=z, cmap=cm)
plt.setp(ax2.get_yticklabels(), visible=False)
plt.colorbar(SC, cax=ax3)
plt.tight_layout()
plt.savefig('temp.png')

rawDescription: Force square subplots when plotting a colorbar


code:
if operation == "addition":
    Label(app, text="Addition:").pack()
    self.num1 = Entry(self)
    ...

rawDescription: Frame object in tkinter not grouping widgets in python


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

xs = np.arange(50)
ys = (np.random.random(50)*70) + 15

plt.scatter(xs,ys)

plt.axis('image')
plt.axis([0, 50, 0, 70])

plt.show()

rawDescription: matplotlib: Have axis maintaining ratio

description: Matplotlib: Have axis maintaining ratio


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

import pandas as pd

def direct():
    seen = set()
    with open("test.csv") as infile, open("formatted.csv", 'w') as outfile:
        for line in infile:
            parts = line.rstrip().split(',')
            number = parts[-1]
            if number not in seen:
                seen.add(number)
                outfile.write(line)

def using_pandas():
    """Alternatively, use Pandas"""
    df = pd.read_csv("test.csv", header=None)
    df = df.drop_duplicates(subset=[3])
    df.to_csv("formatted_pandas.csv", index=None, header=None)

def main():
    direct()
    using_pandas()

if __name__ == "__main__":
    main()

rawDescription: Reformat CSV according to certain field using python


code:
head = ET.Element('head')

properties = ET.SubElement(head, "properties", attrib={'class':"model.View$PropertyList"})

ET.tostring(head)
'<head><properties class="model.View$PropertyList" /></head>'

rawDescription: etree SubElement attribute name class fails

description: Etree SubElement attribute name class fails


code:
import requests
from bs4 import BeautifulSoup as bs

def get_login_token(raw_resp):
    soup = bs(raw_resp.text, 'lxml')
    token = [n.get('value', '') for n in soup.find_all('input')
             if n.get('name', '') == 'wpLoginToken']
    return token[0]

payload = {
    'wpName': 'my_username',
    'wpPassword': 'my_password',
    'wpLoginAttempt': 'Log in',
    #'wpLoginToken': '',
    }

with requests.session() as s:
    resp = s.get('http://en.wikipedia.org/w/index.php?title=Special:UserLogin')
    payload['wpLoginToken'] = get_login_token(resp)

    response_post = s.post('http://en.wikipedia.org/w/index.php?title=Special:UserLogin&action=submitlogin&type=login',
                           data=payload)
    response = s.get('http://en.wikipedia.org/wiki/Special:Watchlist')

rawDescription: Log in to website with python

description: Log in to website with python


code: self.assertIn('rugby', [sport_object.name for sport_object in sports_objects])

rawDescription: Lambda function to simplify unittest?

description: Lambda function to simplify unittest


code: return HttpResponse(status=204)

rawDescription: How can I return HTTP status code 204 from a Django view?

description: Return HTTP status code 204 from a Django view


code:
connection_t = ctypes.c_uint32

link = mydll.link
link.argtypes=(ctypes.c_char_p, ctypes.POINTER(connection_t) )
connect = mydll.connect
connect.argtypes=(connection_t,)
...
connection = connection_t()
link ("localhost: 5412", ctypes.byref(connection))
...

rawDescription: Python-passing object as an argument of function


code: db.collection.find({}, {'_id': False})

rawDescription: Removing _id element from Pymongo results


code:
import maya.cmds as mc

distance = 10
timedelta = 10

cube = mc.polyCube(constructionHistory=True, width=1, height=1, depth=1)
mc.setKeyframe(cube[0], time=1, v=0, at='translateZ')
mc.setKeyframe(cube[0], time=timedelta, v=10, at='translateZ')

rawDescription: Keyframe simple maya loops in python?

description: Keyframe simple maya loops in python


code:
from time import sleep

import contextlib
import sys

from tqdm import tqdm

class DummyFile(object):
  file = None
  def __init__(self, file):
    self.file = file

  def write(self, x):
    # Avoid print() second call (useless \n)
    if len(x.rstrip()) > 0:
        tqdm.write(x, file=self.file)

@contextlib.contextmanager
def nostdout():
    save_stdout = sys.stdout
    sys.stdout = DummyFile(sys.stdout)
    yield
    sys.stdout = save_stdout

def blabla():
  print("Foo blabla")

# tqdm call to sys.stdout must be done BEFORE stdout redirection
# and you need to specify sys.stdout, not sys.stderr (default)
for _ in tqdm(range(3), file=sys.stdout):
    with nostdout():
        blabla()
        sleep(.5)

print('Done!')

rawDescription: Redirect print command in python script through tqdm.write()


code:
my_functions = (
    (my_func1, [2, 5], {'kwarg1': 'val1'}),
    # ...
)

for function, args, kwargs in my_functions:
    if not function(*args, **kwargs):
        break

rawDescription: How to execute many functions one after the other

description: Execute many functions one after the other


code:
def isInLine(player, person):
    deltaX = person[0] - player[0]
    deltaY = person[1] - player[1]

    if (person[0] == player[0]) or (person[1] == player[1]) or (abs(deltaX) == abs(deltaY)):
       return true

rawDescription: Pygame Line of Sight from Fixed Position


code:
cherrypy.config.update({
  'tools.sessions.on': True
})
return cherrypy.tree.mount(Root(), '/', config=path_to_config)

rawDescription: CherryPy3 and IIS 6.0

description: CherryPy3 and IIS 6.0


code:
mod = __import__(module_name)
fn = getattr(mod, fn_name)
fn()

rawDescription: Hot swapping python code (duck type functions?)


code:
for i in range(lines):
    print("#" + " "*i + "#")

rawDescription: Patterns in Python

description: Patterns in Python


code:
f = open('report.csv', 'wb')
f.write(response_content)
f.close

rawDescription: How to iterate through JSON objects in Python and save to a CSV file?

description: Iterate through JSON objects in Python and save to a CSV file


code:
@event.listens_for(Task, "after_update")
def propagate_status(mapper, connection, target):
    obj_table = Object.__table__
    object = target.object
    if object.is_finished():
        connection.execute(
                scan_table.update().
                where(object_table.c.id == object.id).
                values(status=COMPLETED)
            )

rawDescription: Cascade updates after sqlalchemy "after_update" event


code:
import time
time.mktime(time.strptime('2015-03-25T00:00:00Z', '%Y-%m-%dT%H:%M:%SZ'))

rawDescription: How to convert string date to a epoch timestamp in python

description: Convert string date to a epoch timestamp in python


code:
import collections
data = collections.defaultdict(list)

for n, d in zip(name, date):
    data[n].append(d)

rawDescription: Method to Find Out When Users Cancelled Using Dictionaries


rawDescription: Is there a better way to specify named arguments when calling in Python


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

# activate latex text rendering
rc('text', usetex=True)

x = np.arange(10)
y = np.random.random(10)
z = np.random.random(10)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, label = r"This is \textbf{line 1}")
ax.plot(x, z, label = r"This is \textit{line 2}")
ax.legend()
plt.show()

rawDescription: Styling part of label in legend in matplotlib


code:
parser.add_argument('-t', '--type', choices=('type1', 'type2', 'type3'),
                    help='type1/type2/type3')

rawDescription: Python ArgParse

description: Python ArgParse


code:
for row in data:
    temp_string  = nltk.clean_html(str(row[0]).strip(string.digits + string.punctuation).lower() +" "+str(row[1]).strip(string.digits + string.punctuation).lower() \
    +" "+str(row[2]).strip(string.digits + string.punctuation).lower()+" "+str(row[3]).strip(string.digits + string.punctuation)).lower().split()
    temp_string     = [word for word in temp_string if word not in stopwords and len(word) >= 3]
    bigrams         = nltk.bigrams(word_tokenize(str(' '.join(temp_string))))
    all_terms_list  = temp_string + [str(bigram).replace(",","").replace("'", "").strip("()") for bigram in bigrams]
    [live_music_idx_list.append(row[4]) for word in live_music_word_list if word in all_terms_list]

rawDescription: how to return/search for documents using nltk bigrams?

description: Return/search for documents using nltk bigrams


code:
import numpy as np
num_neighbors=np.zeros_like(aa)
for i in range(1,imax-1):
    for j in range(1,jmax-1):
        num_neighbors[i,j]= np.sum(aa[i-1:i+2,j-1:j+2]) - aa[i,j]
        # you need to subtract the center , it's not a neighbor to self

rawDescription: Python matrix index out of range

description: Python matrix index out of range


code: raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

rawDescription: Convert Pandas Column to DateTime

description: Convert Pandas Column to DateTime


code:
from itertools import islice
si = iter(s)
next(islice(si, 2, 3))

rawDescription: how to call __next__ on iterators n times in python

description: Call __next__ on iterators n times in python


code:
from itertools import zip_longest
arr = [['a', 'b', 'c', 'd'], ['X', 'Y'], ['1', '2', '3']]
[''.join(x) for x in zip_longest(*arr, fillvalue='')]

rawDescription: Concatenating columns in a two-dimensional array


code:
import subprocess

#code
prog = subprocess.Popen(['python', filename, args])
#more code

rawDescription: How to run another python program without holding up original?

description: Run another python program without holding up original


code:
def cap_to_size(some_string, size_limit, encoding):
    result = ""
    for char in some_string:
        size_limit -= len(char.encode(encoding))
        if size_limit >= 0:
            result += char
        else:
            return result

rawDescription: Capping a string according to a maximum size given in bytes in Python


code:
def customfct(x,y):
    data = x / y
    return data.mean()

def f(row):
    row['m_weight'] = row['weight'].mean()
    row['var_time'] = row['Time'].var()
    row['cov'] = row['weight'].cov(row['Time'])
    row['odd_stat'] = customfct(row['weight'], row['Time'])
    return row

aggdf = df.groupby('Diet').apply(f)

rawDescription: Pandas: aggregating multiple columns with multiple functions


code:
currentDate = (time.strftime("%d/%m/%Y"))
javascript = """
$('document').ready(init);
function init(){
    $('.bar-percentage[data-percentage]').each(function () {
        var progress = $(this);
        var percentage = Math.ceil($(this).attr('data-percentage'));
        $({countNum: 0}).animate({countNum: percentage}, {
            duration: 2000,
            easing:'linear',
            step: function() {
            // What todo on every count
                var pct = '';
                if(percentage == 0){
                    pct = Math.floor(this.countNum) + '%';
                }else{
                    pct = Math.floor(this.countNum+1) + '%';
                }
            progress.text(pct) && progress.siblings().children().css('width',pct);
            }
        });
    });
};
"""

return """<html>
<head>
    <title>Fitbit</title>
    <link href="/static/css/fitbit.css" rel="stylesheet">
    <script>{0}</script>
</head>

<body>

<h4>{1}</h4>

</body>

</html>""".format(javascript, currentDate)

rawDescription: Python throwing KeyError when JQuery included


code:
import glob,subprocess
for json_file in glob.glob("/home/tmp/*.json"):
    subprocess.Popen(["python","/path/to/my.py",json_file],env=os.environ).communicate()

rawDescription: How can I write find and exec command in python

description: Write find and exec command in python


code:
import os
parent_dir = os.path.abspath(os.path.join(root_dir, ".."))

rawDescription: Walking directories

description: Walking directories


code: {{ object1.file1.read|linebreaksbr }}

rawDescription: Django, open a file in template with \n

description: Django, open a file in template with \n


code: lines = [line.split() for line in open('example.txt')]

rawDescription: Nested lists for lines in text file? (Python 3)


code:
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab # for setting up the data
import matplotlib.pyplot as plt

# set up example data:
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

levels = 10

# plot the filled contour
# using a colormap (jet)
CF = plt.contourf(Z, levels,
                  extent=(-3,3,-2,2),cmap=cm.jet)

# plot the contour lines
# using gray scale
CL = plt.contour(Z, levels,
                 linewidths=2,
                 extent=(-3,3,-2,2),cmap=cm.gray)

# plot color bars for both contours (filled and lines)
CB = plt.colorbar(CL, extend='both')
CBI = plt.colorbar(CF, orientation='horizontal')

# Plotting the second colorbar makes
# the original colorbar look a bit out of place,
# so let's improve its position.

l,b,w,h = plt.gca().get_position().bounds
ll,bb,ww,hh = CB.ax.get_position().bounds
CB.ax.set_position([ll, b, ww, h])

plt.show()

rawDescription: How to overlay a controuf plot with a differently colored contour plot?

description: Overlay a controuf plot with a differently colored contour plot


code:
import urllib2
test = {'A':'', 'B':'-B', 'XYZ': '-X-Y-Z'}
flower_list = []
for key, value in test.items():
     page = urllib2.urlopen('http://www.all-my-favourite-flower-names.com/list-of-flower-names{0}.html'.format(
value)).read()
     soup = BeautifulSoup(page)
     # Now do your logic or every page, and probably save the flower names in a list.

rawDescription: Beautiful Soup: not grabbing correct information


code:
#marking
maze[y][x] = "o"

#recursive case
if self.solve(x+1,y) == True :  #right
    maze[y][x] = ">"
    return True
if self.solve(x,y+1) == True :  #down
    maze[y][x] = "v"
    return True
...

rawDescription: Maze solving with python

description: Maze solving with python


code:
import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
    stdscr.refresh()

if __name__ == "__main__":
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()

    try:
        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
            time.sleep(0.5)
    finally:
        curses.echo()
        curses.nocbreak()
        curses.endwin()

rawDescription: Python - Rewrite multiple lines in the Console


code:
import site
reload(site)

rawDescription: How to refresh sys.path?

description: Refresh sys.path


code: post_date = post_date.strftime('%B %d')

rawDescription: Strip mysql data string with date info to display just Month and Day


code:
x = 5 # why not?
newAltAzcoordiantes = SkyCoord(alt = cAltAz.alt, az = cAltAz.az + x*u.deg, obstime = time, frame = 'altaz', location = loc)
newAltAzcoordiantes.icrs

rawDescription: How do you convert from AltAz coordinates to equatorial coordinates in Astropy

description: Convert from AltAz coordinates to equatorial coordinates in Astropy


code:
# your plot code here

def wrap_rcparams(f, params):
    def _f(*args, **kw):
        backup = {key:plt.rcParams[key] for key in params}
        plt.rcParams.update(params)
        f(*args, **kw)
        plt.rcParams.update(backup)
    return _f

plt.rcParams['mathtext.default'] = 'it'
ax1.draw = wrap_rcparams(ax1.draw, {"mathtext.default":'regular'})

# save the figure here

rawDescription: Matplotlib: Change math font size and then go back to default


code:
import numpy as np
import io

alist = [['1','a','.3'],
        ['2','b','-.5']]

f = io.BytesIO('\n'.join(' '.join(row) for row in alist))
arr = np.genfromtxt(f,dtype=None)
print(arr)
print(arr.dtype)
# [(1, 'a', 0.3) (2, 'b', -0.5)]
# [('f0', '<i4'), ('f1', '|S1'), ('f2', '<f8')]

rawDescription: automatic detection/conversion of data types?

description: Automatic detection/conversion of data types


code:
self.listA.setStyleSheet("""
    color: white;
    background-image: url(./your_image.jpg);
    background-attachment: scroll;
""");

rawDescription: How to apply an image to Widget Background (superimposing)

description: Apply an image to Widget Background (superimposing)


rawDescription: Texture mapping a curved rectangle in OpenGL [python]


code:
class MySearchView(SearchView):

    def extra_context(self):
        return { 'ordered_tasks': ... }

rawDescription: Passing the user object and a filtered object list into a custom SearchView subclass


code:
import urlparse
import urllib
x = u'http://www.odevsitesi.com/ara.asp?kelime=doğanın dengesinin bozulması'
y = x.encode('iso-8859-9')
# just to show what the split of y looks like (we can also handle it as a tuple):
urlparse.urlsplit(y)
z = urlparse.urlsplit(y)
quoted = z[:3] + (urllib.quote(z.query), z.fragment)
# now just to show you what the 'quoted' tuple looks like:
quoted
# and finally putting it back together:
urlparse.urlunsplit(quoted)

rawDescription: Convert url for crawler

description: Convert url for crawler


code:
df_datafile = pd.read_csv('data.csv')
for row, data in df_datafile.iterrows():
    data.dropna().to_frame().transpose().to_csv('file_{}.csv'.format(row))

rawDescription: Write data if it matches a criterion

description: Write data if it matches a criterion


code:
def loadComboCity(self,customerName):
    """query results cityList into self.mydb.matrix"""
    queryName="citylist_thisCustomer"
    self.mysqlAPI(queryName,customerName)

    # Clear the previous items in the combobox (if any)
    self.comboCity.clear()

    id=0
    for row in self.mydb.matrix:
        cityname=self.mydb.matrix[id][0]
        self.addcomboCity(id,cityname)
        id=id+1
    del self.mydb.matrix[:]

rawDescription: Python Hierarchical QcomboBox: clean-up list


code:
import csv
from itertools import izip_longest

def merge_rows(a, b):
    return [x or y for x,y in izip_longest(a, b, fillvalue='')]

def main():
    data = {}

    with open("infile.csv", "rb") as inf:
        incsv = csv.reader(inf, delimiter=";")
        header = next(incsv, [])
        for row in incsv:
            label = row[0]
            try:
                data[label] = merge_rows(data[label], row)
            except KeyError:
                data[label] = row

    # write data in sorted order by label
    keys = sorted(data, key=lambda k: int(k))    # Python 2
    # keys = sorted(data.keys(), key=lambda k: int(k))    # Python 3

    with open("outfile.csv", "wb") as outf:
        outcsv = csv.writer(outf, delimiter=";")
        outcsv.writerow(header)
        outcsv.writerows(data[key] for key in keys)

if __name__=="__main__":
    main()

description: Joining-all-rows-of-a-csv-file-that-have-the-same-1st-column-value


code:
from collections import defaultdict
alltags = defaultdict(set)
for word, tag in tagged_tokens:
    alltags[word].add(tag)
homographs = dict((w, tags) for w, tags in alltags.items() if len(tags) > 1)

rawDescription: How to simplify the function which finds homographs?

description: Simplify the function which finds homographs


code:
class RobsNumbers(object):
    def __init__(self, numbers, min, max):
        self._numbers = numbers
        self._min = min
        self._max = max
        self._filters = []

    def bigger(self, x):
        new_obj = RobsNumbers(self._numbers, x, self._max)
        new_obj._filters = self._filters + [GreaterThanFilter(x)]
        return new_obj

    # Other filter methods simply add a filter to the _filters list of the object

    def __iter__(self):
        # Here is the complicated optimization logic to reorder and execute the filters
        pass

rawDescription: Whats the most pythonic way to order calls to an objects methods without


code: ("\n".join(map(str, listname)))

rawDescription: List Formatting in Tkinter Text Box

description: List Formatting in Tkinter Text Box


code:
from itertools import chain
l = [0, 2, (1, 2), 5, 2, (3, 5)]
list(chain(*(i if isinstance(i, tuple) else (i,) for i in l)))

rawDescription: How to flatten a list with various data types (int, tuple)

description: Flatten a list with various data types (int, tuple)


code:
def long_running_with_more_values(start, stop):
    while start < stop:
        if stop - start < 20000:
            headers = get_headers.delay(start, stop)
            break
        else:
            headers = get_headers.delay(start, start + 20000)
            start += 20000
    insert_to_db.delay(headers)

rawDescription: Pythonic method of iterating over subsets of a range of values?


code:
import subprocess

p = subprocess.Popen('a.bat', creationflags=subprocess.CREATE_NEW_CONSOLE)

rawDescription: Python: How can I execute bat file in new cmd window?


code:
def staticAssignInBase():
    global x
    x = 'someValue'

def dynamicAssignInBase():
    g = globals()
    g['someVarName'] = 'someValue'

rawDescription: Numpy/IPython equivalent to Matlab's assignin


code:
def is_checked(self, driver, item):
  checked = driver.execute_script(("return document.getElementById('%s').checked") % item)
  return checked

rawDescription: How can I check if a checkbox is checked in Selenium Python Webdriver?

description: Check if a checkbox is checked in Selenium Python Webdriver


rawDescription: How to remove single quotes in python

description: Remove single quotes in python


code:
def fib(n):
  if n < 0:
    raise ValueError

  def fib_rec(n):
    if n == 0:
      return 0, 1
    else:
      a, b = fib_rec(n >> 1)
      c = a * ((b << 1) - a)
      d = b * b + a * a
      if n & 1:
        return d, c + d
      else:
        return c, d

  return fib_rec(n)[0]

rawDescription: Python mpmath not arbitrary precision?

description: Python mpmath not arbitrary precision


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

Nrows = 2
Ncols = 3

fig, ax = plt.subplots(Nrows, Ncols,
                       sharex=True,
                       sharey=True)
plt.subplots_adjust(hspace=0,
                    wspace=0)

for i in range(Nrows):
    for j in range(Ncols):
        if i == 0:
            ax[i,j].xaxis.set_ticks_position('top')
            plt.setp(ax[i,j].get_xticklabels(), visible=False)
        elif i == Nrows-1:
            ax[i,j].xaxis.set_ticks_position('bottom')
        else:
            ax[i,j].xaxis.set_ticks_position('none')

        if j == 0:
            ax[i,j].yaxis.set_ticks_position('left')
        elif j == Ncols-1:
            ax[i,j].yaxis.set_ticks_position('right')
            plt.setp(ax[i,j].get_yticklabels(), visible=False)
        else:
            ax[i,j].yaxis.set_ticks_position('none')

rawDescription: Hide internal tick marks and select external tick labels on matplotlib subplots?


code:
import feedparser
d = feedparser.parse("http://feedparser.org/docs/examples/atom10.xml")
d['feed']['title']             # feed data is a dictionary

rawDescription: I want to make Atom Reader with Python

description: I want to make Atom Reader with Python


code:
label, number = irTable["al"]
print("It's the {}".format(label))

rawDescription: List within a Dictionary confusion

description: List within a Dictionary confusion


rawDescription: Is there a way to leave an argument out of the help using python argparse


code:
import functools
import inspect

def ignore_extra_arguments(func):
    args, varargs, kwvarargs, defaults = inspect.getargspec(func)
    @functools.wraps(func)
    def wrapper_func(*wrapper_args, **wrapper_kwargs):
        if varargs is None:
            # remove extra positional arguments
            wrapper_args = wrapper_args[:len(args)]
        if kwvarargs is None:
            # remove extra keyword arguments
            wrapper_kwargs = {k: v for k, v in wrapper_kwargs.iteritems() if k in args}
        return func(*wrapper_args, **wrapper_kwargs)
    return wrapper_func

rawDescription: Decorator to allow function to accept arbitrary arguments


code: list_col_b, list_col_c = zip(*MyModel.objects.values_list('col_b', 'col_c'))

rawDescription: Prepairing list from a django query

description: Prepairing list from a django query


code:
class Table:
    def __init__(self, *columns, pkey = None):
        self.pkey = pkey
        self.__columns = columns
        self.__data = {}

    def __contains__(self, key):
        return key in self.__data

    def __iter__(self):
        for key in self.__order:
            yield key

    def __len__(self):
        return len(self.__data)

    def items(self):
        for key in self.__order:
            yield key, self.__data[key]

    def insert(self, *unnamed, **named):
        if len(unnamed) > 0:
            row_dict = {}
            for column_id, column in enumerate(self.__columns):
                row_dict[column] = unnamed[column_id]
        else:
            row_dict = named
        key = row_dict[self.pkey]
        self.__data[key] = row_dict

class Subtable(Table):
    def __init__(self, table, row_filter):
        self.__order = []
        self.__data = {}
        for key, row in table.items():
            if row_filter(row):
                self.__data[key] = row

rawDescription: Implementing sub-table (view into a table): designing class relationship


code:
class Node(object):
    def __init__(self, me, dists):
        super(Node,self).__init__()
        self.me = me
        self.dists = dists
        _inf = Network.INF
        self.neighbors = sorted((i for i,dist in enumerate(self.dists) if i!=me and dist!=_inf), key=dists.__getitem__)
        self.clear()

    def clear(self):
        self.dist = None
        self.prev = None

    def nearestNeighbor(self):
        try:
            return self.neighbors[0]
        except IndexError:
            return None

    def __str__(self):
        return "{0}: {1}".format(self.me, self.dists)

class Network(object):
    INF     = 10**6

    @classmethod
    def fromFile(cls, fname, delim=None):
        with open(fname) as inf:
            return cls([[int(dist) for dist in line.split(delim)] for line in inf])

    def __init__(self, distArray):
        super(Network,self).__init__()
        self.nodes = [Node(me,dists) for me,dists in enumerate(distArray)]

    def __str__(self):
        return '\n'.join(self.nodes)

    def floodFill(self, fromNode):
        _nodes = self.nodes
        for n in _nodes:
            n.clear()
        _nodes[fromNode].dist = 0
        # left as an exercise ;-)

    def distances(self):
        return [n.dist for n in self.nodes]

def main():
    nw = Network.fromFile('network.txt', delim=',')
    print(nw)

    nw.floodFill(fromNode=0)
    print(nw.distances())

if __name__=="__main__":
    main()

rawDescription: Python - Passing Function Arguments

description: Python - Passing Function Arguments


rawDescription: Sort a list of objects in python by the sum of some attributes


rawDescription: how to manually assign imagefield in Django

description: Manually assign imagefield in Django


code:
def yield_data(data):
    start = None
    end = None
    for entry in sorted(data):
        if start is None:
            start = entry[0]
        if end is None or entry[0] < end:
            end = entry[1]
        else:
            yield [start, end]
            start, end = entry
    yield [start, end]

def main():
    x = [[263, 3121], [2201, 4756], [3145, 6423], [4765, 8165], [12480, 18421],
         [18000, 24191], [26343, 28105], [27341, 28912], [29497, 30282]]
    for group in yield_data(x):
        print(group)

if __name__ == '__main__':
    main()

rawDescription: find non-overlapping blocks in a list

description: Find non-overlapping blocks in a list


code:
base_list = ['BASE: 1: another/path']
base_dict = dict()

# First map the base numbers to the paths
for entry in base_list:
    n, p = map(lambda s: s.strip(), entry.split(':')[1:])
    base_dict[n] = p

source_list = ['SOURCE:  filename.dc : 1 : a/path/: description']

# Loop over all source entries and replace the number with the base path of the numbers match
for i, entry in enumerate(source_list):
    n = entry.split(':')[2].strip()
    if n in base_dict:
        new_entry = entry.split(':')
        new_entry[2] = base_dict[n]
        source_list[i] = ':'.join(new_entry)

rawDescription: Python: Replace elements of one list with those of another if condition is met


code:
import Barra
import multiprocessing

def threadCAN(posQu):
    while True:
        canMsg = Barra.ricevi("can0")
        if canMsg[0] == 'ERR':
            print(canMsg)
        else:
            print("Enqueued message", canMsg)
            posQu.put(canMsg)

if __name__ == "__main__":
    posQu = multiprocessing.Queue(maxsize=0)
    procCan = multiprocessing.Process(target=threadCAN, args=(posQu,))
    procCan.daemon = True
    procCan.start()

    while True:
        posMsg = posQu.get()
        print("Messagge from the queue", posMsg)

rawDescription: Python threading with queue: how to avoid to use join?


code:
new_msg = []
msg = msg.split()
for word in msg: #For every word in the string
    if not word[0].islower(): #if it starts with anything other than lowercase
        new_msg.append(word.lower()) #add to new list
new_msg = ' '.join(new_msg[::-1]) #Reverse order of list and make into string

rawDescription: How to delete lower case from a list and reverse it

description: Delete lower case from a list and reverse it


code:
def dist(n1, n2):
    x = n2[0]-n1[0]
    y = n2[1]-n1[1]
    return math.sqrt(x*x + y*y)   # or math.hypot(x, y)

distances = {}
for node in G.nodes():
    list_of_neigh = G.neighbors(node)
    distances[node] = [dist(node, x) for x in list_of_neigh]

rawDescription: Python: how do I create a dict of lists containing the euclidean distances from a point?


code:
styles = getSampleStyleSheet()
text = Paragraph("long line",
              styles['Normal'])

rawDescription: Word wrap on report lab PDF table

description: Word wrap on report lab PDF table


code:
from ctypes import *
from binascii import hexlify

kernel32 = windll.kernel32
user32 = windll.user32

user32.OpenClipboard(0)

CF_SPARK = user32.RegisterClipboardFormatW("application/spark editor")

if user32.IsClipboardFormatAvailable(CF_SPARK):
    data = user32.GetClipboardData(CF_SPARK)
    size = kernel32.GlobalSize(data)
    data_locked = kernel32.GlobalLock(data)
    text = string_at(data_locked,size)
    kernel32.GlobalUnlock(data)
else:
    print('No spark data in clipboard!')
user32.CloseClipboard()

rawDescription: Read binary data off Windows clipboard, in Blender (python)


code:
name = raw_input("What is your name?")
file = open(name+".txt", "w")
...
file.close()

rawDescription: How do I take Someone's name in Python and create a file to write to with that name?

description: Take Someone's name in Python and create a file to write to with that name


code:
strings = [ 'The cat sat on the mat',           # documents to process
            'The fox jumped over the dog' ]
docstream = []                                  # document indices
wordstream = []                                 # token indices
words = []                                      # tokens themselves

# Return an array of words in the given string. NOTE: this splits up by
# spaces, in real life you might want to split by multiple spaces, newlines,
# tabs, what you have. See regular expressions in the module 're' and
# 're.split(...)'
def tokenize(s):
    return s.split(' ')

# Lookup a token in the wordstream. If not present (yet), append it to the
# wordstream and return the new position. NOTE: in real life you might want
# to fold cases so that 'The' and 'the' are treated the same.
def lookup_token(token):
    for i in range(len(words)):
        if words[i] == token:
            print('Found', token, 'at index', i)
            return i
    words.append(token)
    print('Appended', token, 'at index', len(words) - 1)
    return len(words) - 1

# Main starts here
for stringindex in range(len(strings)):
    print('Analyzing string:', strings[stringindex])
    tokens = tokenize(strings[stringindex])
    for t in tokens:
        print('Analyzing token', t, 'from string', stringindex)
        docstream.append(stringindex)
        wordstream.append(lookup_token(t))

# Done.
print(wordstream)
print(docstream)

rawDescription: How do I create a 'word stream' and 'document stream' in Python?

description: Create a 'word stream' and 'document stream' in Python


code:
class UserFactory(factory.alchemy.SQLAlchemyModelFactory):
    class Meta:
        model = User
        sqlalchemy_session = db.session

    # No need to force the user_pk, it is built automatically from the database
    # user_pk = Sequence(lambda n: n)
    name = Sequence(lambda n: u'User %d' % n)  # coding=utf-8
    group_fk = factory.SubFactory(GroupFactory)

rawDescription: How do I setup dependent factories using Factory Boy and Flask-SQLAlchemy?

description: Setup dependent factories using Factory Boy and Flask-SQLAlchemy


code:
import win32com.client

xl = win32com.client.Dispatch("Excel.Application")
xl.DisplayAlerts = False
wb = xl.Workbooks.Open(r"C:\PATH\TO\SOURCE_FILENAME.XLSX")
wb.SaveAs(r"C:\PATH\TO\DESTINATION_FILENAME.XLS", FileFormat = 56)
wb.Close()
xl.Quit()

rawDescription: xlrd library not working with xlsx files.any way to covert xlsx to xls using python?

description: Xlrd library not working with xlsx files.any way to covert xlsx to xls using python


code:
order=['one','two','three','foo']
ordered_dict = OrderedDict((k, original_dict[k]) for k in order)

rawDescription: create an ordered dict

description: Create an ordered dict


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

x = np.linspace(0, 2*np.pi, 10)
y = np.sin(x)

plt.figure()
plt.quiver(x[:-1], y[:-1], x[1:]-x[:-1], y[1:]-y[:-1], scale_units='xy', angles='xy', scale=1)

plt.show()

rawDescription: Line plot with arrows in matplotlib

description: Line plot with arrows in matplotlib


code:
def test_explicit():
    # specify all children tables to be queried
    Sources = [SourceA, SourceB, SourceC]
    AllSources = with_polymorphic(Source, Sources)

    name_col = func.coalesce(*(_s.name for _s in Sources)).label("name")
    query = session.query(AllSources).order_by(name_col)
    for x in query:
        print(x)

def test_implicit():
    # get all children tables in the query
    from sqlalchemy.orm import class_mapper
    _map = class_mapper(Source)
    Sources = [_smap.class_
               for _smap in _map.self_and_descendants
               if _smap != _map  # @note: exclude base class, it has no `name`
               ]
    AllSources = with_polymorphic(Source, Sources)

    name_col = func.coalesce(*(_s.name for _s in Sources)).label("name")
    query = session.query(AllSources).order_by(name_col)
    for x in query:
        print(x)

rawDescription: sqlalchemy join and order by on multiple tables

description: Sqlalchemy join and order by on multiple tables


code:
from math import sqrt
from fractions import Fraction
a, b, c = 5, -13, 6
disc = b * b - 4 * a * c
s1 = Fraction(((-b + sqrt(disc))/(2*a)))
s2 = Fraction(((-b - sqrt(disc))/(2*a)))
print (s1, s2)
s1, s2 = s1.limit_denominator (), s2.limit_denominator ()
print (s1, s2)

rawDescription: The number 0.6 is not converting to a fraction correctly


code:
for root, dirs, files in os.walk(stpath):
    d = {} # intialize dict
    for fn in files:
        path = os.path.join(root, fn)
        size = os.stat(path).st_size
        # capture file name and size for files in root
        d[fn] = size
    # some folders may be empty
    if d:
        # get the file name of the file with the smallest size
        smallestfile = min(d, key=d.get)
        print(root, smallestfile, d[smallestfile])

rawDescription: How I can delete a file in a folder which is smaller in size using python


code: self.input.__iter__.return_value = iter(["5 5 N", "LRMR"])

rawDescription: Mocking itertools.zip_longest

description: Mocking itertools.zip_longest


code: any(l_value in l2_value for l_value in l for l2_value in l2)

rawDescription: How to check of the existence of any value in the list in python

description: Check of the existence of any value in the list in python


rawDescription: How to efficiently expanding arrays in python?

description: Efficiently expanding arrays in python


code:
df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
df
df.iloc[0]  # first row in a DataFrame
df['A'].iloc[0]  # first item in a Series (Column)

rawDescription: Get first element of Series without have information on index


code:
from lxml import etree
parser = etree.HTMLParser()
tree   = etree.parse(StringIO(reviews.text), parser)
result = etree.tostring(tree.getroot(),
                        pretty_print=True, method="html")
print(result)

rawDescription: how to extract reviews from iframeurl returned by amazon api in python?

description: Extract reviews from iframeurl returned by amazon api in python


code: ', '.join(str(_) for _ in x)

rawDescription: Join integers to a comma seperated string the pythonic way


code:
def addToList(self, str_to_add):
    if str_to_add not in self.list_of_strings:
        self.list_of_strings.append(str_to_add)

rawDescription: How to ensure list contains unique elements?

description: Ensure list contains unique elements


rawDescription: Problems with using re.findall() in python


code:
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.contrib.auth.models import User

class UserAdmin(DjangoUserAdmin):
    list_display = ('email', 'first_name', 'last_name','is_active','date_joined', 'is_staff', 'user_type', 'salary')

    def user_type(self, instance):
        try:
            instance.student
            return "student"
        except Student.DoesNotExist:
            return "professor"

    def salary(self, instance):
        try:
            return instance.professor.salary
        except Professor.DoesNotExist:
            return "N/A"

    def queryset(self, request):
        qs = super(UserAdmin, self).queryset(request)
        # To reduce database calls
        return qs.select_related('student', 'professor')

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

rawDescription: django admin site view one to one classes fields

description: Django admin site view one to one classes fields


rawDescription: Counting occurrences of columns in numpy array


code:
pd.DataFrame([{'col_A':row['col_A'], 'col_B':val}
               for ind, row in df.iterrows()
               for val in row['col_B']])

rawDescription: how to convert a data frame with a list in the value to a big data frame with the each level as a single column value in python?

description: Convert a data frame with a list in the value to a big data frame with the each level as a single column value in python


code:
class ObstaclesGroup(pygame.sprite.Group):
    def update(self, offset):

        # function that returns the x-position of a sprite
        def xPos(sprite):
            return sprite.rect.x

        # find the rightmost sprite
        lastSprite = max(self.sprites(), key=xPos)
        if xPos(lastSprite) < distance + 640:
            # add obstacle with a distance of at least 300 px to the previous
            self.add(Obstacle(distance + 940))

rawDescription: Last item of list does not change after adding


code:
def __exit__(self, *args):
    if not self._closed:
        self.close()

rawDescription: does socket __exit__ close in python?

description: Does socket __exit__ close in python


rawDescription: Ignore case in glob() on Linux

description: Ignore case in glob() on Linux


code:
import itertools

def isa_group_separator(line):
    return line=='\n'

with open('data_file') as f:
    for key,group in itertools.groupby(f,isa_group_separator):
        # print(key,list(group))  # uncomment to see what itertools.groupby does.
        if not key:
            data={}
            for item in group:
                field,value=item.split(':')
                value=value.strip()
                data[field]=value
            print('{FamilyN} {Name} {Age}'.format(**data))

# Y X 20
# F H 23
# Y S 13
# Z M 25

rawDescription: Python: How to loop through blocks of lines


code:
from matplotlib import pyplot
import numpy as np

#sample data:
x = np.arange(30)
y = np.cumsum(np.arange(30))
#offset the x for horizontal, repeat the y for vertical:
x = np.ravel(zip(x,x+1))
y = np.ravel(zip(y,y))

pyplot.plot(x,y)
pyplot.savefig('plt.png')

rawDescription: Matplotlib - Stepped histogram with already binned data


code:
import json

with open('my_dict.json', 'w') as f:
    json.dump(my_dict, f)

# elsewhere...

with open('my_dict.json') as f:
    my_dict = json.load(f)

rawDescription: Elegant way to store dictionary permanently with Python?


code:
if primary:
    axis.xaxis.set_major_formatter(DateFormatter(fmt='%b %y'))
    axis.xaxis.set_minor_formatter(DateFormatter(fmt='%b'))
    plt.setp(axis.get_xticklabels(minor=True), visible=True)
else:
    plt.setp(axis.get_xticklabels(), visible=False)

rawDescription: matplotlib: showing minor tick labels on primary x axis only

description: Matplotlib: showing minor tick labels on primary x axis only


code:
import urllib2
import json

#The URL where we get our array of LA data
GET_LAS = 'http://www.education.gov.uk/cgi-bin/schools/performance/getareas.pl?level=la&code=0'

#The URL which we interpolate the LA ID into to get individual pages
GET_URL = 'http://www.education.gov.uk/schools/performance/geo/la%s_all.html'

def get_performance(la):
    page = urllib2.urlopen(GET_URL % la)
    #print(page.read())

#get the local authority list
las = json.loads(urllib2.urlopen(GET_LAS).read())

for la in las:
    if la != 0:
        print('Processing LA ID #%s (%s)' % (la[0], la[1]))
        get_performance(la[0])

rawDescription: Use Mechanize with select field that is not inside a form?


code:
import numpy as np
a = np.random.randint(0,100,size=50)
np.unique(a)
np.diff(np.unique(a))
np.diff(np.unique(a)).min()

rawDescription: Minimum difference between non-equal elements in integer array


code:
def get_geodatabase_path(input_table):
  '''Return the Geodatabase path from the input table or feature class.
  :param input_table: path to the input table or feature class
  '''
  workspace = os.path.dirname(input_table)
  if [any(ext) for ext in ('.gdb', '.mdb', '.sde') if ext in os.path.splitext(workspace)]:
    return workspace
  else:
    return os.path.dirname(workspace)

rawDescription: arcpy get database path of feature class in feature dataset

description: Arcpy get database path of feature class in feature dataset


code: [[s, c] for s, c in this_amino if s == min_score]

rawDescription: Truncate sorted list of list based on value


code:
import cPickle

class Blubb(object):

    def __init__(self, value, foo=None, bar=None):
        self.value = value
        self.foo = foo
        self.bar = bar

def _new_Bla(cls, value, kw):
    "A function to map kwargs into cls.__new__"
    return cls.__new__(cls, value, **kw)

class Bla(Blubb):

    def __new__(cls, value, **kw):
        instance = super(Bla, cls).__new__(cls)
        instance.__init__(value, **kw)
        return instance

    def __reduce__(self):
        kwargs = {'foo': self.foo, 'bar': self.bar}
        return _new_Bla, (self.__class__, self.value, kwargs), None

x = Bla(2, bar=[1, 2, 3])
pickled = cPickle.dumps(x, 2)
y = cPickle.loads(pickled)
assert y.value == 2
assert y.bar == [1, 2, 3]

rawDescription: Unpickling new-style with kwargs not possible?


code:
import zope.interface
class IFoo(zope.interface.Interface):
    pass

class Foo(object):
    zope.interface.implements(IFoo)
    pass

foo = Foo()
IFoo(foo)
IFoo.providedBy(foo)

rawDescription: Zope component discrepancy between Interface(obj) and getAdapter(obj, Interface)


code:
from __future__ import print_function
import subprocess
from time import sleep

f = open('test.log', 'r')
while True:
    line = ''
    while len(line) == 0 or line[-1] != '\n':
        tail = f.readline()
        if tail == '':
            continue
        line = tail

    print(line, end='')

rawDescription: Processing realtime output of access_log with subprocess


code:
# start redis_call in a background greenlet
g = gevent.spawn(redis_call)

# wait for up to 90 seconds for redis_call to complete
g.join(90)

# if g has finished, kill() is a no-op
# if g is still running, kill() will interrupt it (by raising GreenletExit in it)
# by default, kill() waits for greenlet to exit (which might never happen,
# if redis_call caught GreenletExit and ignored it). You can also do g.kill(block=False) to
# avoid waiting for killing to complete
g.kill()

rawDescription: uWSGI, gevent, a few redis calls and how to timeout a post if greater than 90 ms

description: UWSGI, gevent, a few redis calls and how to timeout a post if greater than 90 ms


rawDescription: Setting attributes in constructor for Django model


code:
str_list = str1.split()
num = len(str_list)
all_lines = [str_list[i:i+14] for i in range(0, num, 14)]
all_lines = [" ".join(line)+"\n" for line in all_lines]
fp = open("outfile.txt", 'w')
fp.writelines(all_lines)
fp.close()

rawDescription: Insert a newline character every 14 numbers using Python


code:
f = figure(facecolor='red')
ax = f.add_subplot(111)
ax.set_axis_bgcolor('black')
ya = ax.yaxis
xa = ax.xaxis                           # you modify x ticks indepently
ya.set_tick_params(labelcolor='green')  # label
ya.set_tick_params(color='white')       # ticks

rawDescription: MATPLOTLIB X-AXIS AND Y-AXIX tick background and font color


code:
import sys
import os

import comtypes.client

working_dir = os.getcwd()
#in_file = os.path.abspath(working_dir  + '/Check/')
#out_file = os.path.abspath(working_dir  + '/modred')
out_file = os.path.abspath('modred')

word = comtypes.client.CreateObject('Word.Application')
#doc = word.Documents.Open('nored.doc')
doc = word.Documents.Open(working_dir  + '/nored.doc')
doc.SaveAs(out_file, FileFormat=16)
doc.Close()
word.Quit()

rawDescription: Change path of input file , comtypes

description: Change path of input file , comtypes


code:
import turtle
class TurtleGTX(turtle.Turtle):
    """My own version of turtle"""
    def __init__(self,*args,**kwargs):
        super(TurtleGTX,self).__init__(*args,**kwargs)
        print("Time for my GTX turtle!")

my_turtle = TurtleGTX()
my_turtle.forward(100)

rawDescription: How to create a subclass in python that is inherited from turtle Module

description: Create a subclass in python that is inherited from turtle Module


code:
class A(object):
    def fun(self, arg):
        return None
    fun = memoized(fun)

rawDescription: Do overridden methods inherit decorators in python?


code: df['Week'] = df['Date'].apply(week)

rawDescription: Pandas dynamic date time week start

description: Pandas dynamic date time week start


rawDescription: Python Find distance between two coordinates


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

import sys, inspect

def create_niestr(obj,
                  abstract_class,
                  methode):
    classname = obj.__class__.__name__
    hi = inspect.getmro(obj.__class__)
    this_method = getattr(obj, methode)
    base_method = getattr(abstract_class, methode)

    if classname is not abstract_class.__name__ and this_method.__func__ is base_method:
        nistr = 'Please implement {}.{}(). See the documentation of {}.{}() for more details.' \
                .format(classname, methode, hi[1].__name__, methode)
    else:
        nistr = 'Normal execution.'

    return nistr

class Foo:
    def test(self):
        nistr = create_niestr(self,
                              Foo,
                              sys._getframe().f_code.co_name)
        print(nistr)

class Xoo(Foo):
    pass

class Zoo(Foo):
    def test(self):
        super(self.__class__, self).test()

Foo().test()
Xoo().test()
Zoo().test()

rawDescription: Get name of the current method, the class-name of the current instance, the class-name of the next sub-instance in a reusable way with Python3?


code:
file_name = 'YOUR_FILE_NAME.txt' #Put here your file

with open(file_name,'r') as fnr:
    text = fnr.readlines()

text = "".join([line.strip() + ': [word]\n' for line in text])

with open(file_name,'w') as fnw:
    fnw.write(text)

rawDescription: Append text in every line of txt in Python


code:
from django.contrib import admin
from django.contrib.admin import widgets
from django.contrib.admin.sites import site
from django import forms

class BlogRawIdWidget(widgets.ForeignKeyRawIdWidget):
    def url_parameters(self):
        res = super().url_parameters()
        res['type__exact'] = 'PROJ'
        return res

class ProjectAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['blog'].queryset = Blog.objects.filter(type='PROJ')
        self.fields['blog'].widget = BlogRawIdWidget(rel=Project._meta.get_field('blog').rel, admin_site=site)

    class Meta:
        # Django 1.8 convenience:
        fields = '__all__'
        model = Project

class ProjectAdmin(admin.ModelAdmin):
    form = ProjectAdminForm
    raw_id_fields = ('blog',)

rawDescription: How to limit choices of ForeignKey choices for Django raw_id_field

description: Limit choices of ForeignKey choices for Django raw_id_field


code:
# mylogger.py
from twisted.python import log

def logger():
    return log.PythonLoggingObserver().emit

rawDescription: How to set twistd.py ILogObserver when using IPlugin?

description: Set twistd.py ILogObserver when using IPlugin


code:
import Tkinter

class mainWindow(Tkinter.Frame):
    def __init__(self, parent):
        Tkinter.Frame.__init__(self, master=parent)
        self.parent=parent
        self.button1=Tkinter.Button(master=self, text='ONE', command=self.change)
        self.button1.pack()
        self.pack(fill=Tkinter.BOTH, expand=True)

    def change(self):
        self.parent.wm_title("Changed")
        self.configure(background="yellow")

root = Tkinter.Tk()
root.geometry("600x600+50+50")
app=mainWindow(root)
root.mainloop()

rawDescription: Unable to change frame color once created


rawDescription: How to query all the elements with this condition in the query?

description: Query all the elements with this condition in the query


code:
class MyModelForm(forms.ModelForm):
    class Meta:
        model = FormData
        fields = ['text_area','email','full_name', 'check_boxes', 'radio_buttons']
        widgets = {
            'text_area': Textarea(attrs={'cols': 50, 'rows': 10}),
        }
    TYPE_CHOICES = [('s', 'small'),('m', 'medium'),('b', 'big')]
    check_boxes = forms.MultipleChoiceField(choices=TYPE_CHOICES, widget=forms.CheckboxSelectMultiple())

    CHOICES = [(1, 'One'),(2, 'Two'),(3, 'Three'),(4, 'Four')]
    radio_buttons = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())

rawDescription: Unable to save the data from checkboxes and radiobuttons using modelForm


rawDescription: How to get “qualification_type_id” when using Boto API for Mturk

description: Get “qualification_type_id” when using Boto API for Mturk


code:
start = datetime.combine(date.today(), time(0, 0))
axis_times = []
y_values = []
i = 0
while i<9:
    start += timedelta(seconds=7)
    axis_times.append(start.strftime("%M:%S"))
    y_values.append(i)
    i+=1

fig, ax = plt.subplots()
ax.scatter(range(len(axis_times)), y_values, c='red', s=80)
ax.scatter(range(len(axis_times)), y_values, c='blue', s=20)

plt.legend(['INT', 'EXT'], loc=4)
plt.xlabel('Distance')
plt.xticks(range(len(axis_times)), axis_times, size='small')

plt.show()

rawDescription: Changing axis on scatterplot to fixed intervals involving time


code:
query = (
    session.query(File)
    .join(File.tags)
    .filter(Tag.tag.in_(search_tags))
    .group_by(File)
    .having(func.count(distinct(Tag.id)) == len(search_tags))
)

rawDescription: SQLAlachmey: ORM filter to match all items in a list, not any


code:
Example
x = np.array([1,2,3,4,5])
y1 = np.arange(5)
y2 = y1 * 2
y3 = y1 * 5

fig = plt.figure()
ax1 = fig.add_subplot(131)
ax1.plot(x, y1)
ax2 = fig.add_subplot(132, sharey=ax1)
ax2.plot(x, y2)
ax3 = fig.add_subplot(133) # No sharey!!!
ax3.plot(x, y3)
plt.show()

rawDescription: Is there any way to share Y axis among only part of subplots in matplotlib?


code:
def auto_sort(request):
    sort_by = request.GET.get('sort_by', None)
    if sort_by:
        temp_path = "{0}/file.txt".format(settings.SITE_ROOT)
        #Set new_text to whatever you want based on your logic
        new_text = 'custom'
        f=open(temp_path,'w')
        f.write(new_text)
        f.close();

        handle=open(temp_path,'w+')
        handle.write(sort_by)
        handle.close();

    return HttpResponseRedirect(reverse('envelopes:editor'))

rawDescription: How to overwrite a file in Python?

description: Overwrite a file in Python


code:
graph = { "a" : ["c"],
          "b" : ["c", "e"],
          "c" : ["a", "b", "d", "e"],
          "d" : ["c"],
          "e" : ["c", "b"],
          "f" : [] }

def max_length(x):
    return len(graph[x])

# Determine what index has the longest value
index = max(graph, key=max_length)
m = len(graph[index])

# Fill the list with `m` zeroes
out = [0 for x in range(m+1)]

for k in graph:
    l = len(graph[k])
    out[l]+=1

print(out)

rawDescription: Finding the degree of an undirected graph


code:
from __future__ import division
def f(n):
  v = n // 5
  q = v // 20
  r = v % 20
  return sum(binomial(q+5-j, 5) * a[r+20*j] for j in range(5))

rawDescription: Mathematica to Python

description: Mathematica to Python


code:
class Pixel:
    def  __init__(self):
        self.bounds = np.loadtxt('bnds.data')
        self.rho = np.loadtxt('densities.data')

    def get_density(self, phi, theta):
        return Density(self, phi, theta)

pixel = Pixel()
rho = pixel.get_density(10,20) # phi = 10, theta = 20
rho.print_rho()

rawDescription: Accessing variables from one class to another in Python


code:
os.chdir( 'c:\\Users\\Hidraulica\\Desktop\\w2furnas' )
os.system( '"C:\\Users\\Hidraulica\\Desktop\\w2furnas\\w2.exe"' )
shutil.move('tsr_1_seg6.opt', 'tsr_1_seg6.txt')

data = np.genfromtxt('c:\\Users\\Hidraulica\\Desktop\\w2furnas\\tsr_1_seg6.txt', skip_header=11, names=True)
trib = np.genfromtxt('c:\\Users\\Hidraulica\\Desktop\\w2furnas\\ctr_tr3.npt', skip_header=2, names=True)

trib['P04'] = data['P04']*0.75

with open('c:\\Users\\Hidraulica\\Desktop\\w2furnas\\ctr_tr3.npt', 'r') as f:
    h = ''.join(f.readline() for i in range(2))

with open('c:\\Users\\Hidraulica\\Desktop\\w2furnas\\ctr_tr3.npt', 'w') as f:
    # first write header from before:
    f.write(h)
    # names from dtype plus newline:
    f.write(' '.join(trib.dtype.names) + '\n')
    # then data, separated with newlines:
    f.write('\n'.join([' '.join(map(str,i)) for i in a]))

rawDescription: How can I save values in a text file?

description: Save values in a text file


code:
#!/usr/bin/python

import paho.mqtt.client as paho
import os
import socket
import ssl
from time import sleep
from random import uniform

connflag = False

def on_connect(client, userdata, flags, rc):
   global connflag
   connflag = True
   print("Connection returned result: " + str(rc))

mqttc = paho.Client()
mqttc.on_connect = on_connect

awshost = "YOURAWSHOST.iot.us-west-2.amazonaws.com"
awsport = 8883
caPath = "root-CA.crt"
certPath = "YOURCERT.pem.crt"
keyPath = "YOURKEY.pem.key"

mqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)

mqttc.connect(awshost, awsport, keepalive=60)

mqttc.loop_start()
while 1==1:
   sleep(0.5)
   f = open('mybinaryfile')
   imagestring = bytearray(f.read())
   f.close()

   message = '"image": { "bytearray": "' + imagestring + '"} } '
   mqttc.publish("$aws/things/rpi/shadow/update", message, qos=1)

rawDescription: How Can I Publish File to AWS- IoT using Mosquitto in Python


code:
class WrappedBox(object):
    def __init__(self, title, message, wraplength=60):
        self.title = title
        self.message = message
        self.wraplength = wraplength

        self.messageWrapped = '\n'.join([self.message[i:i+self.wraplength] for i in xrange(0,len(self.message),self.wraplength)])

        tkMessageBox.showinfo(self.title, self.messageWrapped)

WrappedBox("Results", str(e), wraplength=30)

rawDescription: Tkinter Limit Size Of Popup per line

description: Tkinter Limit Size Of Popup per line


code:
import datetime
today_string = datetime.datetime.today().strftime('%x')

with open('C:/A/B/C/D/TODAYS SHEET' + today_string + '.csv', 'w') as my_file:
    my_file.write('a,a,a,a,a,a')

rawDescription: Open a file name +date as csv in Python

description: Open a file name +date as csv in Python


code:
def randfile():
  return random.sample([gammurc1_path, gammurc2_path], 1) [0]

rawDescription: Gammu how to load balance between two modems


code:
import threading.Thread

class Line_Counter(threading.Thread):
    def __init__(self, staticText, filename):
        threading.Thread.__init__(self)
        self.staticText = staticText

    def run(self):
        self.exit = False
        with open(self.filename) as f:
            if self.exit:
                return
            for count, _ in enumerate(f):   pass
        self.staticText.SetLabel(str(count + 1))

    def abort(self):
        self.exit = True

class MainFrame(wx.Frame):
    def __init__(self, parent, id, filename):
        wx.Frame.__init__(self, parent, id, 'Threaded File Loader')
        self.line_counter = False      # Set up a dummy thread variable
        #### remaining code
        self.file_open_button.Bind( wx.EVT_BUTTON, self.OnOpenFile ) # Event handler for opening file

    def OnOpenFile(self, event):
        filepath = getFile()  # Creates a file open dialog and returns the file path
        if self.line_counter: # Checks if a counter thread is already running
            self.line_counter.abort() # Stops the thread if True
        self.line_counter = Line_Counter(self.staticText, filename).start()  # Starts a new thread

rawDescription: Using multiple threads with wxPython

description: Using multiple threads with wxPython


code:
def go_to_next_day(driver, next_date):
    wait = WebDriverWait(driver, 10)
    actions = ActionChains(driver)
    try:
        next_button = wait.until(ec.element_to_be_clickable((By.CSS_SELECTOR, '.date-selector i[class*=right]')))
        actions.move_to_element(next_button).click().perform()
    except TimeoutException:
        raise ValueError('Unable to navigate to the next day')

    # THIS IS THE KEY FIX
    wait.until(ec.invisibility_of_element_located((By.CSS_SELECTOR, "div.loader")))

    # wait until the next day loads
    wait.until(
        ec.text_to_be_present_in_element((By.CSS_SELECTOR, '.date-selector > span'), next_date.strftime('%m/%d/%Y'))
    )

rawDescription: Selenium click does not trigger event on website (python)


code:
def sub_func(match):
    text = match.group(1)
    return "t"*text.count("t") + "s"*text.count("s")

re.sub(r'(s[st]*t)', sub_func, text)

rawDescription: str.replace() or re.sub() continually until substring no longer present

description: Str.replace() or re.sub() continually until substring no longer present


code:
class SomeClass:
  @classmethod
  def some_class_method(cls):
    pass

  @staticmethod
  def some_static_method():
    pass

SomeClass.some_class_method()
SomeClass.some_static_method()

rawDescription: Python static methods - how to call a method from another method


code:
def character_count(filename):
    with open(filename) as f:
        return sum(len(line.rstrip("\n")) for line in f)

rawDescription: How do you count number of characters from each lines then add them all up?

description: Count number of characters from each lines then add them all up


code:
fig = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(10), 'b')

# create a PdfPages object
pdf = PdfPages(pdffilepath)

# save plot using savefig() method of pdf object
pdf.savefig(fig)

fig1 = plt.figure()
ax = fig_zoom.add_subplot(111)
ax.plot(range(10), range(2, 12), 'r')

pdf.savefig(fig1)

# remember to close the object to ensure writing multiple plots
pdf.close()

rawDescription: is it possible to append figures to Matplotlib's PdfPages?

description: Is it possible to append figures to Matplotlib's PdfPages


code:
import xml.etree.ElementTree as ET

et = ET.parse('xml/test.xml')

for child in et.getroot():
    for core in child:
        core_value = str(core.text)
        core.text = core_value.decode('unicode-escape')

et.write('output.xml')

rawDescription: How to iterate through all XML Elements and apply logic to each Element's value with ElementTree for Python

description: Iterate through all XML Elements and apply logic to each Element's value with ElementTree for Python


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

def col_plot(data):

    xarr, yarr, zarr = zip(*data)[0], zip(*data)[1], zip(*data)[2]
    xarr = [2*x for x in xarr]

    xmin, xmax = min(xarr), max(xarr)
    ymin, ymax = min(yarr), max(yarr)

    fig = plt.figure()

    ax0 = fig.add_subplot(111, aspect='equal')

    plt.xlim(xmin, xmax)
    plt.ylim(ymin, ymax)
    plt.xlabel('$x axis$', fontsize=20)
    plt.ylabel('$y axis$', fontsize=20)
    # Scatter plot.
    cm = plt.cm.get_cmap('RdYlBu_r')
    SC = ax0.scatter(xarr, yarr, marker='o', c=zarr, s=60, lw=0.25, cmap=cm,
        zorder=3)

    the_divider = make_axes_locatable(ax0)
    color_axis = the_divider.append_axes("right", size="5%", pad=0.1)

    # Colorbar.
    cbar = plt.colorbar(SC, cax=color_axis)
    cbar.set_label('$col bar$', fontsize=21, labelpad=-2)

# Generate data.
data0 = np.random.uniform(0., 1., size=(20, 3))

col_plot(data0)

rawDescription: Set equal aspect in plot with colorbar

description: Set equal aspect in plot with colorbar


code:
def running_sum(a):
  tot = 0
  for item in a:
    tot += item
    yield tot

rawDescription: List comprehension for running total

description: List comprehension for running total


code:
class ThumbListWidget(QtGui.QListWidget):
    _drag_info = []

    def __init__(self, type, name, parent=None):
        super(ThumbListWidget, self).__init__(parent)
        self.setObjectName(name)
        ...

    def startDrag(self, actions):
        self._drag_info[:] = [str(self.objectName())]
        for item in self.selectedItems():
            self._drag_info.append(self.row(item))
        super(ThumbListWidget, self).startDrag(actions)

    def dropEvent(self, event):
        if event.mimeData().hasUrls():
            ...
        elif self._drag_info:
            event.setDropAction(QtCore.Qt.MoveAction)
            super(ThumbListWidget, self).dropEvent(event)
            self.emit(QtCore.SIGNAL("dropped"), list(self._drag_info))

    ...

    self.listWidgetA = ThumbListWidget(self, 'A')
    self.listWidgetB = ThumbListWidget(self, 'B')

rawDescription: Python: How to track ListItems that were drag and droped from one ListWidget onto another with PyQt


code:
def architectural_to_float(text):
    ''' Convert architectural measurements to inches.

        >>> for text in """15-3/4",12' 6-3/4",3/4",3/4',15',15",15.5'""".split(','):
        ...     print text.ljust(10), '-->', architectural_to_float(text)
        ...
        15-3/4"    --> 15.75
        12' 6-3/4" --> 150.75
        3/4"       --> 0.75
        3/4'       --> 9.0
        15'        --> 180.0
        15"        --> 15.0
        15.5'      --> 186.0

    '''
    # See http://stackoverflow.com/questions/8675714
    text = text.replace('"', '').replace(' ', '')
    feet, sep, inches = text.rpartition("'")
    floatfeet, sep, fracfeet = feet.rpartition('-')
    feetnum, sep, feetdenom = fracfeet.partition('/')
    feet = float(floatfeet or 0) + float(feetnum or 0) / float(feetdenom or 1)
    floatinches, sep, fracinches = inches.rpartition('-')
    inchesnum, sep, inchesdenom = fracinches.partition('/')
    inches = float(floatinches or 0) + float(inchesnum or 0) / float(inchesdenom or 1)
    return feet * 12.0 + inches

rawDescription: How to convert a measurement displayed in an architectural format to a floating point?

description: Convert a measurement displayed in an architectural format to a floating point


code:
date = datetime.now().strftime('%m/%d/%y %H:%M:%S')

with open("capec_dictionary.txt", "a") as text_file:
    template = '{:24s} {:24s} {:18s}\n'
    text_file.write(template.format('Pass', 'Encryption', 'Date'))

    writePass = finalPass.translate(passSwap)
    text_file.write(template.format(finalPass, writePass, date))

rawDescription: Formatting multiple columns of data in a text file


code:
newest = None
for message in md.itervalues():
   if newest == None or message.get_date() > newest.get_date():
      newest = message
# now newest should contain the newest message

rawDescription: Maildir - open latest email and reply to sender


code:
from email.utils import make_msgid

msg['Message-ID'] = make_msgid()

rawDescription: How can I fetch the SMTP headers after sending email?

description: Fetch the SMTP headers after sending email


code: ret = pickle.loads(ret.data)

rawDescription: TypeError: a bytes-like object is required, not 'Binary'


code:
import os.path, shutil

def remove_ext(arg, dirname, fnames):
    argfiles = (os.path.join(dirname, f) for f in fnames if f.endswith(arg))
    for f in argfiles:
        shutil.move(f, f[:-len(arg)])

os.path.walk('/some/path', remove_ext, '.tex')

rawDescription: removing extensions in subdirectories

description: Removing extensions in subdirectories


code:
a = [1,6,5,None,5,None,None,1]
b = [x for x in a if x is not None]
c = [2,12,10,10,2]  # just an example

v = iter(c)
[None if x is None else next(v) for x in a]

rawDescription: filter a list in Python, then unfilter it

description: Filter a list in Python, then unfilter it


code:
if(len(x)==5):
    break

rawDescription: How to get userinput values to a list using stdin

description: Get userinput values to a list using stdin


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

x = np.linspace(0, 1, 100)
y = np.sin(2*np.pi * x)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'o')
ax.set_xlim(-0.2, 1.2)
ax.set_ylim(-1.5, 1.5)

x_ticks = ax.get_xticks()
y_ticks = ax.get_yticks()
# use len(x_ticks)-1 number of colors
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'orange']
for i, x_tick in enumerate(x_ticks[:-1]):
    ax.text(x_tick+0.03, y_ticks[0]-0.165, "text %i"%i,
            bbox={'fc':colors[i], 'pad':10})

rawDescription: Adding colored boxes to axes in Python's matplotlib


code:
from collections import defaultdict
from itertools import permutations

PRIMES = list(gen_primes(256)) # some arbitrary prime generator

def get_dict(path):
    res = defaultdict(list)
    with open(path, "r") as file:
        for line in file.readlines():
            word = line.strip().upper()
            hash = compute_hash(word)
            res[hash].append(word)
    return res

def compute_hash(word):
    hash = 1
    for char in word:
        try:
            hash *= PRIMES[ord(char) - ord(' ')]
        except IndexError:
            # contains some character out of range - always 0 for our purposes
            return 0
    return hash

def get_result(path, given_word):
    words = get_dict(path)
    given_word = given_word.upper()
    result = set()
    powerset = lambda x: powerset(x[1:]) + [x[:1] + y for y in powerset(x[1:])] if x else [x]
    for word in (word for word in powerset(given_word) if len(word) >= 4):
        hash = compute_hash(word)
        for equiv in words[hash]:
            result.add(equiv)
    return result

if __name__ == '__main__':
    path = "dict.txt"
    given_word = "textbook"
    result = get_result(path, given_word)
    print(result)

rawDescription: How many common English words of 4 letters or more can you make from the letters of a given word (each letter can only be used once)


code: pos_int = self.player.query_position(gst.FORMAT_TIME, None)[0]

rawDescription: How to extract the bitrate and other statistics of a video file with Python

description: Extract the bitrate and other statistics of a video file with Python


rawDescription: Non-capturing optional URL elements in Django


code:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy import spatial

a = ['hello world', 'my name is', 'what is your name?']
b = ['my name is', 'hello world', 'my name is what?']

df = pd.DataFrame(data={'a':a, 'b':b})
df['ab'] = df.apply(lambda x : x['a'] + ' ' + x['b'], axis=1)

clf = TfidfVectorizer(ngram_range=(1, 1))
clf.fit(df['ab'])

tfidf_a = clf.transform(df['a']).todense()
tfidf_b = clf.transform(df['b']).todense()

row_similarities = [1 - spatial.distance.cosine(tfidf_a[x],tfidf_b[x]) for x in range(len(tfidf_a)) ]
row_similarities

[0.0, 0.0, 0.72252389079716417]

rawDescription: Cosine similarity using TFIDF

description: Cosine similarity using TFIDF


code:
df['min_date'] = df.groupby('two')['ts'].transform("min")
df

rawDescription: python pandas: Keeping earliest data in new column when grouping data

description: Python pandas: Keeping earliest data in new column when grouping data


code:
list_1 = [1, 2, 3, 4, 5, 6]
list_2 = [1, 2, 3, 0, 5, 6]

# Print all items from list_1 that are not in list_2 ()
print(*[item for item in list_1 if item not in list_2], sep='\n')

# Print all items from list_1 that differ from the item at the same index in list_2
print(*[x for x, y in zip(list_1, list_2) if x != y], sep='\n')

# Print all items from list_2 that differ from the item at the same index in list_1
print(*[y for x, y in zip(list_1, list_2) if x != y], sep='\n')

rawDescription: Python - Compare two lists in a comprehension


rawDescription: How to keep first two duplicates in a pandas dataframe?

description: Keep first two duplicates in a pandas dataframe


code:
class MainForm(Form):
    def __init__(self):
        self.InitializeComponent()
        appset = AppSettings();
        self._propertyGrid1.SelectedObject = appset

    def InitializeComponent(self):
        self._propertyGrid1 = System.Windows.Forms.PropertyGrid()

class AppSettings():
    def __init__(self):
        self.saveOnClose = True
    def saveOnClose(self):
        return self.saveOnClose

rawDescription: Creating and Populating a Porperty Grid - Iron Python


code:
def pmv(nums):
    chunklen=6
    res = dict()
    res[0] = ()
    for i in xrange(0, len(nums), chunklen):
        part = plus_minus_variations(nums[i:i+chunklen])
        resnew = dict()
        for (i,j) in itertools.product(res, part):
            resnew[i + j] = tuple(list(res[i]) + list(part[j]))
        res = resnew
    return res

rawDescription: Find the numbers that can be made with addition and subtraction, using all numbers given


code:
while not done:
    # --- Main event loop
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done = True # Flag that we are done so we exit this loop

    # --- Game logic should go here
    a+=1
    b+=1
    # --- Drawing code should go here

    # First, clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.
    screen.blit(floor, [0,0])
    screen.blit(cat, [a,b])
    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()
    pygame.display.update()
    # --- Limit to 60 frames per second
    clock.tick(60)

rawDescription: Screen.blit doesnt work unless keydown

description: Screen.blit doesnt work unless keydown


code:
setup(
        windows=['myscript.py'],
        options={
                "py2exe":{
                        "unbuffered": True,
                        "optimize": 2,
                }
        }
)

rawDescription: Compiling with Py2Exe - Black Box Error

description: Compiling with Py2Exe - Black Box Error


code:
from Bio import SeqIO

with open("outfile.txt","w") as f:
        for seq_record in SeqIO.parse("infile.fasta", "fasta"):
                f.write(str(seq_record.id) + "\n")
                f.write(str(seq_record.seq[:10]) + "\n")  #first 10 base positions
                f.write(str(seq_record.seq[-10:]) + "\n") #last 10 base positions

rawDescription: Using Biopython (Python) to extract sequence from FASTA file


code:
# You could use tempfile.NamedTemporaryFile. But I will leave that to you:
mask = np.memmap(tempfile, shape=source_array.shape, dtype=bool, mode='w+')
np.greater_equal(source_array, 255.0, out=mask)

rawDescription: Can I make a numpy memory mapped mask?

description: Make a numpy memory mapped mask


code:
from views import function1, function2

def a_function_one():
   ...
   #call function1 from views
   function1()

rawDescription: Issues with functions in django

description: Issues with functions in django


code:
post_list = SortedDict([(obj.id, obj) for obj in posts])
# reversing the post order in-place
post_list.keyOrder.reverse()

rawDescription: Python: Element order in dictionary

description: Python: Element order in dictionary


code:
import xml.etree.ElementTree as et

doc = """
  Textline1

  Textline2

  Textline3

"""

e = et.fromstring(doc)

items = []
for x in e.getiterator():
    if x.text is not None:
        items.append(x.text.strip())
    if x.tail is not None:
        items.append(x.tail.strip())

doc2 = et.Element("lines")
for i in items:
    l=et.SubElement(doc2, "line")
    l.text = i

print(et.tostring(doc2))

rawDescription: Parse text of element with empty element inside


code:
from django.core import validators

class StepTwoForm(forms.Form):
    number = forms.CharField()

    def __init__(self, *args, **kwargs):
        config = kwargs.pop('config', {})
        super(StepTwoForm, self).__init__(*args, **kwargs)
        if 'MAX_LENGTH' in config:
            validator = validators.MaxLengthValidator(config['MAX_LENGTH'])
            self.fields['number'].validators.append(validator)

rawDescription: Setting max_length of a form field using a parameter in Django


code:
import os
...

result = 'xml'

html = ''
html += ''
html += ''
html += '
Result
'
html += 'Back'
html += '
'
html += 'Result:'
html += '<textarea name="result" readonly>' + result + '</textarea>'
html += '<form method="POST">'
html += '
'
html += '<textarea name="content" placeholder="Enter a comment"></textarea>'
html += '

'
html += '<input type="submit" name="export" value="Save">'
html += '</form>'
html += '
'
html += ''
html += ''

# OUTPUT HTML PAGE
file = open('WebPage.html', 'w')
file.write(html)
file.close()

# OUTPUT PDF PAGE
os.system('/path/to/wkhtmltopdf /path/to/WebPage.html /path/to/WebPage.pdf')

rawDescription: Saving a webpage as PDF using Python?

description: Saving a webpage as PDF using Python


rawDescription: Vectorized Computation of Compositional Variance


code:
keys = {"hello":{"postfix":"bonjour", "count":0},
        "hi":{"postfix":"kiss", "count":0}}

frequencies = ["hello","hi","hello","hello"]

for item in frequencies:
    keys[item]["count"] += 1

print('
')
for k,v in keys.items():
    print("
{0}	{1}	{2}
"
          .format(k, v["count"], v["postfix"]))
print('
')

rawDescription: How can we add new list so that they are in the same row but different column with the dict in table html?


code: candidates[:] = filter(candidate.__ne__, candidates)

rawDescription: Python - Why is my list not being modified outside the scope of this method? How do I modify my code so that it is?


code:
import numpy as np

A = np.array(['b', 'c', 'e', 'd', 'a'])
B = np.array(['a', 'd', 'c', 'b', 'e'])

P = np.empty(len(A), int)
P[B.argsort()] = A.argsort()

rawDescription: Given rearrangements A and B, compute P such that A[P] == B


code:
from reportlab.pdfgen import canvas

def hello(c):
    from reportlab.lib.units import inch

    #First Example
    c.setFillColorRGB(255,0,0) #choose your font colour
    c.setFont("Helvetica", 30) #choose your font type and font size
    c.drawString(100,100,"Hello World") # write your text

    #Second Example
    c.setStrokeColorRGB(0,255,0.3) #choose your line color
    c.line(2,2,2*inch,2*inch)

    #Third Example
    c.setFillColorRGB(1,1,0) #choose fill colour
    c.rect(4*inch,4*inch,2*inch,3*inch, fill=1) #draw rectangle

c = canvas.Canvas("hello.pdf")

hello(c)
c.showPage()
c.save()

rawDescription: How to change text/font color in reportlab.pdfgen

description: Change text/font color in reportlab.pdfgen


rawDescription: How to have a 'broad filter' in SQLAlchemy query search

description: Have a 'broad filter' in SQLAlchemy query search


code:
import re

contents_of_each = re.findall('{([^}]+?)}', txt, re.DOTALL)

rawDescription: Using python to treat a .txt file as a large string, and iterate over each {} in the file


rawDescription: SQL output to list

description: SQL output to list


code:
def clone_entity(e, to_klass, **extra_args):
  """Clones an entity, adding or overriding constructor attributes.

  The cloned entity will have exactly the same property values as the original
  entity, except where overridden. By default it will have no parent entity or
  key name, unless supplied.

  Args:
    e: The entity to clone
    extra_args: Keyword arguments to override from the cloned entity and pass
      to the constructor.
  Returns:
    A cloned, possibly modified, copy of entity e.
  """
  klass = e.__class__
  props = dict((k, v.__get__(e, klass)) for k, v in klass.properties().iteritems())
  props.update(extra_args)
  return to_klass(**props)

# Use the clone method
query = db.GqlQuery("SELECT * FROM OrigKind")
results = query.fetch(10);

for user in results:
    new_entry = clone_entity(user, NewKind)
    new_entry.put()

rawDescription: How to COPY all entities in a Kind in GAE to another Kind without explicitly calling out each property


rawDescription: Python slice list at n and take the next x elements?


rawDescription: Why do I get rows of zeros in my 2D fft?

description: Why do I get rows of zeros in my 2D fft


code:
def new_id_factory():
    if not('_MYTABLE_ID_' in globals()):
        q = db.execute("select max(mytable.id) as max_id from mytable").fetchone()
        _MYTABLE_ID_ = (q and q.max_id) or 0
    _MYTABLE_ID_ += 1
    return _MYTABLE_ID_

t = Table("mytable", Base.metadata,
    Column('id', Integer, primary_key=True, default=new_id_factory), #
    autoload=True, autoload_with=db,
    )

rawDescription: How to specify the primary id when inserting rows with sqlalchemy when id dos not have autoincrement?

description: Specify the primary id when inserting rows with sqlalchemy when id dos not have autoincrement


code:
punctuation = '''!$%*()_-=+\/.,><:;'"?|'''
allowed = string.digits + string.letters + punctuation
filter(allowed.__contains__, s)

rawDescription: Remove characters not in a set in Python


code:
time_before = time.time()
sock.connect((self.host, self.port))
result = time.time() - time_before
sock.close()

rawDescription: How to choose closest/fastest mirror in Python?

description: Choose closest/fastest mirror in Python


code:
from Tkinter import * # from tkinter import * (In Python 3.x)

root = Tk()
root.geometry('3000x3000+-100+-100')
root.mainloop()

rawDescription: Tkinter window outside desktop

description: Tkinter window outside desktop


code:
data = data.reshape(81, 201, 3)
x = data[...,0]
y = data[...,1]
z = data[...,2]

CS = plt.contourf(x,y,z,200,cmap=plt.cm.jet,rasterized=True)
plt.colorbar()

plt.show()

rawDescription: Strange behavior of matplotlib's griddata


rawDescription: How to locate an element by class name and its text in python selenium

description: Locate an element by class name and its text in python selenium


code:
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'django_openid_auth.auth.OpenIDBackend',
    )

rawDescription: Django Multiple Authentication Backend for one project, HOW?


rawDescription: Pandas Series fillna with default date

description: Pandas Series fillna with default date


code:
import subprocess

p = subprocess.Popen(['./script.sh', '-p', '1234'],
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate(input='password\nauth username\nauth password\n')

rawDescription: Python os.system() input text to script

description: Python os.system() input text to script


code:
import wx

class Prototype(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, None, size=(550,300))

        self.InitUI()
        self.Centre()
        self.Show()
    #define User Interface
    def InitUI(self):
        self.panel1 = wx.Panel(self, -1)

        #Static Text
        s_text1 = wx.StaticText(self.panel1, -1, "Hello World!", (10,5)) #top text
        self.s_text2 = wx.TextCtrl(self.panel1, style=wx.TE_READONLY | wx.NO_BORDER, pos=(300,10)) #top text
        self.s_text2.AppendText("gray")
        self.s_text2.SetBackgroundColour("gray")
if __name__ == '__main__':
    app = wx.App()
    Prototype(None, title='')
    app.MainLoop()

rawDescription: how to control background color of a square of a panel on wxPython?

description: Control background color of a square of a panel on wxPython


code:
from fnmatch import fnmatch
l1 = ['test1', 'test2', 'test3', 'test4', 'test5']
l2 = set(['*t1*', '*t4*'])
[x for x in l1 if not any(fnmatch(x, p) for p in l2)]

rawDescription: How to filter list based on another list containing wildcards?

description: Filter list based on another list containing wildcards


code:
def __iter__(self):
    return self.bits.itersearch(bitarray([True]))

rawDescription: Create a list like object using a bitarray


code:
li = [1,2,3,4000,5,6,7,8,9000,10,11,12,1300]
r = [[]]  # start with a list containing an empty sub-list
for i in li:
  if i >= 2000:
    # start a new sub-list when we see a big value
    r.append([i])
  else:
    # append to the last sub-list of r
    r[-1].append(i)

rawDescription: Python: Split a list into nested list at points where item matches criteria


code:
_uppercase = [k for k in dir() if k.isupper()]
ALL_UNICODE = ' '.join(map(globals().get, _uppercase))

rawDescription: Concatenating all strings in a module

description: Concatenating all strings in a module